首页 > 解决方案 > 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}}");
  }
}

标签: google-apps-scriptgoogle-drive-apigoogle-slides-api

解决方案


回答

这里的主要问题是替换的文本没有更新,因此,您可以按照实际操作使用 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
  }
 }

参考

幻灯片:saveAndClose


推荐阅读