Merging PDFs in Node

19,434

Solution 1

What do you expect to get when you do Buffer.concat([pdf1, pdf2])? Just by concatenating two PDFs files you won’t get one containing all pages. PDF is a complex format (basically one for vector graphics). If you just added two JPEG files you wouldn’t expect to get a big image containing both pictures, would you?

You’ll need to use an external library. https://github.com/wubzz/pdf-merge might work for instance.

Solution 2

HummusJS is another PDF manipulation library, but without a dependency on PDFtk. See this answer for an example of combining PDFs in Buffers.

Share:
19,434
mertje
Author by

mertje

Expert at building sloppy solutions.

Updated on July 28, 2022

Comments

  • mertje
    mertje almost 2 years

    Hi i'm trying to merge pdf's of total of n but I cannot get it to work.

    I'm using the Buffer module to concat the pdf's but it does only apply the last pdf in to the final pdf.

    Is this even possible thing to do in node?

    var pdf1 = fs.readFileSync('./test1.pdf');
    var pdf2 = fs.readFileSync('./test2.pdf');
    
    fs.writeFile("./final_pdf.pdf", Buffer.concat([pdf1, pdf2]), function(err) {
        if(err) {
            return console.log(err);
        }
    
        console.log("The file was saved!");
    });
    

    There are currently some libs out there but they do all depend on either other software or programming languages.

  • Gabriel Garrett
    Gabriel Garrett over 5 years
    This is important for those people using services like Firebase that don't allow the installation of PDFtk
  • Daud khan
    Daud khan about 5 years
    Is it possible to merge 7 Pdfs?
  • phil294
    phil294 about 4 years
    HummusJS is now unsupported. Prebuilt binaries are already missing and I couldnt get it to run on first try