Google apps script 将电子表格导出为pdf,然后将文件保存在google drive中
将谷歌电子表格打印成pdf后,我在保存到谷歌硬盘时遇到问题。 如果我把“printurl”字符串放到浏览器中,它会自动给我文件。但我希望它能自动保存到谷歌硬盘。我已经尝试了这段代码,从其他以PDF格式发送电子表格的帖子中借用了这段代码。但这会生成无法打开的pdf。我做错了什么Google apps script 将电子表格导出为pdf,然后将文件保存在google drive中,google-apps-script,Google Apps Script,将谷歌电子表格打印成pdf后,我在保存到谷歌硬盘时遇到问题。 如果我把“printurl”字符串放到浏览器中,它会自动给我文件。但我希望它能自动保存到谷歌硬盘。我已经尝试了这段代码,从其他以PDF格式发送电子表格的帖子中借用了这段代码。但这会生成无法打开的pdf。我做错了什么 function printpdf() { var spreadsheet_id="0Aiy1DTQRndx6dDRidXoxNzlXZFhxd2FITTlBbnUybnc"; var settings = '&f
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格式下对这个问题的更新
你可以用一种简单得多的方式来做
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应用程序帐户 你是那个意思吗
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);
嗨,斯瑞克,谢谢你的回复。我试过了。实际上,这是我目前使用的代码,但是,我不能指定诸如纵向或横向、网格或无网格等选项。如何使用您的方法并保持灵活性?目前没有可用的选项来增强/修改pdf导出,有一个@Srik。有了新的谷歌工作表,你可以使用你的方法,但与其他设置,如肖像/风景等?不知道你是问这是正确的方式或张贴一个实际的解决方案。你能澄清一下吗?