【问题标题】:How to export/convert Google Doc in PDF with Google Apps Script?如何使用 Google Apps 脚本以 PDF 格式导出/转换 Google Doc?
【发布时间】:2020-11-26 16:01:44
【问题描述】:

我正在尝试使用 Google Apps 脚本从 Google Drive 执行 2 项操作:

  1. 从 Google Doc 模板创建文件并在该文件中插入数据
  2. 将此 Google Doc 文件导出为 Google Drive 中的 PDF 文件(同时)

第 1 步有效:Google Docs 文件已正确创建,其中的值已更新。

第 2 步:我有 2 个问题/问题:

  1. 我发现生成 PDF 的代码已用于将所有 Google Docs 文件转换为 PDF 文件,但在我这边,我只需要导出/转换已创建的文件(并非所有文件已经位于文件夹)。
  2. 尽管第 1 点,脚本正在运行并生成 PDF,但是当我打开 PDF 文件时,其中添加的值已丢失,我只有模板中存在的标签。

你有什么想法吗?

代码如下:

function replaceTags () {
 // Global vars
  var ui = DocumentApp.getUi ();
  var date = Utilities.formatDate(new Date(), "GMT", "dd-MM-yyyy");
  var folderOutId = 'xxxxxxxxxxxxxxxxxxxx';
  var tplMaintenanceId = 'xxxxxxxxxxxxxxxxxxxx';
  var fileOutName = 'my file name';
  var clientCompany = ui.prompt ('Company Name :');
  
  // Do a copy from template file to a new file inside a specific folder
  targetFolder = DriveApp.getFolderById (folderOutId);
  var documentId = DriveApp.getFileById (tplMaintenanceId). makeCopy (targetFolder). getId ();
      
  // Rename filed copied
  DriveApp.getFileById (documentId) .setName (fileOutName + ' - ' + clientCompany.getResponseText ());
      
  // Add document body inside variable
  var body = DocumentApp.openById (documentId) .getBody ();
    
  // Insert data inside Google Doc document
  body.replaceText ('##DATE##', date);
  body.replaceText ('##CLIENT_COMPANY##', clientCompany.getResponseText ());
  
  gdocToPDF(documentId);
}

function gdocToPDF(fileID) {
  var documentRootfolder = DriveApp.getFolderById("xxxxxxxxxxxxxxxxxxxx") // replace this with the ID of the folder that contains the documents you want to convert
  var pdfFolder = DriveApp.getFolderById("xxxxxxxxxxxxxxxxxxxx"); // replace this with the ID of the folder that the PDFs should be put in. 
  
  var docFile = DriveApp.getFileById(fileID)
  
  createPDF(docFile.getId(), pdfFolder.getId(), function (fileID, folderID) {
    if (fileID) createPDFfile(fileID, folderID);
  }
 )
}

function createPDF(fileID, folderID, callback) {
    var templateFile = DriveApp.getFileById(fileID);
    var templateName = templateFile.getName();
    
    var existingPDFs = DriveApp.getFolderById(folderID).getFiles();

    //in case no files exist
    if (!existingPDFs.hasNext()) {
        return callback(fileID, folderID);
    }

    for (; existingPDFs.hasNext();) {

        var existingPDFfile = existingPDFs.next();
        var existingPDFfileName = existingPDFfile.getName();
        if (existingPDFfileName == templateName + ".pdf") {
            Logger.log("PDF exists already. No PDF created")
            return callback();
        }
        if (!existingPDFs.hasNext()) {
            Logger.log("PDF is created")
            return callback(fileID, folderID)
        }
    }
}

function createPDFfile(fileID, folderID) {
    var templateFile = DriveApp.getFileById(fileID);
    var folder = DriveApp.getFolderById(folderID);
    var theBlob = templateFile.getBlob().getAs('application/pdf');
    var newPDFFile = folder.createFile(theBlob);

    var fileName = templateFile.getName().replace(".", ""); //otherwise filename will be shortened after full stop    
    newPDFFile.setName(fileName + ".pdf");
}

【问题讨论】:

    标签: pdf google-apps-script google-docs google-drive-shared-drive


    【解决方案1】:

    我尝试重新创建您的代码,并成功将文档转换为 pdf。

    您可以做的是编辑您的 gdocToPDF() 函数以仅接受您想要转换为 PDF 的文档。请参阅下面的示例代码(可能不是您想要的方式):

    将 replaceTags() 函数中使用的文档 ID 传递给 gdocToPDF()

    function replaceTags () {
     ....
     .... 
      DocumentApp.openById(documentId).saveAndClose()
      gdocToPDF(documentId);
    }
    

    不要获取驱动器文件夹中的所有文件,而是使用此代码来仅使用带有替换标签的文件

    function gdocToPDF(fileID) { 
      var documentRootfolder = DriveApp.getFolderById(folder-id) // replace this with the ID of the folder that contains the documents you want to convert
      var pdfFolder = DriveApp.getFolderById(folder-id); // replace this with the ID of the folder that the PDFs should be put in. 
      
      var docFile = DriveApp.getFileById(fileID)
      
      createPDF(docFile.getId(), pdfFolder.getId(), function (fileID, folderID) {
        if (fileID) createPDFfile(fileID, folderID);
      }
     )
    }
    

    这会将 doc 到 pdf 转换为您想要转换的唯一文档。

    祝你有美好的一天!

    【讨论】:

    • 我有一个奇怪的问题,在生成的 PDF 文件中添加的值已经丢失,我只有模板中存在的标签。
    • 您的 PDF 已经存在吗?如果 PDF 文件已经创建,部分代码不允许您覆盖它。
    • 不,PDF 不存在。一开始,只有一个空的 Google Docs 文件模板,里面有一些标签,见这里:prnt.sc/vqozso,然后我启动应用脚本代码,其中标签将被值替换,见这里:prnt.sc/vqp0ul 和最后,生成 PDF 文件但缺少值,请参见此处:prnt.sc/vqp1v0。但我不明白为什么新的 Google Docs 文件正确生成了值和 PDF 编号。
    • 我明白了。我已经编辑了我的答案。请让我知道这是否解决了它。基本上,我只是确保我们将使用与替换标签相同的文档。
    • 好的,我做到了,但我收到了这个错误:ReferenceError: fileID is not defined (ligne 53, fichier "Code")
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-15
    • 2017-03-27
    • 1970-01-01
    • 1970-01-01
    • 2017-08-10
    相关资源
    最近更新 更多