首页 > 解决方案 > 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

标签: google-apps-scriptgoogle-docs

解决方案


推荐阅读