Preview PDF file on website developed with PHP, Jquery and CSS3

Asked

Viewed 319 times

1

I saw on the Dropbox website that my PDF extension files are displayed a preview of the first page of the file, I searched for solutions on the internet for it but saw that there are only ways to embed the PDF in iframe or using a google drive URL to display itlo, I would like to do the same on my website, but do not use these suggestions that displays everything, because there are many PDF’s and will be heavy loading the screen, I would like to know how to take this print of the first page of the PDF, as is done in Dropbox. The files are with the path saved in the database, the physical files in an upload page, on the website I make use of PHP, jQuery and CSS3.

Thank you.

1 answer

3


Use the PDF.js

First download the PDF.js and take all scripts and add to your project, then on your page, on <head> should add:

<script src="build/pdf.js"></script>

To get the first page (or any other ) use getPage

var pdfjsLib = window['pdfjs-dist/build/pdf'];

pdfjsLib.getDocument('helloworld.pdf').then(function (pdf) {
    pdf.getPage(1).then(function(page) {
        var scale = 1.5; //Scala inicial desejada, ajuste como quiser

        var viewport = page.getViewport(scale);

        var canvas = document.getElementById('meuCanvas');
        var context = canvas.getContext('2d');
        canvas.height = viewport.height;
        canvas.width = viewport.width;

        page.render({
          canvasContext: context,
          viewport: viewport
        });
    });
});

And there should be a canvas on the page (or generate), with its contents:

<canvas id="meuCanvas"></canvas>
  • 1

    gratitude William.

  • In var canvas = Document.getElementById('the-canvas'); it should not be var canvas = Document.getElementById('meuCanvas'); ?

  • 1

    @Eliseub. Yes, typo, sorry. Fixed ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.