这是一个古老的问题,但是由于pdf.js多年来一直在发展,所以我想给出一个新的答案。也就是说,它可以在本地完成,而无需涉及任何服务器或外部服务。新的pdf.js具有一个函数:page.getTextContent()。您可以从中获取文本内容。我已经用下面的代码成功地做到了。
- 您在每个步骤中得到的都是诺言。您需要采用以下方式进行编码:
.then( function(){...})继续进行下一步。
1)
PDFJS.getdocument( data ).then( function(pdf) {2)
pdf.getPage(i).then( function(page){3)
page.getTextContent().then( function(textContent){您最终得到的是一个字符串数组
textContent.bidiTexts[]
。您将它们串联起来可获得1页的文本。文本块的坐标用于判断是否需要插入换行符或空格。(这可能并不完全可靠,但是从我的测试来看,这似乎还可以。)输入参数
data
必须是URL或ArrayBuffer类型的数据。我在FileReader
API中使用ReadAsArrayBuffer(file)函数 来获取数据。
希望这可以帮助。
注意: 根据其他用户的说法,该库已更新并导致代码中断。根据下面 async5
的评论,您需要替换
textContent.bidiTexts为
textContent.items。
function Pdf2TextClass(){ var self = this; this.complete = 0; this.pdfToText = function(data, callbackPageDone, callbackAllDone){ console.assert( data instanceof ArrayBuffer || typeof data == 'string' ); PDFJS.getdocument( data ).then( function(pdf) { var div = document.getElementById('viewer'); var total = pdf.numPages; callbackPageDone( 0, total ); var layers = {}; for (i = 1; i <= total; i++){ pdf.getPage(i).then( function(page){ var n = page.pageNumber; page.getTextContent().then( function(textContent){ if( null != textContent.bidiTexts ){ var page_text = ""; var last_block = null; for( var k = 0; k < textContent.bidiTexts.length; k++ ){ var block = textContent.bidiTexts[k]; if( last_block != null && last_block.str[last_block.str.length-1] != ' '){ if( block.x < last_block.x ) page_text += "rn"; else if ( last_block.y != block.y && ( last_block.str.match(/^(s?[a-zA-Z])$|^(.+s[a-zA-Z])$/) == null )) page_text += ' '; } page_text += block.str; last_block = block; } textContent != null && console.log("page " + n + " finished."); //" content: n" + page_text); layers[n] = page_text + "nn"; } ++ self.complete; callbackPageDone( self.complete, total ); if (self.complete == total){ window.setTimeout(function(){ var full_text = ""; var num_pages = Object.keys(layers).length; for( var j = 1; j <= num_pages; j++) full_text += layers[j] ; callbackAllDone(full_text); }, 1000); } }); // end of page.getTextContent().then }); // end of page.then } // of for }); }; // end of pdfToText()}; // end of class


