通过 GAS 将 GDoc 转换为 docx 会产生损坏的文档
Converting a GDoc to docx through GAS produces corrupted document
我使用下面的代码片段将 Google 文档转换为 PDF 和 docx 格式并将其保存到 GDrive。 PDF 没问题,但 docx 在 Office Word 2013 中有问题,根本打不开showing this message。 LibreOffice 6 可以打开文件,但只能在 LibreDraw 中以只读方式打开,而不是 LibreWriter,并且文本位于文本框中,边框是纯图像,而不是对象。
如果我在菜单中从
文件 > 下载为.. > Microsoft Word(.docx) 手动转换它,
文档工作正常。我有数百个文件,手动执行不是解决方案。
function saveToDrive(_name){
//Get document blob for converting
var blob = DocumentApp.openById('string_id').getBlob();
//Save as PDF
var pdf = {
title: _name + '.pdf',
mimeType: MimeType.PDF,
parents:[{id:'google_drive_folder'}]
};
Drive.Files.insert(pdf, blob);
//Save as docx
var docx = {
title: _name + '.docx',
mimeType: MimeType.MICROSOFT_WORD,
parents:[{id:'google_drive_folder'}]
};
Drive.Files.insert(docx, blob);
}
我也使用了字符串 mime 类型,结果相同。我错过了什么?
问题:
getBlob()
默认将其转换为 PDF。因此,当 insert
将其作为 docx
放入云端硬盘时,您正在尝试从 pdf
转换为 docx
。
可能的解决方案:
- 使用驱动器 API
Files:export
从 gdoc
直接转换
- 使用
UrlFetchApp
直接获取导出 link
示例脚本:
function docToDocx(id) {
var format = 'docx',
exportLink =
'https://docs.google.com/document/d/' + id + '/export?format=' + format,
blob = UrlFetchApp.fetch(exportLink, {
headers: {
Authorization: 'Bearer ' + ScriptApp.getOAuthToken(),
},
});
DriveApp.createFile(blob);
}
参考文献:
我使用下面的代码片段将 Google 文档转换为 PDF 和 docx 格式并将其保存到 GDrive。 PDF 没问题,但 docx 在 Office Word 2013 中有问题,根本打不开showing this message。 LibreOffice 6 可以打开文件,但只能在 LibreDraw 中以只读方式打开,而不是 LibreWriter,并且文本位于文本框中,边框是纯图像,而不是对象。
如果我在菜单中从
文件 > 下载为.. > Microsoft Word(.docx) 手动转换它,
文档工作正常。我有数百个文件,手动执行不是解决方案。
function saveToDrive(_name){
//Get document blob for converting
var blob = DocumentApp.openById('string_id').getBlob();
//Save as PDF
var pdf = {
title: _name + '.pdf',
mimeType: MimeType.PDF,
parents:[{id:'google_drive_folder'}]
};
Drive.Files.insert(pdf, blob);
//Save as docx
var docx = {
title: _name + '.docx',
mimeType: MimeType.MICROSOFT_WORD,
parents:[{id:'google_drive_folder'}]
};
Drive.Files.insert(docx, blob);
}
我也使用了字符串 mime 类型,结果相同。我错过了什么?
问题:
getBlob()
默认将其转换为 PDF。因此,当insert
将其作为docx
放入云端硬盘时,您正在尝试从pdf
转换为docx
。
可能的解决方案:
- 使用驱动器 API
Files:export
从 - 使用
UrlFetchApp
直接获取导出 link
gdoc
直接转换
示例脚本:
function docToDocx(id) {
var format = 'docx',
exportLink =
'https://docs.google.com/document/d/' + id + '/export?format=' + format,
blob = UrlFetchApp.fetch(exportLink, {
headers: {
Authorization: 'Bearer ' + ScriptApp.getOAuthToken(),
},
});
DriveApp.createFile(blob);
}