Search code examples
google-sheetsgoogle-apps-scriptpdf

Parameters of exporting PDF in app script


I found the below code of @Tanaike which works for me perfect but I would like to add some parameters to exporting like size of the page or exporting in landscape etc.

I know that I need to add parameters to the url but if something added to it the I am getting an error...

"Exception: Request failed for https://docs.google.com returned code 400. Truncated server response: <meta name="viewport" c... (use muteHttpExceptions option to examine full response)"

How can I input the paramaters to the below code? I need to keep the ability of exporting specific range.

"size=0&"+ "fzr=true&"+ "portrait=false&"+ "fitw=true&"+ "gridlines=false&"+ "printtitle=true&"+ "sheetnames=true&"+ "pagenum=CENTER&"+ "attachment=true";

function myFunction() {
  const cc = ""; // Please set cc.
  const bcc = ""; // Please set bcc.

  // Retrieve Spreadsheet and Sheet objects.
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheetByName("Sheet1");

  // Retrieve PDF blob.
  const url = `https://docs.google.com/spreadsheets/d/${ss.getId()}/export?format=pdf&range=A1:I5&gid=${sheet.getSheetId()}`;
  const pdfBlob = UrlFetchApp.fetch(url, { headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() } }).getBlob();

  // Send an email using email from cell "K2".
  const email = sheet.getRange("k2").getValue();
  MailApp.sendEmail({
    to: email,
    cc: cc || null,
    bcc: bcc || null,
    subject: "sample subject",
    body: "sample body",
    attachments: [pdfBlob],
  });

 // DriveApp.getFiles() // This comment line is used for automatically detecting a scope of "https://www.googleapis.com/auth/drive.readonly". In order to export PDF data, I thought that this scope might be required to be included.
}

Solution

  • When your script is modified, how about the following modification?

    Modified script:

    function myFunction() {
      const cc = ""; // Please set cc.
      const bcc = ""; // Please set bcc.
    
      // Retrieve Spreadsheet and Sheet objects.
      const ss = SpreadsheetApp.getActiveSpreadsheet();
      const sheet = ss.getSheetByName("Sheet1");
    
      // Retrieve PDF blob.
      
      // --- I modified the below script.
      const parameters = {
        format: "pdf",
        range: "A1:I5",
        gid: sheet.getSheetId(),
        size: 0,
        fzr: true,
        portrait: false,
        fitw: true,
        gridlines: false,
        printtitle: true,
        sheetnames: true,
        pagenum: "CENTER",
        attachment: true
      };
      const url = `https://docs.google.com/spreadsheets/d/${ss.getId()}/export?${Object.entries(parameters).map(([k, v]) => `${k}=${v}`).join("&")}`;
      // ---
      
      const pdfBlob = UrlFetchApp.fetch(url, { headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() } }).getBlob();
    
      // Send an email using email from cell "K2".
      const email = sheet.getRange("k2").getValue();
      MailApp.sendEmail({
        to: email,
        cc: cc || null,
        bcc: bcc || null,
        subject: "sample subject",
        body: "sample body",
        attachments: [pdfBlob],
      });
    
     // DriveApp.getFiles() // This comment line is used for automatically detecting a scope of "https://www.googleapis.com/auth/drive.readonly". In order to export PDF data, I thought that this scope might be required to be included.
    }
    
    • By this modification, the values parameters are used as the query parameters.

    Note:

    • As additional information, the above conversion from JSON object to query parameters works. But, when you want to use the values that are required the URL encode, please use encodeURIComponent for the value. You can see the sample here. Ref (Author: me)

    References: