You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

利用App Script批量生成PDF并合并:Google表格ID列表处理方案

解决方案

实现思路

通过Google Apps Script完成以下流程:

  1. 读取表格D3:D范围的Google文档ID,过滤空单元格
  2. 逐个将有效ID对应的文档导出为PDF,暂存到临时文件夹
  3. 合并所有生成的PDF为单个文档,最后自动清理临时文件

完整脚本

async function generateAndMergePDFs() {
  // 配置参数:修改为你的实际工作表名称
  const SHEET_NAME = "Sheet1";
  const ID_RANGE = "D3:D";
  
  // 获取表格中的有效文档ID列表
  const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = spreadsheet.getSheetByName(SHEET_NAME);
  if (!sheet) {
    throw new Error(`未找到名为${SHEET_NAME}的工作表`);
  }
  const idList = sheet.getRange(ID_RANGE).getValues()
    .flat()
    .filter(id => typeof id === 'string' && id.trim() !== '');

  if (idList.length === 0) {
    SpreadsheetApp.getUi().alert("未找到有效文档ID");
    return;
  }

  // 创建临时文件夹存放单个PDF
  const tempFolder = DriveApp.createFolder(`临时PDF_${Date.now()}`);
  const pdfBlobs = [];

  // 遍历ID生成单个PDF
  for (const docId of idList) {
    try {
      const doc = DocumentApp.openById(docId);
      const pdfBlob = doc.getAs("application/pdf").setName(`模板_${docId}.pdf`);
      const tempFile = tempFolder.createFile(pdfBlob);
      pdfBlobs.push(tempFile.getBlob());
      console.log(`已生成ID ${docId} 的PDF`);
    } catch (error) {
      console.error(`处理ID ${docId} 失败: ${error.message}`);
      SpreadsheetApp.getUi().alert(`处理ID ${docId} 失败,请检查ID有效性或权限`);
    }
  }

  if (pdfBlobs.length === 0) {
    tempFolder.setTrashed(true);
    SpreadsheetApp.getUi().alert("没有成功生成任何PDF");
    return;
  }

  // 合并PDF(依赖pdf-lib库)
  const mergedPdfDoc = await PDFLib.PDFDocument.create();
  for (const blob of pdfBlobs) {
    const pdfBytes = blob.getBytes();
    const sourcePdf = await PDFLib.PDFDocument.load(pdfBytes);
    const copiedPages = await mergedPdfDoc.copyPages(sourcePdf, sourcePdf.getPageIndices());
    copiedPages.forEach(page => mergedPdfDoc.addPage(page));
  }

  // 导出合并后的PDF到Drive根目录
  const mergedPdfBytes = await mergedPdfDoc.save();
  const mergedFile = DriveApp.createFile(
    Utilities.newBlob(mergedPdfBytes, "application/pdf", `合并后的PDF_${new Date().toLocaleString()}`)
  );

  // 清理临时文件夹
  tempFolder.setTrashed(true);
  
  SpreadsheetApp.getUi().alert(`合并完成!文件已保存到Drive:${mergedFile.getName()}`);
}

使用步骤

  1. 打开脚本编辑器:在目标Google表格中,点击顶部菜单栏「扩展」→「Apps脚本」
  2. 修改工作表名称:将脚本中SHEET_NAME的值替换为你的实际工作表名称
  3. 添加pdf-lib库:
    • 点击左侧菜单栏「库」→「添加库」
    • 输入库ID:1FS36YkL379x64wkt04r0EhoT4729V5X7,选择最新版本后点击「添加」
  4. 启用Drive API:
    • 点击左侧菜单栏「服务」→「添加服务」
    • 找到「Drive API」并点击「添加」
  5. 运行脚本:
    • 点击脚本编辑器顶部的运行按钮,首次运行需完成权限授权
    • 运行结束后会弹出提示,合并后的PDF将保存到Google Drive根目录

注意事项

  • 确保所有文档ID有效,且当前账号拥有对应文档的查看/编辑权限
  • 临时文件夹会自动移入回收站,可手动永久删除
  • 若合并后PDF格式异常,检查原文档的页面设置(纸张大小、边距)是否统一

内容的提问来源于stack exchange,提问作者Dornescu Lucian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 07:35:22