第一步:下载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/pdfjs-dist@2.2.228/cmaps/';//字体解析
PDFJS.cMapPacked = true;
//加载核心文件
PDFJS.workerSrc = '../../script/pdf.worker.js';//或者https://cdn.jsdelivr.net/npm/pdfjs-dist@2.3.200/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);
});
来源:oschina
链接:https://my.oschina.net/u/4255236/blog/3234608