NodeJS:使用通过读取文件获得的缓冲区将两个PDF文件合并为一个文件 [英] NodeJS: Merge two PDF files into one using the buffer obtained by reading them

查看:621
本文介绍了NodeJS:使用通过读取文件获得的缓冲区将两个PDF文件合并为一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用fill-pdf npm模块来填充模板pdf,它会创建一个新文件,该文件将从磁盘读取,并作为缓冲区返回回调.我有两个文件,我对其执行相同的操作.我想在那里合并两个缓冲区,以形成一个单独的pdf文件,我可以将其发送回客户端.我尝试了不同的缓冲区串联方法.可以使用Buffer.concat将缓冲区连接起来,例如

I am using fill-pdf npm module for filling template pdf's and it creates new file which is read from the disk and returned as buffer to callback. I have two files for which i do the same operation. I want to combine the two buffers there by to form a single pdf file which i can send back to the client. I tried different methods of buffer concatenation. The buffer can be concatenated using Buffer.concat, like,

var newBuffer = Buffer.concat([result_pdf.output, result_pdf_new.output]);

新缓冲区的大小也是输入缓冲区的大小之和.但是,当newBuffer作为响应发送到客户端时,它仅显示数组最后一个提到的文件.

The size of new buffer is also the sum of the size of the input buffers. But still when the newBuffer is sent to client as response, it shows only the file mentioned last in the array.

res.type("application/pdf");
return res.send(buffer);

有什么主意吗?

推荐答案

HummusJS 支持使用其PDF组合 appendPDFPagesFromPDF 方法

HummusJS supports combining PDFs using its appendPDFPagesFromPDF method

使用流与缓冲区配合使用的示例:

Example using streams to work with buffers:

const hummus = require('hummus');
const memoryStreams = require('memory-streams');

/**
 * Concatenate two PDFs in Buffers
 * @param {Buffer} firstBuffer 
 * @param {Buffer} secondBuffer 
 * @returns {Buffer} - a Buffer containing the concactenated PDFs
 */
const combinePDFBuffers = (firstBuffer, secondBuffer) => {
    var outStream = new memoryStreams.WritableStream();

    try {
        var firstPDFStream = new hummus.PDFRStreamForBuffer(firstBuffer);
        var secondPDFStream = new hummus.PDFRStreamForBuffer(secondBuffer);

        var pdfWriter = hummus.createWriterToModify(firstPDFStream, new hummus.PDFStreamForResponse(outStream));
        pdfWriter.appendPDFPagesFromPDF(secondPDFStream);
        pdfWriter.end();
        var newBuffer = outStream.toBuffer();
        outStream.end();

        return newBuffer;
    }
    catch(e){
        outStream.end();
        throw new Error('Error during PDF combination: ' + e.message);
    }
};

combinePDFBuffers(PDFBuffer1, PDFBuffer2);

这篇关于NodeJS:使用通过读取文件获得的缓冲区将两个PDF文件合并为一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