第一步:下載pdf.js 下載地址:https://www.jsdelivr.com/package/npm/pdfjs-dist 打開後找到pdf.js、pdf.work.js以及cmaps路徑下的全部文件,下載到本地或者直接引用其地址 實例代碼 //HTML <canvas id="the-ca ...
第一步:下載pdf.js
下載地址:https://www.jsdelivr.com/package/npm/pdfjs-dist
打開後找到pdf.js、pdf.work.js以及cmaps路徑下的全部文件,下載到本地或者直接引用其地址
實例代碼
//HTML <canvas id="the-canvas"></canvas>
//JS引用 <script type="text/javascript" src="../../script/pdf.js"></script>
//JS使用pdf.JS代碼 var url = 'test.pdf'; PDFJS.cMapUrl = 'https://cdn.jsdelivr.net/npm/[email protected]/cmaps/';//字體解析 PDFJS.cMapPacked = true; //載入核心文件 PDFJS.workerSrc = '../../script/pdf.worker.js';//或者https://cdn.jsdelivr.net/npm/[email protected]/build/pdf.worker.js var loadingTask = PDFJS.getDocument(url); loadingTask.promise.then(function(pdf) { console.log('PDF loaded'); var pageNumber = 1; pdf.getPage(pageNumber).then(function(page) { console.log('Page loaded'); var scale = 1; var viewport = page.getViewport(scale); var canvas = document.getElementById('the-canvas'); var context = canvas.getContext('2d'); canvas.height = viewport.height; canvas.width = viewport.width; var renderContext = { canvasContext: context, viewport: viewport }; var renderTask = page.render(renderContext); renderTask.then(function () { console.log('Page rendered'); }); }); }, function (reason) { console.error(reason); });