pdf. js: просмотр страниц в поисках текста - PullRequest
0 голосов
/ 14 июля 2020

Я думаю, это скорее вопрос о том, как правильно использовать 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);
            });
        });
    });
}

Я хочу искать определенную строку на всех страницах, пока не найду страницу с этой строкой. Я пробовал явно неправильный способ вызвать указанную выше функцию для l oop, но не знал, как закончить, когда строка была найдена. Спасибо за помощь!

1 Ответ

0 голосов
/ 15 июля 2020

вот и неудачная sh попытка. он рекурсивный (wi sh это не было), и хотя он находит текст и переходит к вызову 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
        }
      });
    });
  }

...