PDFKit, nodeJS merging two PDF files

2019-05-19 15:24发布

问题:

does anyone have experience with PDFKit with NodeJS. Specifically, I'm trying to merge 2 PDF documents into 1, but I can't seem seem to get the content of the two PDFs properly with formatting inside the merged one.

Here's what I do:

var PDFDocument = require('pdfkit');
var fs = require('fs');

var doc = new PDFDocument();
var fileName = 'test.pdf';
doc.pipe(fs.createWriteStream(fileName));

var file1 = '1.pdf';
var file2 = '2.pdf';

var stream1 = fs.createReadStream(file1);
doc.text(stream1);

doc.addPage();
var stream2 = fs.createReadStream(file2);
doc.text(stream2);

doc.end();

The output, that being test.pdf, should consist of a single pdf containing the contents of the 2 pdfs with the same formatting, but I'm only getting test.pdf with 2 pages, each consisting of a single line of "[Object object]". I can't seem to find how to redirect the content of the stream inside the doc.text() function.

Any idea on what I do wrong, how should I fix it?

回答1:

var stream1 = fs.createReadStream(file1);

stream1.on('data', function(chunk) {
    console.log('got %d bytes of data', chunk.length);
    doc.contentStream(chunk);
});

stream1.on('end', function() {
    console.log('DONE with file1!!');
    doc.addPage();

    // now time to create and read from next stream.

});

You were creating the streams and writing the stream objects to the file. Instead you should write the data you read from the stream. But this won't be merging the files since you are reading the pdf markup and writing it as text to the next.