Generating thumbnail of a pdf using PDF.js

谁说胖子不能爱 提交于 2019-11-27 16:57:25

问题


I would like to generate a thumbnail from a pdf file using PDF.js, but it isn't like anothers js that have just one file and all needed to include the js in your project is to write:

<script src="any.js"></script>

How can I use PDF.js in my project? I'm using PHP in backend.


回答1:


Based on helloworld example:

function makeThumb(page) {
  // draw page to fit into 96x96 canvas
  var vp = page.getViewport(1);
  var canvas = document.createElement("canvas");
  canvas.width = canvas.height = 96;
  var scale = Math.min(canvas.width / vp.width, canvas.height / vp.height);
  return page.render({canvasContext: canvas.getContext("2d"), viewport: page.getViewport(scale)}).promise.then(function () {
    return canvas;
  });
}

pdfjsLib.getDocument("https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/web/compressed.tracemonkey-pldi-09.pdf").promise.then(function (doc) {
  var pages = []; while (pages.length < doc.numPages) pages.push(pages.length + 1);
  return Promise.all(pages.map(function (num) {
    // create a div for each page and build a small canvas for it
    var div = document.createElement("div");
    document.body.appendChild(div);
    return doc.getPage(num).then(makeThumb)
      .then(function (canvas) {
        div.appendChild(canvas);
    });
  }));
}).catch(console.error);
<script src="//npmcdn.com/pdfjs-dist/build/pdf.js"></script>


来源:https://stackoverflow.com/questions/44547585/generating-thumbnail-of-a-pdf-using-pdf-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!