google-apps-script - Google Apps 脚本,仅在保存的 pdf 中显示模板
问题描述
查看保存的 PDF 文件时,名称不会更改为工作表中的相应名称。知道为什么吗?我认为这与 async/await 的东西有关。
取自电子表格 {{name}} 的名称和 usn 将替换为实际名称,但在生成的 PDF 中未显示。请帮忙
function myFunction() {
var dataspreadsheet = "https://docs.google.com/spreadsheets/d/XXXXX/edit"
var slide = SlidesApp.getActivePresentation();
var ss = SpreadsheetApp.openByUrl(dataspreadsheet)
var sheet = ss.getSheetByName('Sheet1')
var startRow = 2;
var numRows = 3;
var dataRange = sheet.getRange(startRow, 1, numRows, 3);
var data = dataRange.getValues();
console.log(data);
for (var i in data) {
var slides = slide.getSlides();
var template = slides[0]
var row = data[i];
var name = row[0]; // First column
var usn = row[1]; //Second column
template.replaceAllText("{{name}}",name);
var options =
{
"contentType" : "application/pdf",
"muteHttpExceptions": false
};
var presentationCopyId = 'YYY'
var blob = DriveApp.getFileById(presentationCopyId).getBlob();
var folderId = "ZZZ"
DriveApp.getFolderById(folderId).createFile(blob).setName(usn+".pdf");
template.replaceAllText(name,"{{name}}");
}
}
解决方案
回答
这里的主要问题是替换的文本没有更新,因此,您可以按照实际操作使用 replaceAllText 制作幻灯片的副本以填充必要的信息。然后保存并关闭它以刷新并应用更改。在所有这些过程之后,获取动态生成的新文件并将它们移动到您的垃圾目录。
代码
function myFunction() {
var dataspreadsheet = "https://docs.google.com/spreadsheets/d/XXXX/edit"
var slide = SlidesApp.getActivePresentation();
var ss = SpreadsheetApp.openByUrl(dataspreadsheet);
var sheet = ss.getSheetByName('Sheet1');
var startRow = 2;
var numRows = 3;
var dataRange = sheet.getRange(startRow, 1, numRows, 3);
var data = dataRange.getValues();
var slides = slide.getSlides(); // You only need to get the slides once
for (var i in data) {
var row = data[i];
var name = row[0]; // First column
var usn = row[1]; //Second column
/* Make a copy instead */
var tmpSlide = SlidesApp.create(`tmp_presentation_${name}`);
slide.getSlides().forEach(s => {
tmpSlide.appendSlide(s);
});
var slidesTemplate = tmpSlide.getSlides();
slidesTemplate[0].remove(); // Remove the first empty slide
var template = slidesTemplate[1]; // Get the first slide of the copy without the empty slide
template.replaceAllText("{{name}}", name);
tmpSlide.saveAndClose(); // updates flushed and applied
var presentationCopyId = tmpSlide.getId(); // Get the ID of the new copy
var slideFile = DriveApp.getFileById(presentationCopyId);
var blob = slideFile.getBlob();
var folderId = "ZZZ"
DriveApp.getFolderById(folderId).createFile(blob).setName(usn+".pdf");
slideFile.setTrashed(true); // Then remove the slide previously created
}
}
参考
推荐阅读
- git - 如何在 Jenkins 的拉取请求中获取 git 更改的文件
- python - 如何让 Python 访问另一个数据库
- microsoft-dynamics - 营销安装块的动态
- python - 使用 PyShp 将 Shapefile 分成多个部分
- php - 如何在 Symfony 4 中隐藏模型/实体中的特定列
- jquery - 移动菜单问题
- php - 在 Laravel 中卸载 Spatie 包时出现错误 Class 'Spatie\Permission\PermissionServiceProvider' not found
- karate - 在空手道中读取 javascript 时,javascript 评估失败
- javascript - javascript 如何创建与 DOM 元素的单向数据绑定?
- html - 图像背景溢出问题