pdfjs转图片_PDF转图片,在线PDF转JPG/PNG

原理

使用pdf.js预览图片,pdf.js将pdf通过canvas将每一页渲染出来,然后我们通过canvas的toDataURL方法保存为jpg或png格式。

pdf.js是Mozilla开源的一个js库,无需任何本地支持就可以在浏览器上显示pdf文档。唯一的要求就是浏览器必须支持HTML5。

依赖

需要pdf.min.js和pdf.worker.min.js两个js文件

全部代码实现

pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdn.bootcss.com/pdf.js/2.2.228/pdf.worker.min.js';

const preview = document.getElementById('preview');

const page_num = document.getElementById('page_num');

const out_type = document.getElementById('out_type');

let pdfFile, pdf, pageNum, context = preview.getContext('2d');

out_type.querySelectorAll('.button').forEach(function (btn) {

btn.onclick = function () {

out_type.querySelector('.primary').classList.remove('primary');

btn.classList.add('primary');

你可能感兴趣的:(pdfjs转图片)