从 Gmail 获取 pdf 附件作为文本

2024-05-10

我在网络和 Stack Overflow 上搜索但没有找到解决方案。我尝试做的事情如下:我通过邮件收到某些附件,我希望将其作为(纯)文本进行进一步处理。我的脚本如下所示:

function MyFunction() {

  var threads = GmailApp.search ('label:templabel'); 
  var messages = GmailApp.getMessagesForThreads(threads); 

   for (i = 0; i < messages.length; ++i)
   {
     j = messages[i].length; 
   var messageBody = messages[i][0].getBody(); 
   var messageSubject = messages [i][0].getSubject();
     var attach = messages [i][0].getAttachments();
     var attachcontent = attach.getContentAsString();
    GmailApp.sendEmail("mail", messageSubject, "", {htmlBody: attachcontent});
    }
}

不幸的是这不起作用。这里有人知道我该怎么做吗?有可能吗?

预先非常感谢您。

最好的,菲尔


Edit: Updated for DriveApp, as DocsList deprecated.


我建议将其分解为两个问题。第一个是如何从电子邮件中获取 pdf 附件,第二个是如何将 pdf 转换为文本。

正如你所发现的,getContentAsString()不会神奇地将 pdf 附件更改为纯文本或 html。我们需要做一些更复杂的事情。

首先,我们将获取附件Blob https://developers.google.com/apps-script/reference/base/blob,多个服务用来交换数据的实用程序类。

var blob = attachments[0].getAs(MimeType.PDF);

因此,第二个问题被分离出来,并保持我们只对标记为每个线程的第一条消息的第一个附件感兴趣的假设templabel,这是如何myFunction() looks:

/**
 * Get messages labeled 'templabel', and send myself the text contents of
 * pdf attachments in new emails.
 */
function myFunction() {

  var threads = GmailApp.search('label:templabel');
  var threadsMessages = GmailApp.getMessagesForThreads(threads);

  for (var thread = 0; thread < threadsMessages.length; ++thread) {
    var message = threadsMessages[thread][0];
    var messageBody = message.getBody();
    var messageSubject = message.getSubject();
    var attachments = message.getAttachments();

    var blob = attachments[0].getAs(MimeType.PDF);
    var filetext = pdfToText( blob, {keepTextfile: false} );

    GmailApp.sendEmail(Session.getActiveUser().getEmail(), messageSubject, filetext);
  }
}

我们依赖一个辅助函数,pdfToText(),转换我们的pdfblob转换为文本,然后我们将其作为纯文本电子邮件发送给自己。这个辅助函数有多种选项;通过设置keepTextfile: false,我们选择只将 PDF 文件的文本内容返回给我们,并且在我们的云端硬盘中不留下任何残留文件。

pdfToText()

该实用程序可用作为要点 https://gist.github.com/mogsdad/e6795e438615d252584f。那里提供了几个例子。

A 之前的回答 https://stackoverflow.com/questions/14406966/upload-pdf-with-ocr-with-google-apps-script-and-possibly-drive-api/14408321#14408321表明可以使用 Drive APIinsert执行方法OCR http://en.wikipedia.org/wiki/Optical_character_recognition,但没有提供代码详细信息。随着高级 Google 服务的推出,可以通过 Google Apps 脚本轻松访问 Drive API。您确实需要打开并启用Drive API来自编辑,根据Resources > Advanced Google Services.

pdfToText()使用 Drive 服务从 PDF 文件的内容生成 Google 文档。不幸的是,这包含文档中每个页面的“图片” - 我们对此无能为力。然后它使用常规的DocumentService将文档正文提取为纯文本。

/**
 * See gist: https://gist.github.com/mogsdad/e6795e438615d252584f
 *
 * Convert pdf file (blob) to a text file on Drive, using built-in OCR.
 * By default, the text file will be placed in the root folder, with the same
 * name as source pdf (but extension 'txt'). Options:
 *   keepPdf (boolean, default false)     Keep a copy of the original PDF file.
 *   keepGdoc (boolean, default false)    Keep a copy of the OCR Google Doc file.
 *   keepTextfile (boolean, default true) Keep a copy of the text file.
 *   path (string, default blank)         Folder path to store file(s) in.
 *   ocrLanguage (ISO 639-1 code)         Default 'en'.
 *   textResult (boolean, default false)  If true and keepTextfile true, return
 *                                        string of text content. If keepTextfile
 *                                        is false, text content is returned without
 *                                        regard to this option. Otherwise, return
 *                                        id of textfile.
 *
 * @param {blob}   pdfFile    Blob containing pdf file
 * @param {object} options    (Optional) Object specifying handling details
 *
 * @returns {string}          id of text file (default) or text content
 */
