近一年来,我们一直在使用以下代码将 Google 表格工作表(保存在 theSheetName
中)导出到 PDF 中指定的名称 InboundID
.
上周,一次一个不同的用户无法再生成 PDF。我在包含“var newFile = DriveApp.createFile(blob);”的行中失败错误是:
"Conversion from text/html to application/pdf failed."
果然,
UrlFetchApp.fetch
正在返回 HTML 而不是 PDF。同样,仅适用于某些用户。有没有人对为什么我的用户可能会看到这个有任何想法?function sendPDFToDrive(theSheetName, InboundID)
{
var theSpreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var theSpreadsheetId = theSpreadSheet.getId();
var thisSheetId = theSpreadSheet.getSheetByName(theSheetName).getSheetId();
var url_base = theSpreadSheet.getUrl().replace(/edit$/,'');
var theOutFileName = "GASFILE_M_" + (Math.floor(Math.random() * 8997) + 1000) + '.pdf'
//export as pdf
var url_ext = 'export?exportFormat=pdf&format=pdf'
+ (thisSheetId ? ('&gid=' + thisSheetId) : ('&id=' + theSpreadsheetId))
// following parameters are optional...
+ '&size=A4' // paper size
+ '&scale=2' // 1= Normal 100% / 2= Fit to width / 3= Fit to height / 4= Fit to Page
+ '&portrait=true' // orientation, false for landscape
+ '&horizontal_alignment=CENTER' //LEFT/CENTER/RIGHT
+ '&fitw=true' // fit to width, false for actual size
+ '&sheetnames=false&printtitle=false&pagenumbers=false' //hide optional headers and footers
+ '&gridlines=true' // hide gridlines
+ '&printnotes=false' // don't show notes
+ '&fzr=true'; // repeat row headers (frozen rows) on each page
// Setup options
var options =
{
headers:
{
'Authorization': 'Bearer ' + ScriptApp.getOAuthToken(),
}
}
// Build the file
var response = UrlFetchApp.fetch(url_base + url_ext, options);
var blob = response.getBlob().setName(theOutFileName);
var folder = DriveApp.getFolderById("ABC123FooBarID");
var newFile = DriveApp.createFile(blob); //Create a new file from the blob
newFile.setName(InboundID + ".pdf"); //Set the file name of the new file
newFile.makeCopy(folder);
}
最佳答案
我遇到了这个确切的问题。经过一些调试后,我发现我的 URL 被错误地创建。
我的代码和你的几乎一样。我发现罪魁祸首是以下几行:
var url_base = theSpreadSheet.getUrl().replace(/edit$/,'');
这实际上并没有像多年来那样清除行尾的“编辑”。我不能说这是为什么,但证据在日志中。所以,我手工制作了网址:var url = 'https://docs.google.com/spreadsheets/d/'+SpreadsheetApp.getActiveSpreadsheet().getId()+'/';
这似乎解决了问题。这不是一个完美的面向 future 的解决方案,因为如果 Google 更改 URL 的制作方式,这将失败。但它现在有效。我希望这有帮助。您可以将您的代码创建的 url 发送到日志并检查它们以查看您是否遇到了与我相同的问题。
关于pdf - 无法再为某些用户从 Google Sheets 电子表格生成 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63413712/