pdfjs使用npm,如何使用pdf.js从pdf正确提取文本

I'm new to ES6 and Promise. I'm trying pdf.js to extract texts from all pages of a pdf file into a string array. And when extraction is done, I want to parse the array somehow. Say pdf file(passed via typedarray correctly) has 4 pages and my code is:

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);

});

});

}

});

It manages to work, but, of course, the problem is my parse function is called 4 times. I just want to call parse only after all 4-pages-extraction is done.

解决方案

Similar to https://stackoverflow.com/a/40494019/1765767 -- collect page promises using Promise.all and don't forget to chain then's:

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);

});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值