function pdfToText ( pdfFile, options ) {
  // Ensure Advanced Drive Service is enabled
  try {
    Drive.Files.list();
  }
  catch (e) {
    throw new Error( "To use pdfToText(), first enable 'Drive API' in Resources > Advanced Google Services." );
  }

  // Set default options
  options = options || {};
  options.keepTextfile = options.hasOwnProperty("keepTextfile") ? options.keepTextfile : true;

  // Prepare resource object for file creation
  var parents = [];
  if (options.path) {
    parents.push( getDriveFolderFromPath (options.path) );
  }
  var pdfName = pdfFile.getName();
  var resource = {
    title: pdfName,
    mimeType: pdfFile.getContentType(),
    parents: parents
  };

  // Save PDF to Drive, if requested
  if (options.keepPdf) {
    var file = Drive.Files.insert(resource, pdfFile);
  }

  // Save PDF as GDOC
  resource.title = pdfName.replace(/pdf$/, 'gdoc');
  var insertOpts = {
    ocr: true,
    ocrLanguage: options.ocrLanguage || 'en'
  }
  var gdocFile = Drive.Files.insert(resource, pdfFile, insertOpts);

  // Get text from GDOC  
  var gdocDoc = DocumentApp.openById(gdocFile.id);
  var text = gdocDoc.getBody().getText();

  // We're done using the Gdoc. Unless requested to keepGdoc, delete it.
  if (!options.keepGdoc) {
    Drive.Files.remove(gdocFile.id);
  }

  // Save text file, if requested
  if (options.keepTextfile) {
    resource.title = pdfName.replace(/pdf$/, 'txt');
    resource.mimeType = MimeType.PLAIN_TEXT;

    var textBlob = Utilities.newBlob(text, MimeType.PLAIN_TEXT, resource.title);
    var textFile = Drive.Files.insert(resource, textBlob);
  }

  // Return result of conversion
  if (!options.keepTextfile || options.textResult) {
    return text;
  }
  else {
    return textFile.id
  }
}

转换为 DriveApp 有助于此布鲁斯·麦克弗森的实用程序 http://ramblings.mcpher.com/Home/excelquirks/gooscript/driveapppathfolder:

