Извлечение текста из pdf-файла с помощью javascript

Я хочу извлечь текст из pdf-файла, используя только Javascript на стороне клиента без использования сервера. Я уже нашел код JavaScript в следующей ссылке: извлечение текста из pdf в Javascript

и затем в

http://hublog.hubmed.org/archives/001948.html

и здесь:

https://github.com/hubgit/hubgit.github.com/tree/master/2011/11/pdftotext

1) я хочу пожалуйста, чтобы узнать, какие файлы необходимы для этих извлечения из предыдущих. 2) я точно не знаю, как адаптировать эти коды в приложении, а не в интернете.

любой ответ приветствуется. Спасибо.

2 ответов


вот хороший пример того, как использовать pdf.js для извлечения текста: http://git.macropus.org/2011/11/pdftotext/example/

конечно, вам нужно удалить много кода для вашей цели, но он должен это сделать


Я сделал более простой подход, который не должен публиковать сообщения между iframes, используя ту же библиотеку (используя последнюю версию), использование pdf.js.

в следующем примере будет извлечен весь текст только с первой страницы PDF:

/**
 * Retrieves the text of a specif page within a PDF Document obtained through pdf.js 
 * 
 * @param {Integer} pageNum Specifies the number of the page 
 * @param {PDFDocument} PDFDocumentInstance The PDF document obtained 
 **/
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);
            });
        });
    });
}

/**
 * Extract the test from the PDF
 */

var PDF_URL  = '/path/to/example.pdf';
PDFJS.getDocument(PDF_URL).then(function (PDFDocumentInstance) {

    var totalPages = PDFDocumentInstance.pdfInfo.numPages;
    var pageNumber = 1;

    // Extract the text
    getPageText(pageNumber , PDFDocumentInstance).then(function(textPage){
        // Show the text of the page in the console
        console.log(textPage);
    });

}, function (reason) {
    // PDF loading error
    console.error(reason);
});

Читать статью об этом решении здесь. Как упоминалось в @xarxziux, библиотека изменилась с момента публикации первого решения (она не должна работать с последней версией pdf.Яш больше.) Это должно сработать в большинстве случаев.