首页 > 解决方案 > 编辑 Google Doc 然后转换为 PDF 的脚本

问题描述

我一直在尝试制作一个系统,我可以在其中更改谷歌文档的内容,然后将其保存为 pdf。该脚本在 Google 表格中运行,所以我不确定这是否是我的问题。我可以使用正确的信息对其进行编辑,但它仍然是文档,而不是 PDF。我也不编码,所以这是我根据其他人的工作得到的。任何帮助都会很棒,谢谢!

function autoFillGoogleDocFromForm(e) {
  //e.values is an array of form values
  var timestamp = e.values[0];
  var InvenName = e.values[1];
  var Case = e.values[2];
  var AppNumber = e.values[3];
  var Firm = e.values[4];
  var InvenTitle = e.values[5];
  var Date = e.values[6];
  var AppType = e.values[7];

  //file is the template file, and you get it by ID
  var file = DriveApp.getFileById('FILE_ID_HERE'); 

  //We can make a copy of the template, name it, and optionally tell it what folder to live in
  //file.makeCopy will return a Google Drive file object
  var folder = DriveApp.getFolderById('FOLDER_ID_HERE')
  var copy = file.makeCopy(Case + ' ' + 'E Assigmnt' + ' ' + AppType + ' ' + AppNumber + ' ' + InvenName ,folder);

  //Once we've got the new file created, we need to open it as a document by using its ID
  var doc = DocumentApp.openById(copy.getId()); 

  //Since everything we need to change is in the body, we need to get that
  var body = doc.getBody(); 
  var footer = doc.getFooter();

  //Then we call all of our replaceText methods
  body.replaceText('{{Name}}', InvenName);
  body.replaceText('{{Title}}' ,InvenTitle);
  body.replaceText('{{AppNumber}}', AppNumber);
  body.replaceText('{{Date}}' , Date);
  footer.replaceText('{{FirmNumber}}', Firm);
  footer.replaceText('{{Case}}', Case);

  //Lastly we save and close the document to persist our changes
  DocumentApp.getActiveDocument().saveAndClose();

  var doc = DocumentApp.getActiveDocument();
  var docblob = DocumentApp.getActiveDocument().getAs('application/pdf');
  docblob.setName(doc.getName() + ".pdf");

}

标签: javascriptgoogle-apps-scriptgoogle-sheets

解决方案


我相信你的目标如下。

  • 您想通过使用 Google Apps 脚本修改复制的 Google 文档来创建 PDF 文件。

为此,这个答案怎么样?

修改点:

  • 在您的脚本中,通过替换文本来修改复制的 Google 文档。但修改后的 Document 不会导出为 PDF 文件。活动文档被转换为 PDF 格式。但是,blob 不会导出为文件。

修改后的脚本:

当您的脚本被修改时,请进行如下修改。

从:
DocumentApp.getActiveDocument().saveAndClose();

var doc = DocumentApp.getActiveDocument();
var docblob = DocumentApp.getActiveDocument().getAs('application/pdf');
docblob.setName(doc.getName() + ".pdf");
至:
doc.saveAndClose();
var docblob = doc.getBlob();
docblob.setName(doc.getName() + ".pdf");
DriveApp.createFile(docblob);
  • 通过上述修改,复制的Google Document通过替换文本进行修改,修改后的Document导出为PDF文件。在这种情况下,创建的 PDF 文件将被放入根文件夹。

参考:


推荐阅读