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

如何用Google App Script实现Drive中PDF自动打印并修正代码?

修正Google Apps Script打印PDF代码(解决PdfApp未定义错误)

问题根源

  1. PdfApp并非Google Apps Script内置服务,也无公开可用的官方库,直接调用会触发"PdfApp库未定义"错误
  2. 原代码将PDF拆分为图片再转临时PDF的流程完全冗余,Google Cloud Print支持直接打印PDF文件

修正后的代码

function printPDFs() {
  const folderId = "1mrAHm29XWv-0WPFN6WLludnBNcjA1ifv";
  const printerName = "SHARP MX-2517FN SPDL2-c";
  const folder = DriveApp.getFolderById(folderId);
  const files = getAllPDFFilesInFolder(folder);
  
  // 获取目标打印机
  const printer = getPrinterByName(printerName);
  
  // 遍历所有PDF文件并提交打印任务
  while (files.hasNext()) {
    const file = files.next();
    const pdfBlob = file.getBlob().setContentType("application/pdf");
    
    // 通过Cloud Print提交打印
    CloudPrint.submitJob({
      printerId: printer.id,
      title: file.getName(),
      content: pdfBlob.getBytes(),
      contentType: "application/pdf"
    });
    
    console.log(`已提交打印:${file.getName()}`);
  }
}

function getPrinterByName(name) {
  const printers = CloudPrint.getPrinters();
  for (let i = 0; i < printers.length; i++) {
    if (printers[i].name === name) {
      return printers[i];
    }
  }
  throw new Error(`未找到指定打印机:${name}`);
}

function getAllPDFFilesInFolder(folder) {
  let files = folder.getFilesByType(MimeType.PDF);
  const childFolders = folder.getFolders();
  
  // 递归遍历子文件夹
  while (childFolders.hasNext()) {
    const childFiles = getAllPDFFilesInFolder(childFolders.next());
    files = concatenateFileIterators(files, childFiles);
  }
  
  return files;
}

function concatenateFileIterators(iterator1, iterator2) {
  const arr = [];
  while (iterator1.hasNext()) arr.push(iterator1.next());
  while (iterator2.hasNext()) arr.push(iterator2.next());
  
  // 返回兼容Apps Script的迭代器对象
  return {
    next: function() {
      return { value: arr.shift(), done: arr.length === 0 };
    },
    hasNext: function() {
      return arr.length > 0;
    }
  };
}

关键修改点

  • 移除所有PdfApp相关代码,直接使用原始PDF文件的Blob提交打印,简化流程
  • 使用CloudPrint.submitJob()直接发送PDF内容,避免不必要的格式转换
  • 修复了concatenateFileIterators的迭代器实现,确保与Google Apps Script的迭代器接口兼容
  • 增加打印日志,便于排查任务状态

前置操作

  1. 在脚本编辑器中启用Cloud Print高级服务:点击「扩展」→「Apps Script」→「资源」→「高级Google服务」,找到Cloud Print并开启
  2. 确保目标打印机已通过Google Cloud Print完成注册,且打印机名称与代码中完全一致(可通过CloudPrint.getPrinters()打印所有可用打印机名称核对)
  3. 首次运行脚本时,需要授权访问Google Drive和Cloud Print服务

内容的提问来源于stack exchange,提问作者hiep Hoangduc

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 12:25:27