Merging Multiple PDF Files as a Single PDF File using Google Apps Script

Gists

This is a sample script for merging multiple PDF files as a single PDF file using Google Apps Script.

In this sample script, pdf-lib is used. In the current stage, it seems that this Javascript can be directly used with Google Apps Script.

Sample script

As a sample situation, please put multiple PDF files in your Google Drive. This sample merges those PDF files as a single PDF file.

async function myFunction() {
  // Retrieve PDF data.
  const ids = ["###fileId1###", "###fileId2###", "###fileId3###", , ,]; // Please set the file IDs of your PDF files.
  const data = ids.map((id) => new Uint8Array(DriveApp.getFileById(id).getBlob().getBytes()));

  // Merge PDFs.
  const cdnjs = "https://cdn.jsdelivr.net/npm/pdf-lib/dist/pdf-lib.min.js";
  eval(UrlFetchApp.fetch(cdnjs).getContentText()); // Load pdf-lib
  const setTimeout = function(f, t) {
    Utilities.sleep(t);
    return f();
  }
  const pdfDoc = await PDFLib.PDFDocument.create();
  for (let i = 0; i < data.length; i++) {
    const pdfData = await PDFLib.PDFDocument.load(data[i]);
    const pages = await pdfDoc.copyPages(pdfData, [...Array(pdfData.getPageCount())].map((_, i) => i));
    pages.forEach(page => pdfDoc.addPage(page));
  }
  const bytes = await pdfDoc.save();

  // Create a PDF file.
  DriveApp.createFile(Utilities.newBlob([...new Int8Array(bytes)], MimeType.PDF, "sample2.pdf"));
}
  • When this script is run, the PDF files of ids are merged as a single PDF file and it is created in the root folder.

  • If you want to use the downloaded multiple PDF files, please modify the above script as follows.

    • From

      const ids = ["###fileId1###", "###fileId2###", "###fileId3###", , ,]; // Please set the file IDs of your PDF files.
      const data = ids.map((id) => new Uint8Array(DriveApp.getFileById(id).getBlob().getBytes()));
      
    • To

      const urls = ["###url1###", "###url2###", "###url3###", , ,]; // Please set the URLs of your PDF files.
      const data = urls.map((url) => new Uint8Array(UrlFetchApp.fetch(url).getContent()));
      

References

 Share!