// From: http://ramblings.mcpher.com/Home/excelquirks/gooscript/driveapppathfolder
function getDriveFolderFromPath (path) {
  return (path || "/").split("/").reduce ( function(prev,current) {
    if (prev && current) {
      var fldrs = prev.getFoldersByName(current);
      return fldrs.hasNext() ? fldrs.next() : null;
    }
    else { 
      return current ? null : prev; 
    }
  },DriveApp.getRootFolder()); 
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 Gmail 获取 pdf 附件作为文本 的相关文章

  • Gmail 应用程序中指向特定邮件的深层链接

    我成功地从 gmail api 获得了消息网址 https mail google com mail email protected cdn cgi l email protection all 155134b5e66a9b06 然而 当我
  • url文本压缩(不是缩短)并存储在mysql中

    我在 mysql 中有一个 url 表 其中只有两个字段 id 和 varchar 255 用于 url 目前那里有超过 5000 万个 url 我的老板刚刚向我提供了有关当前项目扩展的线索 这将导致在该 url 表中添加更多的 url 预
  • GhostScript PDF 合并(丢失可编辑字段)

    我正在使用 GhostScript 将 PDF 合并为一个 PDF 其中一份 PDF 具有我在 Adob e Acrobat Pro 9 中创建的文本框字段 可编辑字段 当我使用 GhostScript 合并这两个 PDF 时 我丢失了文本
  • 使用itext java库复制时pdf文件大小大大增加

    我正在尝试使用 Java 中的 itextpdf 库将现有的 pdf 文件复制到一些新文件中 我使用的是 itextpdf 5 5 10 版本 我在两种方式上都面临着不同的问题 PDFStamper 和 PdfCopy 当我使用 PDFSt
  • 在 iPhone 上搜索 PDF

    经过两天尝试使用 Quartz 从 PDF 中读取注释后 我成功做到了并且发布我的代码 https stackoverflow com questions 4080373 get pdf hyperlinks on ios with qua
  • 如何在模态窗口中显示pdf? [关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我有一个模式窗口 其中包含锚文本 当我单击此链接时 它必须调用其他位置的 pdf 并将其显示在弹出窗口中 我怎样才能做到这一点 请帮忙
  • 使用 GhostScript 获取页面大小

    是否可以使用 GhostScript 获取页面大小 例如从 PDF 文档页面 我见过 bbox 设备 但它返回的是边界框 每页不同 而不是 PDF 页面的 TrimBox 或 CropBox 看http www prePressure co
  • 如何为 Android 创建我们自己的 PDF 查看器?

    我想构建一个可在我的 Android 应用程序中使用的 PDF 阅读器 查看器 但我无法使用 Google 文档来阅读我的内容 我无法使用我的设备中已安装的任何 PDF 阅读器 它应该位于我的应用程序内 并且不会通过互联网公开我的安全内容
  • 如何从纯文本文件中解析文本并使用结果突出显示 PDF 文件

    早在 2010 年 就有人声称能够做到这一点 http www mobileread com forums showthread php t 103847 http www mobileread com forums showthread
  • 如果输入重复,则覆盖 Google 表格(用于表单响应)行

    因此 我一直在尝试找出如何阻止谷歌表单中的谷歌表格响应输出中出现重复的行 如果找到这个链接 听起来它正是我想要的 表单 Google 脚本防止重复 https stackoverflow com questions 16965687 for
  • 将 Word 转换为 PDF - 禁用“保存”对话框

    我有一个用 C 编写的 Word 到 PDF 转换器 除了一件事之外 它工作得很好 有时 在某些 Word 文件上 后台会出现一条消息保存源文件中的更改 gt 是 否 取消 但我没有对源文件进行任何更改 我只想从 Word 文件创建 PDF
  • 裁剪 .pdf 文件的页面

    我想知道是否有人有以编程方式处理 pdf 文件的经验 我有一个 pdf 文件 我需要将每一页裁剪到一定大小 经过快速谷歌搜索后 我找到了 python 的 pyPdf 库 但我的实验失败了 当我更改页面对象上的cropBox 和trimBo
  • 脚本在 SpreadsheetApp.openById 上失败 - 需要权限

    我有一个 onOpen 函数 可以在电子表格中创建自定义菜单 它已经工作了一年多 但几天前它停止工作了 当我查看执行记录时 我得到 执行失败 您无权调用 SpreadsheetApp openById 所需权限 https www goog
  • 将 PDF 转换为 CMYK 但忽略黑色?

    我使用以下命令将 RGB PDF 转换为 CMYK usr local bin gs dSAFER dBATCH dNOPAUSE dNOCACHE sDEVICE pdfwrite sColorConversionStrategy CMY
  • 如何使用 pdftk 和 /MediaBox 裁剪 PDF 边距

    I used pdftk解压缩 PDF 然后将其作为文本文件打开 我想编辑 媒体盒领域 就我而言 MediaBox 0 0 612 792 例如 我想减少边距 MediaBox 100 0 512 792 不幸的是它不起作用 我可以改变0
  • Google Add-on 在有限模式应用脚本中添加菜单项

    我们在新的谷歌应用程序脚本添加商店中发布了一个插件 但在除安装的初始电子表格之外的任何电子表格中使用该插件时 权限似乎无法正常工作 我遇到一个问题 当创建新电子表格并且用户从 管理加载项 菜单中选择 使用此加载项 时 我们的菜单项不会填充
  • 测量填写部分的时间 - 谷歌表单

    我正在尝试使用谷歌表单进行研究调查问卷 对于某些部分 我想自动测量用户填写所需的时间 谷歌表单中没有这样的选项 我尝试复制表单源 并用 javascript 填充时间 但它不起作用 跨源问题 未能成功托管复制的表单 如何做到 我如何衡量回答
  • 打印包含 JBIG2 图像的 PDF

    请推荐一些库 帮助我打印包含 JBIG2 编码图像的 PDF 文件 PDFRenderer PDFBox别帮我 这些库可以打印简单的 PDF 但不能打印包含 JBIG2 图像的 PDF PDFRenderer尝试修复它 根据 PDFRedn
  • 如何为 Gmail 开发 Chrome 扩展程序?

    我正在考虑为 Gmail 开发 Chrome 扩展程序 我想知道当前的最佳实践是什么 例如 默认情况下为每封电子邮件附加 GPG 签名 添加一个额外的按钮来执行某些操作 我已经有了 发送电子邮件并提示我完成某些操作的劫持操作 只是这些例子帮
  • 从 puppeteer PDF 中删除分页符?

    我目前正在尝试查看是否有一种方法可以删除我的 puppeteer PDF 中的分页符 因为我当前的 PDF 设置中的一些分页符正在以一种奇怪的方式切断文本 我正在谈论的内容的屏幕截图 我的傀儡代码 app get companyId pdf

随机推荐