Created
September 12, 2022 23:04
-
-
Save kseikyo/49c61b77bfd1265d2e5cf37e69dfd012 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Name: Merge pdfs | |
// Author: Lucas Sierota | |
// Description: Merge multiple pdfs into one | |
// Dependencies: pdf-lib | |
import "@johnlindquist/kit"; | |
import fs from "fs/promises"; | |
const { PDFDocument } = await npm("pdf-lib"); | |
let name = await selectFile("Select a PDF file to merge"); | |
const paths = [name]; | |
// keep adding paths until there's no input | |
while ( | |
(await arg({ | |
placeholder: "Select another?", | |
hint: `Press only y or n? [y]/[n]`, | |
})) === "y" | |
) { | |
name = await selectFile("Select another PDF file to merge"); | |
if (name !== "") paths.push(name); | |
} | |
// merge the pdfs | |
const pdfsToMerge = await Promise.all( | |
paths.map(async (path) => await fs.readFile(path)) | |
); | |
let finalPath = await selectFolder("Select a folder to save the merged PDF"); | |
let finalName = await arg("Enter a name for the merged PDF"); | |
finalPath = `${finalPath}${finalName}.pdf`; | |
try { | |
const mergedPdf = await PDFDocument.create(); | |
for (const pdfBytes of pdfsToMerge) { | |
const pdf = await PDFDocument.load(pdfBytes); | |
const copiedPages = await mergedPdf.copyPages(pdf, pdf.getPageIndices()); | |
copiedPages.forEach((page) => { | |
mergedPdf.addPage(page); | |
}); | |
} | |
const buf = await mergedPdf.save(); // Uint8Array | |
let exists = await pathExists(finalPath); | |
if (!exists) { | |
await writeFile(finalPath, buf); | |
} else { | |
await div(md(`The path ${finalPath} already exists`)); | |
} | |
} catch (e) { | |
log(`Error: ${e}`); | |
await div(md(`Error: ${e}`)); | |
} | |
await div(md(`Merged PDF saved to ${finalPath}`)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment