Skip to content

JS PDF 转图片

Published: at 05:58 PMSuggest Changes

记一下 PDf 转图片

function draw() {
  var canvas = document.createElement('canvas'),
    ctx = canvas.getContext('2d');
  canvas.width = width;
  canvas.height = height;
  for (var i = 0; i < pages.length; i++)
    ctx.putImageData(pages[i], 0, heights[i]);
  document.body.appendChild(canvas);
}
PDFJS.disableWorker = true; // due to CORS
PDFJS.getDocument(url).then(function (pdf) {
  getPage();

  function getPage() {
    pdf.getPage(currentPage).then(function (page) {
      console.log('Printing ' + currentPage);
      var viewport = page.getViewport(scale);
      var canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d');
      var renderContext = { canvasContext: ctx, viewport: viewport };

      canvas.height = viewport.height;
      canvas.width = viewport.width;

      page.render(renderContext).promise.then(function () {
        pages.push(ctx.getImageData(0, 0, canvas.width, canvas.height));

        heights.push(height);
        height += canvas.height;
        if (width < canvas.width) width = canvas.width;

        if (currentPage < pdf.numPages) {
          currentPage++;
          getPage();
        } else {
          draw();
        }
      });
    });
  }
});

还有另外一套比较好使的

function onUpload(files) {
  if (files.length !== 1) return;
  const file = files[0];
  let reader = new FileReader();
  reader.onload = e => {
    const data = atob(e.target.result.replace(/.*base64,/, ''));
    renderPDF(data);    
  }
  
  reader.readAsDataURL(file);
}
 

async function renderPDF(data) {
  const pdf = await pdfjsLib.getDocument({data}).promise;
  
  for (let i = 1; i <= pdf.numPages; i++) {
    const image = document.createElement('img');
    document.body.appendChild(image);
    
    const page = await pdf.getPage(i);
    const viewport = page.getViewport({scale: 2});
    const canvas = document.createElement('canvas');
    const canvasContext = canvas.getContext('2d');
    canvas.height = viewport.height;
    canvas.width = viewport.width;
    await page.render({canvasContext, viewport}).promise;
    const data = canvas.toDataURL('image/png');
    image.src = data;
    image.style.width = '100%';
  }
}

参考文章


Previous Post
CSS: 视频相对容器全宽
Next Post
使用 JavaScript 裁剪 Canvas 画布