DEV Community

Visakh Vijayan
Visakh Vijayan

Posted on

Merging PDFs in NodeJs

public static async mergeProposalPDFs(frontURL: string, backURL: string): Promise<Buffer> {
    const pdfDoc = await PDFDocument.create();

    const pdf1Data = await fetch(frontURL).then((res) => res.arrayBuffer());
    const pdf1 = await PDFDocument.load(pdf1Data);
    const copiedPages1 = await pdfDoc.copyPages(pdf1, pdf1.getPageIndices());
    copiedPages1.forEach((page) => pdfDoc.addPage(page));

    const pdf2Data = await fetch(backURL).then((res) => res.arrayBuffer());
    const pdf2 = await PDFDocument.load(pdf2Data);
    const copiedPages2 = await pdfDoc.copyPages(pdf2, pdf2.getPageIndices());
    copiedPages2.forEach((page) => pdfDoc.addPage(page));

    // Save the merged PDF to a new buffer
    const mergedPdfFile = await pdfDoc.save();

    return Buffer.from(mergedPdfFile);
  }
Enter fullscreen mode Exit fullscreen mode

The function takes in two PDF urls and returns a buffer. In our case we wanted it to be uploaded further to s3.

Top comments (0)