How to Export Google Docs to PDF Using Apps Script (with Tab Support)

Looking to automate PDF exports from Google Docs? Here's an Apps Script function that exports a Google Doc to a PDF. It can export entire documents or a specific tab.

This code is particularly useful for use cases such as:

  • Automated report generation or other workflow automation scenarios

  • Batch processing of documents

  • Creating PDF archives of your documents

/**
 * Exports a Google Doc to PDF, optionally specifying a tab to export.
 * @param {string} docId The ID of the Google Doc.
 * @param {object} [options] Optional parameters.
 * @param {string} [options.fileName] The name of the exported PDF file. Defaults to the Doc's name.
 * @param {number} [options.tabIndex] The index of the tab to export (1-based).
 * @param {string} [options.tabId] The ID of the tab to export.
 * @returns {string} The ID of the newly created PDF file in Google Drive.
 * @throws {Error} If docId is missing, tabIndex is out of bounds, or tabId is invalid.
 */
function exportGoogleDocToPDF(docId, options = {}) {
    if (!docId) {
      throw new Error("docId is required.");
    }
    const doc = DocumentApp.openById(docId);

    let url = `https://docs.google.com/document/d/${doc.getId()}/export?format=pdf`;
    
    // Export tab
    if(options.hasOwnProperty("tabIndex") || options.hasOwnProperty("tabId")) {
      const tabs = doc.getTabs();
      let tabId = null;
      if(options.hasOwnProperty("tabId")) {
        tabId = options["tabId"];
        const tabExists = tabs.some(tab => tab.getId() === options.tabId);
        if (!tabExists) {
          throw new Error("Invalid tabId provided.");
        }
      } else if(options.hasOwnProperty("tabIndex")) {
        if(tabs.length < options["tabIndex"]) {
          throw new Error("Tab index is out of bounds.");
        } 
        tabId = tabs[options["tabIndex"] - 1].getId();
      }
      url = url + `&tab=${tabId}`;
    }

    const params = {
        headers: {
            "Authorization": 'Bearer ' + ScriptApp.getOAuthToken()
        }
    };
    const response = UrlFetchApp.fetch(url, params);
    const fileName = options.hasOwnProperty("fileName") ? options["fileName"] : doc.getName();
    const blob = response.getBlob();
    blob.setName(fileName);
    const exportedFile = DriveApp.createFile(blob)
    return exportedFile.getId();
}

How to Use It

Basic Export

The simplest way to use the function is to export an entire document:

const docId = "<DOC_ID>"; // Replace with your Google Doc's ID
const pdfId = exportGoogleDocToPDF(docId);

If you do not specify a tab, all the tabs in the document will be exported. Also, for each tab, the exported PDF file will contain a cover page with its name that precedes its contents.

For example, consider the following Google Doc that has two tabs:

Screenshot of a Google Doc containing two tabs.

The exported PDF file will have 4 pages:

  • A cover page for Tab 1

  • Tab 1's contents

  • A cover page for Tab 2

  • Tab 2's contents

If you specify a tab to export (by specifying either its index or its ID), only its contents will be exported. In this case, a cover sheet will not be included.

Export with Custom Filename

const docId = "<DOC_ID>"; // Replace with your Google Doc's ID
const pdfId = exportGoogleDocToPDF(docId, {
    fileName: 'Monthly-Report-Jan-2024.pdf'
});

Export Specific Tab by Index

const docId = "<DOC_ID>"; // Replace with your Google Doc's ID
const pdfId = exportGoogleDocToPDF(docId, {
    tabIndex: 1  // Exports first tab
});

Export Specific Tab by ID

const docId = "<DOC_ID>"; // Replace with your Google Doc's ID
const pdfId = exportGoogleDocToPDF(docId, {
    tabId: 'tab_id_12345'
});

Sign up to be notified when I publish new content

By signing up you agree to the Privacy Policy & Terms.