基于CloudConvert API的Google Apps Script PDF转PNG代码故障求助
修复Google Apps Script调用CloudConvert API转换PDF到PNG的问题
原代码存在的核心问题
- 未定义变量:直接使用
folder变量但未声明,导致运行时抛出引用错误。 - 废弃API调用:
getDownloadUrl()已被Google弃用,且生成的URL无有效权限,CloudConvert无法访问私有Drive文件。 - 任务配置错误:误用
export/url任务并传入folder_id(该参数属于export/google-drive任务),且未处理CloudConvert异步任务的状态等待,提交Job后直接获取URL会得到无效结果。 - 无错误处理:未处理文件不存在、任务失败等异常场景,容易崩溃。
修正后的完整代码
function convertPDFtoPNG(fileName, folderId) { // 替换为你的CloudConvert API密钥 const apiKey = "YOUR_CLOUDCONVERT_API_KEY"; try { // 获取目标文件夹 const folder = DriveApp.getFolderById(folderId); // 查找目标PDF文件 const files = folder.getFilesByName(fileName + ".pdf"); if (!files.hasNext()) { throw new Error("未找到指定的PDF文件"); } const pdfFile = files.next(); const pdfFileId = pdfFile.getId(); // 构建CloudConvert Job请求体 const requestBody = { tasks: { // 从Google Drive导入PDF(需提前在CloudConvert授权Drive访问) "import-drive": { operation: "import/google-drive", file_id: pdfFileId, filename: pdfFile.getName() }, // PDF转PNG转换任务 "convert-png": { operation: "convert", input: "import-drive", input_format: "pdf", output_format: "png", // 可选:自定义PNG参数,比如分辨率 "converter_options": { "dpi": 300 } }, // 导出转换后的PNG到原Drive文件夹 "export-drive": { operation: "export/google-drive", input: "convert-png", folder_id: folderId, filename: fileName + ".png" } }, tag: "pdf-to-png-conversion" }; // 发送创建Job请求 const options = { method: "post", headers: { "Authorization": `Bearer ${apiKey}`, "Content-Type": "application/json" }, payload: JSON.stringify(requestBody) }; const response = UrlFetchApp.fetch("https://api.cloudconvert.com/v2/jobs", options); const job = JSON.parse(response.getContentText()); const jobId = job.data.id; // 轮询任务状态,直到完成或失败 let jobStatus; do { Utilities.sleep(2000); // 每2秒查询一次状态 const statusResponse = UrlFetchApp.fetch(`https://api.cloudconvert.com/v2/jobs/${jobId}`, { headers: { "Authorization": `Bearer ${apiKey}` } }); jobStatus = JSON.parse(statusResponse.getContentText()).data.status; } while (jobStatus === "processing" || jobStatus === "waiting"); // 检查任务执行结果 if (jobStatus !== "finished") { throw new Error(`任务执行失败:${jobStatus}`); } console.log("PDF转PNG完成,文件已保存到原文件夹"); } catch (error) { console.error("转换出错:", error.message); } } // 示例调用:替换为你的文件夹ID和目标文件名(不带.pdf后缀) // convertPDFtoPNG("test-file", "YOUR_GOOGLE_DRIVE_FOLDER_ID");
关键修改说明
- 变量与权限优化:通过
folderId参数明确获取目标文件夹,使用CloudConvert官方的import/google-drive和export/google-drive任务,无需处理复杂的Drive文件授权URL,只需提前在CloudConvert控制台完成Drive授权即可。 - 异步任务处理:添加轮询逻辑等待任务完成,因为CloudConvert的转换任务是异步执行的,提交后不能立即获取结果。
- 异常捕获:增加文件不存在、任务失败等场景的错误处理,避免脚本崩溃。
- 可选参数配置:添加了
converter_options可自定义PNG的分辨率等参数,按需调整即可。
内容的提问来源于stack exchange,提问作者Saud Malik
相关产品推荐
相关产品推荐

