google-sheetsgoogle-apps-scriptexport-to-pdf

When exporting a spreadsheet as a PDF using AppScript, how do you include the current date and time?


What, if any, is the keyword argument to include in url to show the current date and time when exporting a spreadsheet as a PDF in AppScript? This option is possible when clicking File > Download > PDF so I would have thought it was possible through the script too.

I've tried timestamp=true but that didn't work


Solution

  • You need to programmatically add the current date and time to the file name, as there is no direct keyword argument like timestamp=true for this purpose.

    Here’s an example of how you can add the current date and time to the file name when exporting a Google Sheets spreadsheet as a PDF with Apps Script:

    function exportSpreadsheetAsPDF() {
      // Get the active spreadsheet
      var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
      var sheet = spreadsheet.getActiveSheet();
     
      // Get the current date and time
      var now = new Date();
      var timestamp = Utilities.formatDate(now, Session.getScriptTimeZone(), 'yyyyMMdd_HHmmss');
     
      // Prepare the export URL
      var sheetId = sheet.getSheetId();
      var url = 'https://docs.google.com/spreadsheets/d/' + spreadsheet.getId() + '/export?';
     
      var exportOptions = {
        format: 'pdf',
        size: 'letter',         // Paper size
        portrait: true,         // Orientation
        fitw: true,             // Fit to width
        top_margin: '0.50',     // Margins
        right_margin: '0.50',
        bottom_margin: '0.50',
        left_margin: '0.50',
        gridlines: false,       // Whether to print gridlines
        printtitle: false,      // Whether to print title
        pagenum: 'CENTER',      // Page number position
        attachment: false,
        gid: sheetId,           // Sheet ID
      };
     
      // Append export options to the URL
      for (var key in exportOptions) {
        url += key + '=' + exportOptions[key] + '&';
      }
     
      // Get the PDF content
      var response = UrlFetchApp.fetch(url, {
        headers: {
          'Authorization': 'Bearer ' + ScriptApp.getOAuthToken(),
        },
      });
     
      var pdfBlob = response.getBlob().setName('Export_' + timestamp + '.pdf');
     
      // Save the PDF to Google Drive
      var folder = DriveApp.getFolderById('your-folder-id'); // Replace with your folder ID
      folder.createFile(pdfBlob);
    }