【问题标题】:DriveApp conversion from DocX to PDF failsDriveApp 从 DocX 到 PDF 的转换失败
【发布时间】:2018-02-25 10:01:37
【问题描述】:

我正在尝试转换我的 Google 云端硬盘上的现有 .DOCX 文件。 它一直有效,直到应该创建新的(PDF)文件,然后我收到此错误消息: “从 application/vnd.openxmlformats-officedocument.wordprocessingml.document 到 application/pdf 的转换失败”。

相关的 DOCX 文件不应损坏,因为它可以通过 Google 文档打开并从那里手动转换为 PDF。

我已启用 Drive API(在 Drive 和 API 控制台中)

其他人看到过这个问题吗?

代码:

 function convertPDF(fileid) {
     var docId = fileid;
     var f=DriveApp.getFileById(docId);
     var n=f.getName();
     var docFolder = f.getParents().next().getId();

     var docblob = f.getAs('application/pdf');
     n=n.replace(".docx",".pdf");
     docblob.setName(n);
     var bn=docblob.getName();
     var t=docblob.getContentType();
     Logger.log(bn+"-->"+t);  // <-- works 

     var file = DriveApp.createFile(docblob); // <<- error msg here

     var fileId = file.getId();
     moveFileId(fileId, docFolder);
     return (fileId);
}

【问题讨论】:

    标签: google-apps-script google-drive-api


    【解决方案1】:

    在 Google,它不能直接从 docx 转换为 pdf。但是,将docx 转换为Google 文档后,它可以转换为pdf。为了将docx 转换为 Google 文档,您可以使用 Drive API 使用高级 Google 服务。为此,请按如下方式启用 Advanced Google 服务的 Drive API。

    1. 在脚本编辑器中,选择资源 > 高级 Google 服务
    2. 在出现的对话框中,单击 Drive API v2 的开/关开关。
    3. 点击确定按钮。

    高级谷歌服务的详细信息是here

    我认为在 API 控制台启用 Drive API 已经完成,因为您已经在脚本中使用了DriveApp。当脚本中使用DriveApp 时,Google 会在 API 控制台上自动启用 Drive API。

    使用Drive API修改后的脚本如下。

    修改后的脚本:

    function convertPDF(docx_id) {
      var docx = DriveApp.getFileById(docx_id);
      var docFolder = docx.getParents().next().getId();
      var n = docx.getName();
      var res = Drive.Files.insert({ // Here, Drive API of Advanced Google services is used.
        "mimeType": "application/vnd.google-apps.document",
        "title": n
      }, docx.getBlob());
      var f = DriveApp.getFileById(res.id).getBlob();
    
      var docblob = f.getAs('application/pdf');
      n=n.replace(".docx",".pdf");
      docblob.setName(n);
      var bn=docblob.getName();
      var t=docblob.getContentType();
      Logger.log(bn+"-->"+t);
      var file = DriveApp.createFile(docblob);
      var fileId = file.getId();
      Logger.log(fileId)
      moveFileId(fileId, docFolder);
      return (fileId);
    }
    

    我不知道moveFileId()。所以如果这一行出现错误,请检查函数。

    注意:

    在这种情况下,Google 文档被创建为临时文件,用于转换为 PDF。文件名与 docx 文件相同。所以如果你不需要,请删除它。

    【讨论】:

    • 谢谢!尽管转换为 Google Doc 有一些负面影响(可能会更改更复杂的布局),但这已经足够了
    猜你喜欢
    • 2018-08-24
    • 2020-06-07
    • 1970-01-01
    • 2020-12-13
    • 2018-12-28
    • 1970-01-01
    • 1970-01-01
    • 2016-05-17
    相关资源
    最近更新 更多