Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating thumbnail of a pdf using PDF.js

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.

like image 628
Andre Alvim Avatar asked Jun 14 '17 14:06

Andre Alvim


People also ask

How do I get a PDF to show a thumbnail?

Open Acrobat DC or Acrobat Reader DC. On the Edit menu, choose Preferences. In the Preferences dialog box, choose General in the Categories list, and then select the Enable PDF thumbnail previews in Windows Explorer check box.

How do I make a PDF viewer in HTML?

Ways of putting a PDF document in HTML The easiest way to put PDF in an HTML document is using the <a> tag with its href attribute. You need to add the URL or the reference link of your PDF file to the element.


2 Answers

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>
like image 67
async5 Avatar answered Nov 17 '22 03:11

async5


I figured it out, the scale is not a parameter. The parameters are an object with field of scale that needed to be set.

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; 
    });
}
like image 22
Glen L Avatar answered Nov 17 '22 01:11

Glen L