google-apps-script - DriveApp 从 DocX 到 PDF 的转换失败

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

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

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

我已启用 Drive API(在云端硬盘和 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,它无法直接从 docx 转换为 pdf。但是,将 docx 转换为 Google 文档后,它可以转换为 pdf。为了将 docx 转换为 Google 文档,您可以使用高级 Google 服务来使用 Drive API。为此,请启用高级 Google 服务的 Drive API,如下所示。

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

高级Google服务的详细信息是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-apps-script - DriveApp 从 DocX 到 PDF 的转换失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46252645/

相关文章:

google-apps-script - 缺少 Apps 脚本网络 Hook 和 Access-Control-Allow-Origin header

curl - 使用 curl 列出谷歌驱动器文件

python - Google Documents List API v3 (Python) 更新文档

google-apps-script - 用于删除空白或未使用的列的谷歌脚本

使用 Google SignIn 和 google spreadsheet api 的 iOS 示例

c# - 使用 API 检索 Google Drive 文件夹列表

python - 使用 GSpread 在文件夹中创建电子表格

google-apps-script - 使用脚本复制谷歌工作表,同时保留 protected 工作表的权限

firebase - 使用 Google Apps 脚本将 Google Sheets 数据保存到 Firebase 中

javascript - Google 脚本左侧分配无效