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

Gists

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

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 1

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

  // Load pdf-lib
  const cdnjs = "https://cdn.jsdelivr.net/npm/pdf-lib/dist/pdf-lib.min.js";
  eval(UrlFetchApp.fetch(cdnjs).getContentText().replace(/setTimeout\(.*?,.*?(\d*?)\)/g, "Utilities.sleep($1);return t();"));

  // Merge PDFs.
  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"));
}

Sample script 2: Added on November 26, 2023

From this discussion, it seems that the following script can be used for merging PDF files.

Here, I noticed that when the large PDF data is used, an error of The JavaScript runtime exited unexpectedly. occurs in the method of Utilities.newBlob for converting the byte array to Blob. In that case, I confirmed that when the below script is used, the error could be avoided.

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

  // Load pdf-lib
  const cdnjs = "https://cdn.jsdelivr.net/npm/pdf-lib/dist/pdf-lib.min.js";
  eval(UrlFetchApp.fetch(cdnjs).getContentText().replace(/setTimeout\(.*?,.*?(\d*?)\)/g, "Utilities.sleep($1);return t();"));

  // Merge PDFs.
  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, pdfData.getPageIndices());
    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"));
}

References

 Share!