google-apps-script - Google Apps 脚本创建 Google Doc,然后将 blob 保存到 PDF 即使在 saveAndClose() 之后也无法正常工作
问题描述
我想复制一个谷歌文档(这是一个模板),将其另存为新文件名,将文本添加到文档中,将图像添加到文档中,然后制作文档的 pdf 副本。
我可以让文档复制,添加文本,添加图像,并且效果很好。然后我添加要转换为 blob 的行以创建 pdf,但 pdf 现在正是添加文本和图像之前的模板。所以然后我保存并关闭,然后重新打开文档,然后转换为 blob pdf - 但在这种情况下,文档的文本和图像是空白的,而 pdf 是空白的。在创建pdf之前,我已经尝试了多次保存和关闭并重新打开。我不知道为什么它不能正常工作。
// Create template copy:
const folder = DriveApp.getFolderById(destinationFolderID); // Get folder with specified destinationFolderID
const copiedTemplateDoc = DriveApp.getFileById(templateGoogleDocumentID).makeCopy("file name xyz", folder); // Copy template to destination folder
const docId = copiedTemplateDoc.getId();
var doc = DocumentApp.openById(docId);
const header = doc.getHeader();
const body = doc.getBody();
// Insert photo
if(imageURL) {
const imageBlob = UrlFetchApp.fetch(imageURL).getBlob();
const totalElements = doc.getNumChildren();
const el=[]
for(var j = 0; j < totalElements; ++j) {
const element = doc.getChild(j);
const type = element.getType();
if (type =='PARAGRAPH'){
el[j]=element.getText()
if(el[j]=='{Photo}'){
element.removeFromParent();
const styles = {};
styles[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;
doc.insertImage(j, imageBlob).setHeight('144').getParent().setAttributes(styles);
}
}
}
}
doc.saveAndClose() // the doc must be saved and closed before it can be converted to a pdf
DocumentApp.openById(docId);
const testPDF = DriveApp.createFile(doc.getBlob()).moveTo(folder); // Export a PDF copy of the Lead Sheet doc to the SREC drive folder
解决方案
推荐阅读
- php - 不同的htaccess目录和子目录重定向
- c - 字符位图有一些标准吗?
- flutter - 我不明白 Flutter 中 Theme 类的意义
- javascript - 基于条件和对象值的对象的Javascript数组计数
- python - 从任务中引发忽略不会确认消息
- java - 检查 BigInteger 是否为完美正方形的复杂性
- android - 片段未与片段管理器关联。(对话片段)
- java - 我想写一个代码来回答一个无限系列,它有交替加减运算。我看不到错误,在我的代码中
- javascript - 使用正则表达式验证家庭地址
- python - Paramiko中ssh over ssh的保持活动机制