Tôi đã thực hiện một cách tiếp cận dễ dàng hơn mà không cần đăng thông báo giữa các iframe bằng cùng một thư viện (sử dụng phiên bản mới nhất), using pdf.js.
Ví dụ sau sẽ trích xuất tất cả các văn bản chỉ từ trang đầu tiên của file 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);
});
Read the article about this solution here. Như @xarxziux đã đề cập, thư viện đã thay đổi kể từ khi giải pháp đầu tiên được đăng (nó không nên hoạt động với phiên bản mới nhất của pdf.js nữa). Điều này sẽ làm việc cho hầu hết các trường hợp.
Nguồn
2017-03-05 09:37:34
Cảm ơn bạn, nó đã hoạt động cho tôi: D – Coccinelle
Lưu ý cho những người dùng Google trong tương lai: dự án pdf.js chính thức dường như đã thay đổi nhiều lần kể từ khi các liên kết ở trên được đăng, nhưng hiện tại nó nằm trong trang GitHub của Mozilla - https://github.com/mozilla/pdf.js – xarxziux