Exporting Specific Pages From a PDF as a New PDF Using Google Apps Script

Gists

This is a sample script for exporting the specific pages from a PDF as a new PDF 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

async function myFunction() {
  // Retrieve PDF data.
  const fileId = "###"; // Please set a file ID of your a PDF file or a file ID of Google Docs files (Document, Spreadsheet, Slide).
  const pageNumbers = [2, 4]; // In this sample, 2 and 4 pages are exported as a PDF.

  const blob = DriveApp.getFileById(fileId).getBlob();

  // 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();
  const pdfData = await PDFLib.PDFDocument.load(
    new Uint8Array(blob.getBytes())
  );
  const pages = await pdfDoc.copyPages(
    pdfData,
    [...Array(pdfData.getPageCount())].map((_, i) => i)
  );
  pages.forEach((page, i) => {
    if (pageNumbers.includes(i + 1)) {
      pdfDoc.addPage(page);
    }
  });
  const bytes = await pdfDoc.save();

  // Create a PDF file.
  DriveApp.createFile(
    Utilities.newBlob([...new Int8Array(bytes)], MimeType.PDF, "sample.pdf")
  );
}
  • When this script is run, the specific pages (In this sample, 2 and 4 pages.) in pageNumbers of a PDF file of fileId are exported as a new PDF file.

  • In this sample, when Google Docs files (Document, Spreadsheet, Slide and so on) can be also directly used. In that case, when the file ID of Google Docs files is set to fileId and run the script, the Google Docs files are automatically converted to a PDF format and the specific pages are exported as a PDF file.

Note

  • Of course, in this case, you can also use the pdf-lib library by copying and pasting the script library retrieved from https://cdn.jsdelivr.net/npm/pdf-lib/dist/pdf-lib.min.js in the script editor of Google Apps Script. In this case, the process cost for loading it can be reduced.

References

 Share!