使用Drive API转换docx为PDF失败,提示仅支持Google Docs
解决Drive API导出PDF时“Export only supports Google Docs”的错误
你猜的完全正确!问题就出在你上传的是普通的.docx二进制文件,而Drive API的Files.Export方法只认原生Google Docs格式(比如Google Docs、Google Sheets这类Google自家的文档类型),直接上传的docx并不在支持列表里,所以才会抛出这个错误。
下面给你两种可行的解决方案:
方案1:上传时直接转换成Google Docs格式,再导出PDF
上传文件的时候,我们可以通过设置Convert=true参数,让Drive自动把docx转换成Google Docs格式,之后就能用Export接口转PDF了。修改后的代码如下:
FilesResource.CreateMediaUpload request; // 定义文件元数据,指定转换后的Google Docs MIME类型 var fileMetadata = new Google.Apis.Drive.v3.Data.File() { Name = "test_converted", MimeType = "application/vnd.google-apps.document" }; using (var stream = new System.IO.FileStream(@"test.docx", System.IO.FileMode.Open)) { // 上传时指定原文件的MIME类型,同时开启转换 request = driveService.Files.Create( fileMetadata, stream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); request.Convert = true; // 关键:开启自动转换为Google Docs request.Fields = "id, webViewLink, webContentLink, size"; // 修正原代码的引号错误 var x = request.Upload(); Console.WriteLine(x); } var convertedFile = request.ResponseBody; // 现在可以用转换后的文件ID导出PDF var downloadRequest = driveService.Files.Export(convertedFile.Id, "application/pdf"); // 执行导出操作并保存到本地 using (var stream = new System.IO.FileStream(@"output.pdf", System.IO.FileMode.Create)) { downloadRequest.Download(stream); }
方案2:转换已上传的docx为Google Docs格式
如果已经上传了docx文件,不想重新上传,可以用Files.Copy接口把普通docx转换成Google Docs格式,再进行导出:
// 定义转换后的文件元数据,指定Google Docs MIME类型 var copyMetadata = new Google.Apis.Drive.v3.Data.File() { Name = "existing_doc_converted", MimeType = "application/vnd.google-apps.document" }; // 复制原文件并转换格式 var copyRequest = driveService.Files.Copy(copyMetadata, file.Id); copyRequest.Fields = "id"; var convertedFile = copyRequest.Execute(); // 导出PDF var downloadRequest = driveService.Files.Export(convertedFile.Id, "application/pdf"); using (var stream = new System.IO.FileStream(@"output_from_existing.pdf", System.IO.FileMode.Create)) { downloadRequest.Download(stream); }
注意事项
- 转换后的Google Docs文件是一个新的独立文件,和原docx文件互不影响,不需要的话可以调用
Files.Delete接口删除。 - 确保你的Drive API权限包含
https://www.googleapis.com/auth/drive(或对应细分权限),否则可能会出现权限错误。
内容的提问来源于stack exchange,提问作者Amarula
相关产品推荐
相关产品推荐

