1

I'm trying to export the current active Google Sheet to a PDF. The below nearly does what I want but I would like a few changes.

Changes.

  1. Save the PDF in the same folder as the main spreadsheet rather than the root drive folder.

  2. Use the currently active sheet rather than a defined sheet.

    function generatePdf() {    
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var mainSheetName = 'Barney'; //Change 'Main Sheet' to the name of your main sheet
      var mainSheet = ss.getSheetByName(mainSheetName);
      var name = mainSheet.getRange('C2').getValue(); //Gets the pdf name from cell B6
      var sheets = ss.getSheets(); //Pulls all sheets as an array
    
      for (var i = 0; i < sheets.length; i++) { //Iterates through all sheets
        if (sheets[i].getSheetName() !== mainSheetName) { //Hides all sheets that are not the main one
          sheets[i].hideSheet()
        }
      }
    
      DriveApp.createFile(ss.getBlob().getAs('application/pdf').setName(name)); //Exports the main sheet
    
      for (var i = 0; i < sheets.length; i++) { //Brings back all sheets that were hidden
        sheets[i].showSheet()
      }
    }
    
1

1 Answer 1

0

Try this:

  const mainSheet = ss.getActiveSheet();

...and this:

  const pdfFile = DriveApp.createFile(ss.getBlob().getAs('application/pdf').setName(name));
  const folder = DriveApp.getFileById(ss.getId()).getParents().next();
  pdfFile.moveTo(folder);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.