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

前端 未结 3 590
轮回少年
轮回少年 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 09:13

    As mentioned by @MechaCode, the creator has ended support for HummusJS.

    So I would like to give you 2 solutions.

    1. Using node-pdftk npm module

      The Following sample code uses node-pdftk npm module to combine two pdf buffers seamlessly.

      const pdftk = require('node-pdftk');
      
      var pdfBuffer1 = fs.readFileSync("./pdf1.pdf");
      var pdfBuffer2 = fs.readFileSync("./pdf2.pdf");
      
      pdftk
          .input([pdfBuffer1, pdfBuffer2])
          .output()
          .then(buf => {
              let path = 'merged.pdf';
              fs.open(path, 'w', function (err, fd) {
                  fs.write(fd, buf, 0, buf.length, null, function (err) {
                      fs.close(fd, function () {
                          console.log('wrote the file successfully');
                      });
                  });
              });
          });
      

      The requirement for node-pdftk npm module is you need to install the PDFtk library. Some of you may find this overhead / tedious. So I have another solution using pdf-lib library.

    2. Using pdf-lib npm module

      const PDFDocument = require('pdf-lib').PDFDocument
      
      var pdfBuffer1 = fs.readFileSync("./pdf1.pdf"); 
      var pdfBuffer2 = fs.readFileSync("./pdf2.pdf");
      
      var pdfsToMerge = [pdfBuffer1, pdfBuffer2]
      
      const mergedPdf = await PDFDocument.create(); 
      for (const pdfBytes of pdfsToMerge) { 
          const pdf = await PDFDocument.load(pdfBytes); 
          const copiedPages = await mergedPdf.copyPages(pdf, pdf.getPageIndices());
          copiedPages.forEach((page) => {
               mergedPdf.addPage(page); 
          }); 
      } 
      
      const buf = await mergedPdf.save();        // Uint8Array
      
      let path = 'merged.pdf'; 
      fs.open(path, 'w', function (err, fd) {
          fs.write(fd, buf, 0, buf.length, null, function (err) {
              fs.close(fd, function () {
                  console.log('wrote the file successfully');
              }); 
          }); 
      }); 
      
      

    Personally I prefer to use pdf-lib npm module.

提交回复
热议问题