【问题标题】:Convert PDFs to Google docs and get extracted text along with link to original PDF file into a spreadsheet将 PDF 转换为 Google 文档并将提取的文本以及原始 PDF 文件的链接提取到电子表格中
【发布时间】:2020-04-02 08:30:59
【问题描述】:

当我运行脚本以使用 OCR 将 PDF 文件转换为 Google 文档然后将结果填充到 Google 表格中时,我在获取 PDF 文件的链接时遇到了一个小问题。

到目前为止,我得到了创建的文件的名称(Google Docs)和提取的文本。

我想要实现的目标:在第 3 列,我想获取与创建的 Google 文档对应的 PDF 文件的链接

我尝试将变量 pdf 包含到 push 数组中:

    var pdf = document.getId();
...
    output.push([name, body, pdf]);

但我得到所有文件的相同 ID。理想情况下,我想获得 PDF 文件的完整链接,而不仅仅是它的 ID,以避免必须使用以下内容创建列:

=CONCATENATE("https://drive.google.com/file/d/",C2)

其中 C2 包含 PDF 文件的 ID。

代码如下:

function extractTextOnOpen() {



var folderName = "OCR TESTS";

   var sheetId = "SHEET'S ID HERE";

  //Define Project folder

var folder = DriveApp.getFoldersByName(folderName).next();
var folderId = folder.getId();

//Find all PDFs in folder

var documents = folder.getFilesByType("application/pdf");
while (documents.hasNext()) {

    //Convert each PDF to a Google Doc with OCR
    var document = documents.next();

    // Get the PDF link to insert in the sheet for reference

    var pdf = document.getId();


    var imageName = document.getName();
    var docName = imageName.split("\.")[0];
    var file = {
        title: docName,
        mimeType: "application/pdf"
        // for images, use: "image/png"

    }
    Drive.Files.insert(file, document, { ocr: true });

    //Store newly-created Google Doc in the same project folder

    var newFile = DriveApp.getFilesByName(docName).next();
    folder.addFile(newFile);
    var rootFolder = DriveApp.getRootFolder();
    rootFolder.removeFile(newFile);
}

//Find all Google Docs in the project folder

var docs = folder.getFilesByType("application/vnd.google-apps.document");

//Set up spreadsheet

var ss = SpreadsheetApp.openById(sheetId);
SpreadsheetApp.setActiveSpreadsheet(ss);
Logger.log('File name: ' + ss.getName());


  // specify the sheet to insert the results

 var sheet = ss.getSheetByName('Sheet1');


// Set up the spreadsheet to display the results

 var headers = [["File Name", "Test Paper Scanned", "PDF Link"]];
  sheet.getRange("A1:C").clear()
  sheet.getRange("A1:C1").setValues(headers);


 var output = [];

//Populate spreadsheet with OCR text

while (docs.hasNext()) {
    var file = docs.next();
    var docId = file.getId();
    var doc = DocumentApp.openById(docId);
    var name = doc.getName();
    var body = doc.getBody().getText();

       output.push([name, body, pdf]);

   // write data to the sheet

  sheet.getRange(2, 1, output.length, 3).setValues(output);

}};

【问题讨论】:

    标签: google-apps-script google-sheets


    【解决方案1】:

    您有一个不必要的循环,因此您失去了保存 PDF URL 的机会。我已经更改了您的代码顺序,以向您展示它是如何工作的。本质上,所有工作都发生在您遍历 PDF 的第一个循环中。*

    function extractTextOnOpen() {
      var folderName = "OCR TESTS";
      var sheetId = "SHEET'S ID HERE";
    
      //Set up spreadsheet
      var ss = SpreadsheetApp.openById(sheetId);
    
      // specify the sheet to insert the results  
      var sheet = ss.getSheetByName("Sheet1");
    
      // Set up the spreadsheet to display the results
      var headers = ["File Name", "Test Paper Scanned", "PDF Link"];
      sheet.getRange("A1:C").clear()
      var output = [headers];
    
      //Define Project folder
      var folder = DriveApp.getFoldersByName(folderName).next();
      var folderId = folder.getId();
    
      //Find all PDFs in folder
      var pdfs = folder.getFilesByType("application/pdf");
      while (pdfs.hasNext()) {
        //Convert each PDF to a Google Doc with OCR
        var pdf = pdfs.next();    
        var imageName = pdf.getName();
        var docName = imageName.split("\.")[0];
        var file = {
          title: docName,
          mimeType: "application/pdf"
        };
        var driveFile = Drive.Files.insert(file, pdf, { ocr: true });
    
        //Store newly-created Google Doc in the same project folder
        var newFile = DriveApp.getFileById(driveFile.id);
        folder.addFile(newFile);
        var rootFolder = DriveApp.getRootFolder();
        rootFolder.removeFile(newFile);
    
        //Get the Google Doc data
        var doc = DocumentApp.openById(driveFile.id);
        var name = doc.getName();
        var body = doc.getBody().getText();
        output.push([name, body, pdf.getUrl()]);
      }
      //Print to the sheet
      sheet.getRange(1, 1, output.length, output[0].length).setValues(output);
    }
    

    在上面的代码中,请注意 Drive API 返回一个file,因此在后续的.getFileById() 调用中会用到它。然后您可以使用.getUrl().getDownloadUrl()

    var driveFile = Drive.Files.insert(file, pdf, { ocr: true });
    
    //Store newly-created Google Doc in the same project folder
    var newFile = DriveApp.getFileById(driveFile.id);
    

    另外,您正在使用批处理 .setValues(),它更快,但您将它放在一个循环中。我更新了脚本以在最后只打印一次。

    * 如果您真的想遍历两个 PDF 循环,然后是 Google Docs,那么您需要在第一个循环中将 PDF ID 映射到 Google Doc ID。

    【讨论】:

    • 非常感谢,稍作改动即可正常工作,因为我收到sheet.getRange("A1:C").clear().appendRow(headers) 的错误(无法在对象范围中找到函数 appendRow),所以我已将其恢复为原来的样子?还有我使用.setValues 的原因是因为工作表具有从 D2 开始的公式,因此我需要将转换结果放在顶部,除非有更好的方法吗?您能否更新有关错误的代码,以便对遇到类似任务的任何人有用,再次感谢您的帮助。
    • @Nabnub 感谢您指出这一点。我更新了代码并对打印到工作表的方式进行了轻微修改。
    • 谢谢你。我已经接受了你的回答。我正在尝试一步一步地完成这个小项目。我目前正在尝试仅使用 5 个 PDF,执行时间约为 47 秒。我开始有点担心,当文件夹中大约有 25 个 PDF 文件时,我会用这种方法达到 6 分钟的执行限制吗? 也许我必须这样做发布另一个问题。
    • @Nabnub 你可能会!您拨打的某些电话速度很慢,您无能为力。循序渐进才是正确的方法。如果您还有其他问题,请发帖,有人会帮助您:)
    【解决方案2】:

    getUrl()这个方法呢?

    示例:

    var pdf = document.getUrl();

    【讨论】:

      猜你喜欢
      • 2022-12-18
      • 1970-01-01
      • 1970-01-01
      • 2018-09-03
      • 2018-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      相关资源
      最近更新 更多