# pdf-preview **Repository Path**: lemonnan/pdf-preview ## Basic Information - **Project Name**: pdf-preview - **Description**: pdf预览以及识别文字 - **Primary Language**: JavaScript - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 4 - **Forks**: 1 - **Created**: 2021-03-19 - **Last Updated**: 2023-08-31 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # PDFJS预览与文字识别 ## pdfjs官网 http://mozilla.github.io/pdf.js/ ## Demo [Demo](https://lemonnan.gitee.io/pdf-preview/index.html) ## 使用方法 ```javascript //用 promise 获取页面 PDFJS.getDocument(fileURL).then(function (pdf) { }); // 获取i页的页面 pdf.getPage(i).then(function (page) { }) // 识别pdf中文本 page.getTextContent().then(function(textContent) { for(let j = 0; j < textContent.items.length; j++) { // textContent.items[j].str为识别到的文本字符串 } }); // 渲染pdf var renderTask = page.render(renderContext); renderTask.promise.then(function() { // 渲染完成 }); ``` ## 若字体未显示或者乱码,检查是否设置cMapUrl ```javascript PDFJS.cMapUrl = '/assets/pdfjs/cmaps/'; PDFJS.cMapPacked = true; ``` ## 注意 如果未加载成功,检查一下pdf路径是否正确,是否在同一域名下, 例如报错:Access to XMLHttpRequest at 'file:///D:/myFile/mywork/project/pdfjs/test.pdf' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https 可本地安装服务器进行测试,也可使用vscode的Live Server插件(index.html上点击右键选择Open with Live Server自动打开浏览器)