所需工具

  1. pdf.js(负责API解析,可将pdf文件渲染成canvas实现预览)
  2. pdf.worker.js(负责核心解析)

工具下载

pdf.js及pdf.worker.js下载地址:
http://mozilla.github.io/pdf.js/getting_started/#download

我自己的下载地址:https://download.csdn.net/download/W_LIN/87814244

代码实现:

1、将pdf文件第一页转换为图片

/ 获取PDF文件
const pdfUrl = 'example.pdf';
const pdf = await pdfjsLib.getDocument(pdfUrl).promise;

// 获取第一页
const page = await pdf.getPage(1);

// 将页面转换为图片
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
const viewport = page.getViewport({ scale: 1 });
canvas.width = viewport.width;
canvas.height = viewport.height;
await page.render({ canvasContext: context, viewport }).promise;

// 将图片保存为PNG格式
const imgData = canvas.toDataURL('image/png');

实际应用,动态生成canvas

<div id="zz-canvas-container"></div>
async function pdfToCanvas(pdfUrl) {
// 获取PDF文件
const pdf = await pdfjsLib.getDocument(pdfUrl).promise;
// 获取第一页
const page = await pdf.getPage(1);
// 将页面转换为图片
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
var viewport = page.getViewport({scale: 1,});
var scale = (800 / viewport.width).toFixed(2)
viewport = page.getViewport({scale: scale});
canvas.width = viewport.width;
canvas.height = viewport.height;
page.render({canvasContext: context, viewport}).promise;
zzContainer.appendChild(canvas);
}

2、将PDF文件的所有页面转换为图片

// 获取PDF文件
const pdfUrl = 'example.pdf';
const pdf = await pdfLib.getDocument(pdfUrl).promise;

// 获取所有页面
const pages = Array.from({ length: pdf.numPages }, (_, i) => i + 1);

// 将每个页面转换为图片
const images = await Promise.all(pages.map(async (pageNumber) => {
  const page = await pdf.getPage(pageNumber);
  const canvas = document.createElement('canvas');
  const context = canvas.getContext('2d');
  const viewport = page.getViewport({ scale: 1 });
  canvas.width = viewport.width;
  canvas.height = viewport.height;
  await page.render({ canvasContext: context, viewport }).promise;
  return canvas.toDataURL('image/png');
}));

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