-
-
Save ZReC/add0e9e546f5e29731d47b80cddbd4cb to your computer and use it in GitHub Desktop.
Approach to combine pairs of landscape pdf pages into A4 ones, using Deno and pdf-lib. Page count will be at most half + 1.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
PageSizes, | |
PDFDocument, | |
PDFEmbeddedPage, | |
} from "https://cdn.skypack.dev/pdf-lib@1.17.1?dts"; | |
interface FitPage { | |
page: PDFEmbeddedPage; | |
new_dims: { | |
width: number; | |
height: number; | |
}; | |
} | |
const pdf_out = await PDFDocument.create(); | |
const pages = await pdf_out.embedPages( | |
(await PDFDocument.load(await Deno.readFile(Deno.args[0]))).getPages(), | |
); | |
const [width, height] = PageSizes.A4; | |
let currentPage = 0; | |
while (currentPage <= pages.length - 1) { | |
const out_page = pdf_out.addPage(PageSizes.A4); | |
const fit_pages: Array<FitPage> = []; | |
for (let i = 0; i < 2; i++) { | |
const page = pages[currentPage + i]; | |
if (page) { | |
const size = page.size(); | |
const scaling_ratio = Math.min( | |
width / size.width, | |
height * .5 / size.height, | |
); | |
const new_dims = page.scale(scaling_ratio); | |
fit_pages.push({ page, new_dims }); | |
} | |
} | |
currentPage += 2; | |
fit_pages.forEach(({ page, new_dims }, idx) => { | |
out_page.drawPage(page, { | |
x: (width - new_dims.width) / 2, | |
y: (idx % 2 ? 0 : height / 2) + (height / 2 - new_dims.height) / 2, | |
width: new_dims.width, | |
height: new_dims.height, | |
}); | |
}); | |
} | |
Deno.writeFile(`new_${Deno.args[0]}.pdf`, await pdf_out.save()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
deno run --allow-read --allow-write .ts input.pdf