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

前端 未结 3 589
轮回少年
轮回少年 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条回答
  •  猫巷女王i
    2020-12-28 08:58

    Here's what we use in our Express server to merge a list of PDF blobs.

    const { PDFRStreamForBuffer, createWriterToModify, PDFStreamForResponse } = require('hummus');
    const { WritableStream } = require('memory-streams');
    
    // Merge the pages of the pdfBlobs (Javascript buffers) into a single PDF blob                                                                                                                                                                  
    const mergePdfs = pdfBlobs => {
      if (pdfBlobs.length === 0) throw new Error('mergePdfs called with empty list of PDF blobs');
      // This optimization is not necessary, but it avoids the churn down below                                                                                                                                                
      if (pdfBlobs.length === 1) return pdfBlobs[0];
    
      // Adapted from: https://stackoverflow.com/questions/36766234/nodejs-merge-two-pdf-files-into-one-using-the-buffer-obtained-by-reading-them?answertab=active#tab-top                                                     
      // Hummus is useful, but with poor interfaces -- E.g. createWriterToModify shouldn't require any PDF stream                                                                                                              
      // And Hummus has many Issues: https://github.com/galkahana/HummusJS/issues                                                                                                                                              
      const [firstPdfRStream, ...restPdfRStreams] = pdfBlobs.map(pdfBlob => new PDFRStreamForBuffer(pdfBlob));
      const outStream = new WritableStream();
      const pdfWriter = createWriterToModify(firstPdfRStream, new PDFStreamForResponse(outStream));
      restPdfRStreams.forEach(pdfRStream => pdfWriter.appendPDFPagesFromPDF(pdfRStream));
      pdfWriter.end();
      outStream.end();
      return outStream.toBuffer();
    };
    
    module.exports = exports = {
      mergePdfs,
    };
    

提交回复
热议问题