Google Apps Script如何将多个PDF Blob合并为单个Blob生成合并PDF文件
你之前直接对两个Blob执行加法操作的写法是无效的,PDF是有固定结构化格式的文件,不能直接拼接二进制内容生成可用的合并文件。
你可以通过以下代码实现两个PDF的合并,运行前需要先在Google Apps Script编辑器左侧的「服务」菜单中添加Drive API v3:
function mergeTwoSheetPDFs() { // 可保留你原有的para配置 const para = { headers: { Authorization: "Bearer " + ScriptApp.getOAuthToken() }, muteHttpExceptions: true }; // 替换为你自己的表格导出链接 const url1 = "https://docs.google.com/spreadsheets/d/SHEETID/export?format=pdf&gid=788671078"; const url2 = "https://docs.google.com/spreadsheets/d/SHEETID/export?format=pdf&gid=788671070"; // 获取两个PDF的Blob const blob1 = UrlFetchApp.fetch(url1, para).getBlob(); const blob2 = UrlFetchApp.fetch(url2, para).getBlob(); // 合并PDF const mergedPdfBlob = mergePDFBlobs([blob1, blob2], "合并后的文件.pdf"); // 保存到目标文件夹 DriveApp.getFoldersByName("a").next().createFile(mergedPdfBlob); } // PDF合并工具函数 function mergePDFBlobs(pdfBlobs, fileName) { // 临时存储单份PDF文件 const tempFiles = pdfBlobs.map(blob => DriveApp.createFile(blob)); // 调用Drive API执行合并 const mergedFileId = Drive.Files.copy({ title: fileName, mimeType: MimeType.PDF }, tempFiles[0].getId()).id; for (let i = 1; i < tempFiles.length; i++) { Drive.Files.update({}, mergedFileId, tempFiles[i].getBlob()); } const mergedBlob = DriveApp.getFileById(mergedFileId).getBlob(); // 清理临时文件 tempFiles.forEach(file => file.setTrashed(true)); DriveApp.getFileById(mergedFileId).setTrashed(true); return mergedBlob.setName(fileName); }
注意事项:
- 请将代码中的
SHEETID替换为你自己的Google Sheet文件ID - 请求参数
para可以保留你原有的配置,不需要和示例完全一致 - 运行前请确认你对目标表格和名称为「a」的文件夹有读写权限
内容的提问来源于stack exchange,提问作者Andrew
相关产品推荐
相关产品推荐

