DriveApp 从 DocX 到 PDF 的转换失败

2024-01-02

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

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

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

还有其他人看到这个问题吗?

Code:

 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,它不能直接从docx to pdf。但是转换之后docx到Google文档,它可以转换为pdf。为了转换docx根据 Google 文档,您可以使用高级 Google 服务来使用 Drive API。为此,请启用高级 Google 服务的 Drive API,如下所示。

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

高级Google服务的详细信息是here https://developers.google.com/apps-script/guides/services/advanced.

我认为在 API 控制台启用 Drive API 已经完成,因为您已经使用过DriveApp在你的剧本上。当以下情况发生时,Google 会自动在 API 控制台上启用 Drive API:DriveApp在脚本中使用。

使用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()。所以如果这一行出现错误,请检查该函数。

Note :

在本例中,Google 文档被创建为临时文件,用于转换为 PDF。文件名与 docx 文件相同。因此,如果您不需要,请删除它。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

DriveApp 从 DocX 到 PDF 的转换失败 的相关文章

随机推荐