javascriptgoogle-apps-script

How to export all pages in Google Sheets tab page to PDF?


This is the function we use to export the content of a Google Sheets file to a PDF file in Drive:

function createPDF(ssId, sheet, pdfName, folder) {
  /**
   * Creates a PDF for the customer invoice template sheet
   * @param {string} ssId - Id of the Google Spreadsheet
   * @param {object} sheet - Sheet to be converted as PDF
   * @param {string} pdfName - File name of the PDF being created
   * @return {file object} PDF file as a blob
   */
  const fr = 0, fc = 0, lc = 9, lr = 27;
  const url = "https://docs.google.com/spreadsheets/d/" + ssId + "/export" +
    "?format=pdf&" +
    "size=A4&" +
    'fitw=true&' +                        // fit to page width, false for actual size
    "fzr=true&" +
    "portrait=true&" +
    "fitw=true&" +
    "gridlines=false&" +
    "printtitle=false&" +
    "top_margin=0.5&" +
    "bottom_margin=0.25&" +
    "left_margin=0.5&" +
    "right_margin=0.5&" +
    "sheetnames=false&" +
    "pagenum=UNDEFINED&" +
    "attachment=true&" +
    "gid=" + sheet.getSheetId() + '&' +
    "r1=" + fr + "&c1=" + fc + "&r2=" + lr + "&c2=" + lc;

  const params = { method: "GET", headers: { "authorization": "Bearer " + ScriptApp.getOAuthToken() } };
  const blob = UrlFetchApp.fetch(url, params).getBlob().setName(pdfName)

  const pdfFile = folder.createFile(blob)
  return pdfFile
}

This code works fine but only exports the first page. There are 2 pages in a single Google Sheet tab. How is it possible to export the complete sheet in the tab? Just like the GUI does?


Solution

  • As Louis remi said here, gid (grid id) is the sheet filter. Remove

    "gid=" + sheet.getSheetId() + '&' +