【问题标题】:pdf.js: looping through pages searching for textpdf.js:循环搜索文本的页面
【发布时间】:2020-07-15 06:52:32
【问题描述】:

我想这更多是关于如何正确使用 Promises 的问题,我不明白:

根据这个网站 (https://ourcodeworld.com/articles/read/405/how-to-convert-pdf-to-text-extract-text-from-pdf-with-javascript),我们以这种方式从页面中提取文本:

// assume pdf file has been loaded
function getPageText(pageNum, PDFDocumentInstance) {
    // Return a Promise that is solved once the text of the page is retrieven
    return new Promise(function (resolve, reject) {
        PDFDocumentInstance.getPage(pageNum).then(function (pdfPage) {
            // The main trick to obtain the text of the PDF page, use the getTextContent method
            pdfPage.getTextContent().then(function (textContent) {
                var textItems = textContent.items;
                var finalString = "";

                // Concatenate the string of the item to the final string
                for (var i = 0; i < textItems.length; i++) {
                    var item = textItems[i];
                    finalString += item.str + " ";
                }
                // Solve promise with the text retrieven from the page
                resolve(finalString);
            });
        });
    });
}

我想在所有页面中搜索某个字符串,直到找到包含该字符串的页面。我尝试了在 for 循环中调用上述函数的明显错误方法,但不知道在找到字符串时如何结束。 感谢您的帮助!

【问题讨论】:

  • PDFDocumentInstance.getPage(pageNum) 已经返回了一个 Promise,将其包装在一个新的 Promise 中是一种反模式,请给我一点时间来修复您的代码
  • 这应该可以,希望:pastebin.com/cAvd9XBW
  • @ChrisG,感谢您重构上面的代码-我肯定会使用您的版本-但它没有回答我的问题,即如何在文档的页面中逐页搜索某个字符串。
  • 这是带有文本搜索模型的工作代码:jsfiddle.net/69hjL4tc 它使用内部带有await 的循环来按顺序搜索页面。也可以使用 Promise.all() 一次搜索所有页面,顺便说一句
  • 那个1s超时只是模拟实际异步操作的模型;小提琴只应该展示如何按顺序运行异步调用,直到满足某个条件

标签: javascript es6-promise pdf.js


【解决方案1】:

这是一个蹩脚的尝试。它是递归的(希望不是),虽然它找到了文本并进行了 resolve() 调用,但我不知道从哪里执行,因为它没有像我希望的那样记录到控制台:

  function findText() {
    var textToFind = document.getElementById('textToFind').value;
    findIt( 1, textToFind ).then( function( pageIndex ) {
      // the line below never gets called. i expected the resolve() method 
      // further down to come here.
      console.log( 'Found ' + textToFind + ' on page ' + pageIndex );
    },
    function(reason) {
      console.log(reason);
    });
  }

  function findIt( pageIndex, textToFind ) {
    return new Promise( function( resolve, reject ) {
      if ( pageIndex > pdfObject.numPages-1 ) {
        reject("Couldn't find " + textToFind);
      }
      getPageText( pageIndex ).then( function( pageText ) {
        if ( pageText.indexOf(textToFind) === -1 ) {
          findIt( pageIndex+1, textToFind );
        }
        else {
          resolve(pageIndex); // in the debugger, i get here
        }
      });
    });
  }

【讨论】:

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