我是ES6和Promise的新手。我正在尝试pdf.js将pdf文件所有页面的文本提取到字符串数组中。当提取完成后,我想以某种方式解析数组。说pdf文件(正确通过typedarray
传递)具有4
页,我的代码是:
let str = [];
PDFJS.getDocument(typedarray).then(function(pdf) {
for(let i = 1; i <= pdf.numPages; i++) {
pdf.getPage(i).then(function(page) {
page.getTextContent().then(function(textContent) {
for(let j = 0; j < textContent.items.length; j++) {
str.push(textContent.items[j].str);
}
parse(str);
});
});
}
});
它可以正常工作,但是,当然,问题是我的
parse
函数称为4
倍。我只想在完成所有4页提取后才调用parse
。 最佳答案
与https://stackoverflow.com/a/40494019/1765767相似-使用Promise.all收集页面 promise ,不要忘记链接以下内容:
function gettext(pdfUrl){
var pdf = PDFJS.getDocument(pdfUrl);
return pdf.then(function(pdf) { // get all pages text
var maxPages = pdf.pdfInfo.numPages;
var countPromises = []; // collecting all page promises
for (var j = 1; j <= maxPages; j++) {
var page = pdf.getPage(j);
var txt = "";
countPromises.push(page.then(function(page) { // add page promise
var textContent = page.getTextContent();
return textContent.then(function(text){ // return content promise
return text.items.map(function (s) { return s.str; }).join(''); // value page text
});
}));
}
// Wait for all pages and join text
return Promise.all(countPromises).then(function (texts) {
return texts.join('');
});
});
}
// waiting on gettext to finish completion, or error
gettext("https://cdn.mozilla.net/pdfjs/tracemonkey.pdf").then(function (text) {
alert('parse ' + text);
},
function (reason) {
console.error(reason);
});
<script src="https://npmcdn.com/pdfjs-dist/build/pdf.js"></script>
关于javascript - 如何使用pdf.js从pdf正确提取文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40635979/