3

将谷歌电子表格打印为 pdf 后,我在保存到谷歌驱动器时遇到问题。如果我只是将“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 格式下对此问题的更新。

将电子表格打印为 PDF,然后使用 OAuth2 将文件保存在云端硬盘中

4

2 回答 2

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 帐户。

于 2012-10-14T13:18:00.443 回答
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);
于 2013-02-26T15:03:00.930 回答