Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

google apps script - Change document orientation when exporting to PDF

I have this script that emails the content of a speadsheet to all the collaborators on a regular basis.

function myFunction() {
  var document = SpreadsheetApp.openById("123documentid456");

  var editors = document.getEditors();
  for(var i = 0; i < editors.length; i++){
    MailApp.sendEmail(editors[i].getEmail(), "Subject", "Some message", {
      attachments : [document.getAs(MimeType.PDF)]
    });
  }
}

It creates a PDF and emails it. The thing is the content does not display nicely as the PDF's orientation is portrait. Is there any way to make it export to landscape?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From here, this code could help

*************************************************

function savePDFs() {
  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=false' + //orientation, false for landscape, true for portrait
  '&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(sheet.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

  DocsList.createFile(blob);
  //OR DriveApp.createFile(blob);
}

*************************************************

Notice this bit: '&portrait=false' + //orientation, false for landscape, true for portrait


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...