【问题标题】:Get Text from PDF to Text conversion with Google apps script使用 Google 应用脚本将文本从 PDF 转换为文本
【发布时间】:2013-11-28 15:05:38
【问题描述】:

我有一个脚本,可以从某些 Gmail 邮件中获取(可搜索的)PDF 附件。

现在我需要从这些 pdf 中提取一些字符串数据。

有没有办法在启用 OCR 转换的情况下将其添加到 Google Drive 并从该文件中提取文本?还是有更好的方法来解决我的问题?

【问题讨论】:

标签: javascript pdf google-apps-script ocr google-drive-api


【解决方案1】:

您说您从“可搜索”的 pdf 附件开始,我假设您的意思是它们实际上没有文本类型的内容,而是扫描的文档,在 pdf 图像上带有文本。如果您将它们存储在 Drive 中,Google 将自动对其执行 OCR,但是 OCR 不会存储为文件内容的一部分,它仅用于索引文档,以便以后可以使用驱动器搜索找到它(即其内部供驱动器使用,未暴露)。

但是,您可能想试试这个 DocsList api https://developers.google.com/apps-script/reference/docs-list/file#getContentAsString() 如果它们实际上有文本(而不是图像上的文本),它可以在你的 pdf 上工作。

【讨论】:

  • 我所说的可搜索的意思是您可以通过按 CTRL+F 搜索字符串或在 Adob​​e Reader 中标记并复制为字符串。使用 DocsList 和 getContantAsString 方法不会返回 PDF 的文本。
  • 如果在 Adob​​e 中发生这种情况,那么您的 PDF 中已经包含文本(相对于带有文本的图像),因此根本不需要 OCR。即使那样,docsList 方法也可能不会像您发现的那样显示它。
  • 如果getContentAsString()没有回答问题,为什么这个答案还在?
【解决方案2】:

有没有办法在启用 OCR 转换的情况下将其添加到 Google Drive 并从该文件中提取文本?还是有更好的方法来解决我的问题?

Get pdf-attachments from Gmail as text 的 pdfToText() 实用程序使用高级 Drive 服务和 DocumentApp 将 PDF 转换为 Google-Doc 到文本。您可以通过这种方式获取 OCR 文本,或将其直接保存到云端硬盘上任何文件夹中的 txt 文件中。

【讨论】:

    【解决方案3】:

    这是一个解决方案。您必须在控制台开发人员中激活 Drive API。

    将附件转换为文本的脚本

    function uploadFile() {
      var search = "label:inbox";
      var threads = GmailApp.search(search, 0, 2);
        for (var i=0; i<threads.length; i++) {
          var messages = GmailApp.getMessagesForThread(threads[i]);
          for (var j=0; j<messages.length; j++) {
            var email = messages[j]; 
            var sujet = email.getSubject();
            var data = email.getAttachments()[0];
            if (data){
              var file = {
              title: sujet,
              mimeType: 'image/png'
             };
         var image = data;
        file = Drive.Files.insert(file, image, {ocr: true});
        var body = DocumentApp.openById(file.id).getBody();
        var imgs = body.getImages();
        for (var i = 0; i < imgs.length; i++) {
        imgs[i].removeFromParent();
        }
        }
        }
        }
    
    ///////////Script to convert external file to text
    function uploadFile(){
    var image = UrlFetchApp.fetch('http://web.engr.oregonstate.edu/~dambrobr/classes/cs532/muggleton94inductive.pdf').getBlob();
    var file = {title: 'IA',mimeType: 'image/png'};
    file = Drive.Files.insert(file, image, {ocr: true});
    var body = DocumentApp.openById(file.id).getBody();
    var imgs = body.getImages();
    for (var i = 0; i < imgs.length; i++) {
    imgs[i].removeFromParent();
    }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多