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測試