引用站外地址
PDF.js
A general-purpose,web standards-based platform for parsing and rendering PDFs.
下载 PDF.js
在官网下载PDF.js
预构建包,只需要build
文件夹中的pdf.mjs
和pdf.worker.mjs
即可。
定义转换函数
在<script type="module">
中导入并使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| import * as pdfjsLib from '/js/pdf.mjs'; pdfjsLib.GlobalWorkerOptions.workerSrc = '/js/pdf.worker.mjs';
async function renderPdfToImage(url,pageNumber=1,scaleFactor=1) { const loadingTask = pdfjsLib.getDocument(url); const pdf = await loadingTask.promise;
const page = await pdf.getPage(pageNumber); const viewport = page.getViewport({ scale: scaleFactor });
const canvas = document.createElement('canvas'); const context = canvas.getContext('2d');
canvas.width = viewport.width; canvas.height = viewport.height;
const renderContext = { canvasContext: context, viewport: viewport, }; await page.render(renderContext).promise;
return canvas.toDataURL('image/png'); }
|
生成并下载图片
1 2 3 4 5 6 7 8 9 10
| const imageDataUrl = await renderPdfToImage('https://example.com/example.pdf');
const link = document.createElement('a'); link.href = imageDataUrl; link.download = `pdf图片.png`; document.body.appendChild(link); link.click(); document.body.removeChild(link);
|