使用PDF.js生成pdf的缩略图

And*_*vim 4 javascript php pdfjs

我想使用PDF.js从pdf文件生成缩略图,但它不像只有一个文件的其他js,并且所有需要在项目中包含js的是:

<script src="any.js"></script>
Run Code Online (Sandbox Code Playgroud)

如何在我的项目中使用PDF.js?我在后端使用PHP.

asy*_*nc5 10

基于helloworld示例:

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);
Run Code Online (Sandbox Code Playgroud)
<script src="//npmcdn.com/pdfjs-dist/build/pdf.js"></script>
Run Code Online (Sandbox Code Playgroud)

  • @async5:代码片段错误:`"message": "Uncaught ReferenceError: PDFJS is not defined",`你认为你可以修改你的答案/可运行片段吗?先感谢您。 (2认同)

小智 5

我发现,比例不是参数。参数是需要设置的具有比例字段的对象。

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