Save GSheet Tabs to PDF

61 views Asked by At

I'm trying to save each tab of a gsheet as its own PDF. I got this code from chatGPT but its throwing up a "Script function not found: saveTabsAsPDFs" so would love some help on fixing it.

/**
 * @OnlyCurrentDoc
 *
 * The above comment specifies that this automation will only
 * attempt to read or modify the spreadsheet this script is bound to.
 * The authorization request message presented to users reflects the
 * limited scope.
 */

const APP_TITLE = 'PDF Generator';

/**
 * Create a custom menu in the Google Sheets UI.
 */
function createCustomMenu() {
  const menu = SpreadsheetApp.getUi().createMenu(APP_TITLE);
  menu
    .addItem('Save Tabs as PDFs', 'saveTabsAsPDFs')  // Corrected function name
    .addToUi();
}

/**
 * Save each tab as a separate PDF file.
 */
function saveTabsAsPDFs() {
  const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  const sheets = spreadsheet.getSheets();

  for (let i = 0; i < sheets.length; i++) {
    const sheet = sheets[i];
    const blob = sheet.getRange(1, 1, sheet.getMaxRows(), sheet.getMaxColumns()).getBlob();
    const pdfName = sheet.getName() + '.pdf';

    // Save PDF to the root folder of Google Drive
    saveBlobToDrive(blob, pdfName);
  }

  // Notify the user that the process is complete
  SpreadsheetApp.getUi().alert('PDFs generated successfully.');
}

/**
 * Save a Blob to Google Drive.
 *
 * @param {Blob} blob The blob to save.
 * @param {string} fileName The name of the file.
 */
function saveBlobToDrive(blob, fileName) {
  const folder = DriveApp.getRootFolder();
  folder.createFile(blob).setName(fileName);
}

// Manually run this function to create the custom menu
createCustomMenu();

This is my first attempt with app script/ coding of any kind so would appreciate any help

0

There are 0 answers