PDF.js 是一个使用 HTML5 构建的可移植文档格式(PDF)查看器。使用的前提是浏览器要支持 html5。
PDF.js 由社区驱动,并获得 Mozilla Labs 的支持。 目标是建立一个通用的,基于 Web 标准的平台,用于解析和呈现 PDF。html
pdfjshtml5
demogit
The goal is to support all HTML5 compliant browsers, but sincefeature support varies per browser/version our support for all PDF featuresvaries as well. If you want to support more browsers than Firefox you'll needto include compatibility.jswhich has polyfills for missing features. Find the list offeatures needed for PDF.js to properly work and browser tests for thosefeatures at RequiredBrowser Features. In general, the support is below:github
咱们的目标是支持全部 HTML5 兼容的浏览器,可是每一个浏览器/版本对 PDF 的全部特性的支持是不一样的。若是你想支持除了 Firefox 之外的更多种浏览器,你须要有 compatibility.js 文件,它有 polyfills 丢失的功能。想查找 PDF.js 正常工做所需的浏览器的测试要求,请参考以下浏览器特性的列表:web
安装 npm install pdfjs-dist
npm
引入 import PDFJS from 'pdfjs-dist'
canvas
上传浏览器
<input type="file" accept=".pdf" :id="uniqueId" @change="onFileChange" ref="file" class="inputfile"/> onFileChange() { const file = this.$refs.file.files[0]; this.fileName = file ? file.name : '请选择文件'; this.file = file }
解析渲染app
<div id="pdf-viewer"></div> extractPdfContent() { if(this.file.type != "application/pdf"){ console.error(this.file.name, "is not a pdf file.") return } var fileReader = new FileReader(); fileReader.onload = function() { var typedarray = new Uint8Array(this.result); var pdfContainer = document.getElementById('pdf-viewer'); PDFJS.getDocument(typedarray).then(function(pdf) { // you can now use *pdf* here let arr = [] for(let i = 1; i<= pdf.numPages;i++) { arr.push(pdf.getPage(i)) } //这里的处理是为了不pdf渲染乱序 Promise.all(arr).then(function(pages) { for(let j = 0; j< pdf.numPages;j++) { let page = pages[j] var viewport = page.getViewport(2.0); var canvasNew = document.createElement('canvas'); canvasNew.style.width = '100%'; canvasNew.id = `pdf_${page.pageNumber}`; canvasNew.height = viewport.height; canvasNew.width = viewport.width; page.render({ canvasContext: canvasNew.getContext('2d'), viewport: viewport }); pdfContainer.appendChild(canvasNew) } }); }) } fileReader.readAsArrayBuffer(this.file); }
https://mozilla.github.io/pdf...
How to render a full PDF using Mozilla's pdf.js测试