Merging PDF Files in Google Drive using Google Apps Script

Salimkamboh
3 min readAug 26, 2023

We often need to merge multiple PDF files into one for various reasons. While on local machine we can use any tool, in Google Drive it can be challenging. Google Apps Script, along with the PDF-Lib library, provides a convenient way to achieve this.

Lets do it step by step. In this exercise we will merge pdf files in a directory to a single file.

  1. Login to Google Drive
  2. Click New -> More -> Google Apps Script. A new tab will open an editor with a placeholder function already written.

3. We need folder if for the specific folder. For that right click folder in google drive. Click Share -> Get Link. Click on Copy Link button on next screen. The link will be similar to https://drive.google.com/drive/folders/101g52HffUw_7676752ZJ5L8wEBkq1i?usp=share_link. 101g52HffUw_7676752ZJ5L8wEBkq1i is our required folder id in this case. Lets write it to our google apps script as

var folderId = '101g52HffUw_7676752ZJ5L8wEBkq1i';

4. Lets get folder handle and files in the folder:

var folder = DriveApp.getFolderById(folderId);
var files = folder.getFiles();

5. Fetch the PDF-lib library’s JavaScript code from a CDN and then execute it using the eval() function, effectively making the library's functions and classes available in your Google Apps Script environment. This enables you to use PDF-lib's functionalities to work with PDF documents within your script. After that create a handle to PDF-lib library.

const cdnjs = "https://cdn.jsdelivr.net/npm/pdf-lib/dist/pdf-lib.min.js";
eval(UrlFetchApp.fetch(cdnjs).getContentText());
const pdfDoc = await PDFLib.PDFDocument.create();

6. Loop over to the files in folder and load PDF document from the specified file using PDF-lib’s load method. The await keyword ensures that the PDF document is fully loaded before the code proceeds to the next line. Sore the loaded PDF data in the pdfData variable. Copy pages from one PDF document (pdfData) to another PDF document (pdfDoc) using the PDF-lib library. The copyPages method is used to copy the desired pages, and the addPage method is used to add each copied page to the destination PDF document. This process effectively combines the pages from the source PDF document into the destination PDF document.

while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName()+' '+file.getMimeType());
if (file.getMimeType() === 'application/pdf') {
const pdfData = await PDFLib.PDFDocument.load(new Uint8Array(file.getBlob().getBytes()));
const pages = await pdfDoc.copyPages(pdfData, [...Array(pdfData.getPageCount())].map((_, i) => i));
pages.forEach(page => pdfDoc.addPage(page));
}
}

7. Save the merged PDF document using PDF-lib’s save method

const bytes = await pdfDoc.save();

8. Create a new PDF file in Google Drive using the DriveApp.createFile method. The merged PDF document is converted into bytes and stored in Google Drive with the specified file name ("Merged.pdf").

 DriveApp.createFile(Utilities.newBlob([...new Int8Array(bytes)], MimeType.PDF, "Merged.pdf"));

9. Click on Save button in top panel of script and then click Run. You are done.

Here is final script:

async function combinePDFs() {
var folderId = '101g52HffUw_7676752ZJ5L8wEBkq1i'; // Replace with the ID of the folder containing your PDFs
var folder = DriveApp.getFolderById(folderId);
var files = folder.getFiles();

// 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();
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName()+' '+file.getMimeType());
if (file.getMimeType() === 'application/pdf') {
const pdfData = await PDFLib.PDFDocument.load(new Uint8Array(file.getBlob().getBytes()));
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, "Merged.pdf"));
}

--

--

Salimkamboh

Technical Lead | Solution Architect | Php | Larave l Yii | AWS | Continuous Integration and Continuous Delivery (CI/CD)