PDFKit, nodeJS merging two PDF files

隐身守侯 提交于 2019-12-07 12:22:57

问题


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:


It is not possible to merge two PDF documents with pdfkit!

You can use pdftk Server for that purpose. The program offers a command line interface, which could merge two pdfs with the following command:

pdftk 1.pdf 2.pdf cat output merged.pdf



回答2:


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.



来源:https://stackoverflow.com/questions/25640533/pdfkit-nodejs-merging-two-pdf-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!