提问人:Massagran 提问时间:9/29/2023 更新时间:10/6/2023 访问量:38
Google Apps 脚本在从 UrlFetchApp.fetch [duplicate] 创建 blob 时提取错误的 PDF
Google Apps Script fetching the wrong PDF when creating blob from UrlFetchApp.fetch [duplicate]
问:
我有一个谷歌应用程序脚本,它:
- 读取谷歌表格(模板)
- 复制模板,将其保存到 Google 云端硬盘并为其指定新名称
- 然后,我编辑了这张新工作表(更改日期和编号)。
最后一步是将此新工作表以 PDF 格式通过电子邮件发送。我找不到错误,但创建的 PDF 始终是原始模板,而不是我按 ID 引用的新创建的工作表。 我尝试过的事情:
打开新的电子表格并验证它是否已正确编辑(是的,这有效)
使用硬编码的 ID 调用函数。 类似:(硬编码工作并发送正确的 PDF)
sendExportedSheetAsPDFAttachment('2l0e8OdB8[....]yxSR7234s', 'test_pdf.pdf')
引入延迟 (),以确保在创建 PDF blob 之前编辑工作表(不起作用)
Utilities.sleep(80000);
以下是涉及的一些功能
function getFileAsBlob(exportUrl, pdfName){
let params = { method: "GET", headers: { "authorization": "Bearer " + ScriptApp.getOAuthToken() } };
let blob_file = UrlFetchApp.fetch(exportUrl, params).getBlob().setName(pdfName);
return blob_file;
}
和
function sendExportedSheetAsPDFAttachment(newSpreadsheetId, pdfName ) {
// CONVERT SHEET TO PDF
Logger.log('Creating URL for sheet with ID: ' + newSpreadsheetId)
let url_for_blob = "https://docs.google.com/spreadsheets/d/"+ newSpreadsheetId +"/export?format=pdf&portrait=true&size=a4&gridlines=false"
Logger.log("URL " + url_for_blob)
let blob = getFileAsBlob(url_for_blob, pdfName);
// CRAFT MESSAGE
var em_message = "Hello world,<br><br>"
var message = {
to: "[email protected]",
subject: "Good bye world",
htmlBody: em_message,
name: "Bad bot",
attachments: [blob]
}
MailApp.sendEmail(message);
}
这应该有效。硬编码,有效。记录器始终显示正确的新 ID(而不是模板的 ID,即 PDF 中显示的 ID)。newSpreadsheetID
在此之前,我使用以下命令编辑新创建的工作表:
function editNewSheet(newSpreadsheetId, day, currentMonthAsWord, month, year) {
var ss = SpreadsheetApp.openById(newSpreadsheetId);
var sheet = ss.getSheetByName('Invoice');
// range to edit
var cell = sheet.getRange('H4:I4');
// date of Invoice
cell.setValue(day + ' ' + currentMonthAsWord + ' ' + year);
// Invoice number:
var cell = sheet.getRange('H7:I7');
var invoiceNr = (year-2023)*12+month-5
cell.setValue('SPEV31-' + invoiceNR.toString() );
// month
var cell = sheet.getRange('C20');
cell.setValue(currentMonthAsWord + ' ' + year);
}
这三个函数按以下顺序使用:
function createAndEmailInvoice() {
// [SOME CODE HERE]
// Get the ID of the newly created spreadsheet
var newSpreadsheetId = copiedSpreadsheet.getId();
// Rename the newly created spreadsheet
DriveApp.getFileById(newSpreadsheetId).setName(newSheetName);
// EDIT Spreadsheet
Logger.log('New spreadsheet ' + newSheetName + ' created with ID: ' + newSpreadsheetId);
editNewSheet(newSpreadsheetId, day, currentMonthAsWord, month, year)
// Add a sleep here to wait for a few seconds.
Utilities.sleep(10000);
// Download the sheet as PDF & send email with it.
sendExportedSheetAsPDFAttachment(newSpreadsheetId, newSheetName );
}
任何关于可能出错的想法都是值得赞赏的。
答: 暂无答案
评论
var pdfToAttach = DriveApp.getFileById(newSpreadsheetId).getAs('application/pdf');
Utilities.sleep(10000);
SpreadsheetApp.flush();
BTW, Reading the question which has been marked as duplicate would have never made me use .flush().