我正在尝试转换 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,如下所示。
- 在脚本编辑器中,选择“资源”>“高级 Google 服务”
- 在出现的对话框中,点击 Drive API v2 的开关。
- 点击“确定”按钮。
高级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/