Google Apps Script - Add landscape parameter to PD

2019-02-15 13:15发布

any help would be greatly appreciated. I use the below code successfully to automatically send an email using triggers daily that turns the attached Google Sheet into a .PDF and emails it to a list of recipients. I am having difficulty in setting the parameter to landscape instead of portrait.

Thank you for your help in advance.

// START
function onOpen() {
    var ui = SpreadsheetApp.getUi();
    ui.createMenu("Sender-Thingy")
        .addItem("Send", "send")
        .addToUi();
};

function send() {
    var ss = SpreadsheetApp.getActive();
    var email = "email@gmail.com";
    var subject = "New PRT Daily Report: 09/02/2016";
    var body = "Please find attached your PRT Daily Report.";


    MailApp.sendEmail(email, subject, body, {
        attachments: [{
            fileName: ss.getName() + ".pdf",
            content: ss.getAs("application/pdf").getBytes(),
            mimeType: "application/pdf"
        }]
    });
};

// END

1条回答
唯我独甜
2楼-- · 2019-02-15 13:38

By using a URL to build the PDF instead, you can specify if it's landscape or not.

Then email it to wherever it needs to go, using what you have already

Something like this, bear in mind this script needs you to edit a few bits and only exports a single page, it can do more pages if you needed it to.

This is untested

    function creatPDF() {
  SpreadsheetApp.flush();

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();

  var url = ss.getUrl();

  //remove the trailing 'edit' from the url
  url = url.replace(/edit$/, '');

  //additional parameters for exporting the sheet as a pdf
  var url_ext = 'export?exportFormat=pdf&format=pdf' + //export as pdf
    //below parameters are optional...
    '&size=letter' + //paper size
    '&portrait=true' + //orientation, false for landscape
    '&fitw=true' + //fit to width, false for actual size
    '&sheetnames=false&printtitle=false&pagenumbers=false' + //hide optional headers and footers
    '&gridlines=false' + //hide gridlines
    '&fzr=false' + //do not repeat row headers (frozen rows) on each page
    '&gid=' + sheet.getSheetId(); //the sheet's Id

  var token = ScriptApp.getOAuthToken();

  var response = UrlFetchApp.fetch(url + url_ext, {
    headers: {
      'Authorization': 'Bearer ' + token
    }
  });

  var blob = response.getBlob().setName(ss.getName() + '.pdf');

  //from here you should be able to use and manipulate the blob to send and email or create a file per usual.
  //In this example, I save the pdf to drive
    var email = "email@gmail.com";
    var subject = "New PRT Daily Report: 09/02/2016";
    var body = "Please find attached your PRT Daily Report.";

    MailApp.sendEmail(email, subject, body, {
        attachments: [{blob
        }]
    });


}
查看更多
登录 后发表回答