Google App脚本:如何将PDF转换为GDOC以获得OCR?

问题描述 投票:1回答:1

[我正在尝试编写一些代码,以使用已经拥有的序列号搜索PDF(gmail),将其保存在云端硬盘中,对其进行OCR读取,然后阅读其内容。

第一步没问题,第二步用下面的代码管理,但是用DocumentApp打开文档以获取getText()的最后两行不起作用:

  var serial = "123456789";
  var ret = DriveApp.searchFiles('fullText contains "' + serial + '"');
  if (ret.hasNext()) {
    var file = ret.next();
    var n_blob = Utilities.newBlob(file.getBlob().getDataAsString(), MimeType.PDF);
    n_blob.setName(serial);
    var n_file = DriveApp.createFile(n_blob);
    var rt = DocumentApp.openById(n_file.getId()); **//not working**
    var text = rt.getBody().getText(); **//not working**
  }

我尝试了许多不同的方式,包括基于Drive.Files.insert()的解决方案,该解决方案不再起作用。]

[如果有人有任何想法或建议可以帮助我,我很困在这里?

谢谢

javascript google-apps-script google-drive-api ocr userscripts
1个回答
0
投票
  • 您要将PDF文件转换为Google文档文件。
    • file的[var file = ret.next();始终为PDF文件。
  • 您想使用Google Apps脚本来实现。

如果我的理解是正确的,那么这个答案怎么样?请认为这只是几个可能的答案之一。

修改点:

  • [很遗憾,var n_blob = Utilities.newBlob(file.getBlob().getDataAsString(), MimeType.PDF)var n_file = DriveApp.createFile(n_blob)无法创建Google文档。这样,就会发生错误。

模式1:

在此模式下,Drive.Files.copy用于将PDF转换为Google Document。因为在您的问题中,我看到了Drive.Files.insert() which is not working anymore

修改的脚本:

请按照以下步骤修改脚本。在运行脚本之前,please enable Drive API at Advanced Google services.

从:
if (ret.hasNext()) {
  var file = ret.next();
  var n_blob = Utilities.newBlob(file.getBlob().getDataAsString(), MimeType.PDF);
  n_blob.setName(serial);
  var n_file = DriveApp.createFile(n_blob);
  var rt = DocumentApp.openById(n_file.getId()); **//not working**
  var text = rt.getBody().getText(); **//not working**
}
至:
if (ret.hasNext()) {
  var file = ret.next();
  if (file.getMimeType() === MimeType.PDF) {
    var fileId = Drive.Files.copy({mimeType: MimeType.GOOGLE_DOCS}, file.getId()).id;
    var rt = DocumentApp.openById(fileId);
    var text = rt.getBody().getText();
    Logger.log(text)
  }
}

模式2:

我以为可以使用Drive.Files.insert。因此,在这种模式下,我建议使用Drive.Files.insert修改脚本。您可以测试一下吗?

修改的脚本:

请按照以下步骤修改脚本。在运行脚本之前,please enable Drive API at Advanced Google services.

从:
if (ret.hasNext()) {
  var file = ret.next();
  var n_blob = Utilities.newBlob(file.getBlob().getDataAsString(), MimeType.PDF);
  n_blob.setName(serial);
  var n_file = DriveApp.createFile(n_blob);
  var rt = DocumentApp.openById(n_file.getId()); **//not working**
  var text = rt.getBody().getText(); **//not working**
}
至:
if (ret.hasNext()) {
  var file = ret.next();
  if (file.getMimeType() === MimeType.PDF) {
    var fileId = Drive.Files.insert({title: serial, mimeType: MimeType.GOOGLE_DOCS}, file.getBlob()).id;
    var rt = DocumentApp.openById(fileId);
    var text = rt.getBody().getText();
    Logger.log(text)
  }
}

注意:

  • [很遗憾,我不了解Drive.Files.insert() which is not working anymore。因此,如果上述修改后的脚本不起作用,请告诉我。我想考虑其他方法。
  • [检查日志时,如果看不到从PDF转换的Google Document文本,则表示var file = ret.next();的所有文件都不是PDF类型。请注意这一点。

参考:

如果我误解了你的问题,而这不是你想要的方向,我深表歉意。

© www.soinside.com 2019 - 2024. All rights reserved.