5

pdf-merge provides an api for merging pdf files, but it falls short when trying to merge buffers or streams. When trying to merge these buffers in the standard manner or via packages (aka Buffer.concat, stream-concat, buffer-concat) the result only includes the last stream instead of a merged result.

As it seems, more people encountered this issue, but no solution was provided (example :NodeJS: Merge two PDF files into one using the buffer obtained by reading them)

I guess this is due to the unique representation of a pdf file.

I also tried pdfkit's addContent(buffer) but the result is an empty file and apparently it is not supported (https://github.com/devongovett/pdfkit/issues/417).

Did anyone experience this issue and made it work ? We must use streams for performance issues (so mitigating via files is not an option).

Thanks.

Community
  • 1
  • 1
Oren Schwartz
  • 103
  • 1
  • 7
  • 1
    Possible duplicate of [NodeJS: Merge two PDF files into one using the buffer obtained by reading them](https://stackoverflow.com/questions/36766234/nodejs-merge-two-pdf-files-into-one-using-the-buffer-obtained-by-reading-them) – Geek Guy Jan 17 '19 at 20:48

1 Answers1

5

I found node-pdftk to be of great use for this. By simply passing an array of buffers as input and then immediately turning it into output, you should get a combined set of PDFs.

npm i node-pdftk

const pdfs = [...] // array of PDF buffers

pdftk
  .input(pdfs)
  .output()
  .then(buf => {
    res.type('application/pdf');
    res.send(buf);
  });
cienki
  • 1,639
  • 1
  • 16
  • 14