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

如何使用Google Apps Script将邮件附件PDF转换为jpg/png单页图片并保存到Drive?

基于Google Apps Script的PDF转图片实现方案

核心流程匹配三类使用场景

  • PDF来源:直接对接Gmail附件抓取逻辑,无需手动上传PDF到Drive
  • 单页拆分:调用Drive原生逐页导出能力,每个PDF页面对应生成独立图片
  • 结果存储:转换后的图片直接写入指定Drive目录,支持临时文件自动清理

可直接复用的完整代码

运行前需在GAS编辑器的服务面板中添加Drive API高级服务,无需引入第三方工具:

// 自定义配置区
const CONVERT_CONFIG = {
  mailMatchRule: 'has:attachment filename:pdf', // 匹配目标带PDF附件的邮件规则
  outputFolderId: '替换为你的目标存储Drive文件夹ID',
  outputImageFormat: 'png', // 可替换为 jpg、webp 等Drive支持的图片格式
  imageScale: 2, // 输出图片清晰度倍率,2为常规屏幕显示的清晰标准
  tempFolderName: '_pdf_convert_temp'
};

function runPdfConvert() {
  // 初始化存储路径
  const tempFolder = getOrCreateTempDir(CONVERT_CONFIG.tempFolderName);
  const targetFolder = DriveApp.getFolderById(CONVERT_CONFIG.outputFolderId);

  // 抓取匹配规则的邮件
  const matchedThreads = GmailApp.search(CONVERT_CONFIG.mailMatchRule, 0, 1);
  if (!matchedThreads.length) {
    console.log('未找到匹配规则的带PDF附件邮件');
    return;
  }

  // 提取邮件中的PDF附件
  const targetMessage = matchedThreads[0].getMessages()[0];
  const pdfBlob = targetMessage.getAttachments()
    .find(attachment => attachment.getContentType() === 'application/pdf');
  if (!pdfBlob) {
    console.log('当前邮件内未检测到有效PDF格式附件');
    return;
  }

  // 临时存储PDF到Drive,准备逐页转换
  const tempPdfFile = tempFolder.createFile(pdfBlob);
  const pdfFileMeta = Drive.Files.get(tempPdfFile.getId());
  const totalPages = Number(pdfFileMeta.imageMediaMetadata.pageCount || 1);

  // 逐页生成独立图片并存入目标文件夹
  for (let currentPage = 1; currentPage <= totalPages; currentPage++) {
    const pageImage = Drive.Files.files.export(
      tempPdfFile.getId(),
      CONVERT_CONFIG.outputImageFormat,
      {
        page: currentPage,
        scale: CONVERT_CONFIG.imageScale
      }
    );
    targetFolder.createFile(
      pageImage.setName(`${pdfFileMeta.title}_Page_${currentPage}.${CONVERT_CONFIG.outputImageFormat}`)
    );
  }

  // 清理临时文件
  tempFolder.removeFile(tempPdfFile);
  console.log(`转换完成,共导出${totalPages}张独立图片至目标文件夹`);
}

// 工具函数:获取或创建临时存储文件夹
function getOrCreateTempDir(folderName) {
  const existingFolders = DriveApp.getFoldersByName(folderName);
  return existingFolders.hasNext() 
    ? existingFolders.next() 
    : DriveApp.createFolder(folderName);
}

关键调整说明

  • 邮件匹配规则:可根据实际业务调整mailMatchRule的检索参数,比如增加发件人地址、邮件主题关键词,精准定位需要转换的PDF来源
  • 输出格式切换:直接修改outputImageFormat的取值即可切换输出图片类型,支持jpg、png、webp等Drive原生导出的格式,无需修改核心转换逻辑
  • 超时处理:当PDF总页数超过50页时,建议将分页转换逻辑拆分为分批执行的任务,避免触发GAS单次运行6分钟的时长限制
  • 临时文件清理:代码内置了临时PDF文件的自动清理逻辑,转换流程结束后不会在Drive中残留中间文件

内容的提问来源于stack exchange,提问作者Marek Čech

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.25 22:27:03