Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs: merging pdf streams \ buffers

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.

like image 651
Oren Schwartz Avatar asked Jul 18 '16 11:07

Oren Schwartz


1 Answers

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);
  });
like image 128
cienki Avatar answered Sep 25 '22 00:09

cienki