Merge multiple PDFs into a single file without sending it to some unknown server 🤖

Open merge-pdfs in Script Kit

// 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}`));

Note: This does not support encrypted files.