exporting spreadsheet to pdf then saving the file

2019-02-15 04:15发布

问题:

I'm having problems saving to google drive after printing a google spreadsheet to pdf. If i just put the "printurl" string into a browser, it will automatically give me the file. But I want it to be saved to google drive automatically. I've tried this code by borrowing code from other posts that emails a spreadsheet as PDF. But this produces a pdf that is unable to be opened. What am I doing wrong?

function printpdf() {
var spreadsheet_id="0Aiy1DTQRndx6dDRidXoxNzlXZFhxd2FITTlBbnUybnc";
var settings = '&fitw=true&portrait=false&exportFormat=pdf&gid=0&gridlines=false';
var printurl = 'https://spreadsheets.google.com/feeds/download/spreadsheets/Export?   key=' + spreadsheet_id + settings;
var result=UrlFetchApp.fetch(printurl);
var content=result.getContent();
var file=DocsList.createFile("temp",content,"application/pdf");
}

Here is an update to this question under the new oauth2 format.

Printing spreadsheet to PDF then saving file in Drive using OAuth2

回答1:

You can do it in a much simpler fashion

function printpdf(){

  var spreadsheet_id="0Aiy1DTQRndx6dDRidXoxNzlXZFhxd2FITTlBbnUybnc";
  var spreadsheetFile = DocsList.getFileById(spreadsheet_id); 
  var blob = spreadsheetFile.getAs('application/pdf'); 
  DocsList.createFile(blob);
}

Note that the DocsList.createFile(blob) works only with Google Apps accounts.



回答2:

did you mean it like that?

  var id = SpreadsheetApp.getActiveSpreadsheet().getId();
  var sheetName = getConfig(SHEET_NAME_CELL);
  var dataSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);

  if (!dataSheet) {
    Browser.msgBox("Can't find sheet named:" + sheetName);
    return;
  }

  var dataSheetIndex = dataSheet.getSheetId();

 //this is three level authorization 
  var oauthConfig = UrlFetchApp.addOAuthService("google");
  oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
  oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope=https://spreadsheets.google.com/feeds/");
  oauthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
  oauthConfig.setConsumerKey("anonymous");
  oauthConfig.setConsumerSecret("anonymous");

  //even better code
  //oauthConfig.setConsumerKey(ScriptProperties.getProperty("consumerKey"));
  //oauthConfig.setConsumerSecret(ScriptProperties.getProperty("consumerSecret"));

  var requestData = {
    "method": "GET",
    "oAuthServiceName": "google",
    "oAuthUseToken": "always"
  };


  var url = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=" + id +  "&gid=" + dataSheetIndex + "&fitw=true&size=A4&portrait=true&sheetnames=false&printtitle=false&exportFormat=pdf&format=pdf&gridlines=false";



  //Save File to Google Drive 
  var seplogoBlob = UrlFetchApp.fetch(url, requestData).getBlob().setName("Filename.pdf");
  DocsList.createFile(seplogoBlob);