NodeJS: Merge two PDF files into one using the buffer obtained by reading them

前端 未结 3 564
轮回少年
轮回少年 2020-12-28 08:18

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

3条回答
  •  醉梦人生
    2020-12-28 08:56

    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);
    

提交回复
热议问题