将电子表格导出为pdf,然后将文件保存在谷歌驱动器中

时间:2012-10-14 10:51:59

标签: google-apps-script

在将Google电子表格打印到pdf后,我在保存到Google驱动器时遇到问题。 如果我只是将“printurl”字符串放入浏览器,它会自动给我文件。但我希望它能自动保存到谷歌驱动器。我通过借用其他帖子中的代码来尝试此代码,这些帖子将电子表格通过电子邮件发送为PDF格式。但这会产生无法打开的pdf。我究竟做错了什么?

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");
}

以下是新oauth2格式下此问题的更新。

Printing spreadsheet to PDF then saving file in Drive using OAuth2

2 个答案:

答案 0 :(得分:6)

你可以用更简单的方式做到这一点

function printpdf(){

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

请注意,DocsList.createFile(blob)仅适用于Google Apps帐户。

答案 1 :(得分:0)

你的意思是这样吗?

  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);