【发布时间】:2020-07-15 06:52:32
【问题描述】:
我想这更多是关于如何正确使用 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);
});
});
});
}
我想在所有页面中搜索某个字符串,直到找到包含该字符串的页面。我尝试了在 for 循环中调用上述函数的明显错误方法,但不知道在找到字符串时如何结束。 感谢您的帮助!
【问题讨论】:
-
PDFDocumentInstance.getPage(pageNum)已经返回了一个 Promise,将其包装在一个新的 Promise 中是一种反模式,请给我一点时间来修复您的代码 -
这应该可以,希望:pastebin.com/cAvd9XBW
-
@ChrisG,感谢您重构上面的代码-我肯定会使用您的版本-但它没有回答我的问题,即如何在文档的页面中逐页搜索某个字符串。
-
这是带有文本搜索模型的工作代码:jsfiddle.net/69hjL4tc 它使用内部带有
await的循环来按顺序搜索页面。也可以使用 Promise.all() 一次搜索所有页面,顺便说一句 -
那个1s超时只是模拟实际异步操作的模型;小提琴只应该展示如何按顺序运行异步调用,直到满足某个条件
标签: javascript es6-promise pdf.js