PDF.js Example to Load Local PDF File From File Input and Render it in Browser Using Javascript

PDF.js Example to Load Local PDF File From File Input and Render it in Browser Using Javascript Article has many meanings. We are going to know this topic clearly through this article. We hope you like this article.

PDF.js Example to Load Local PDF File From File Input and Render it in Browser Using Javascript

PDF.js Example to Load Local PDF File From File Input and Render it in Browser Using Javascript

<input type="file" id="pdf-upload" />
<hr /><canvas></canvas>

<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/1.8.349/pdf.min.js"></script>
document.querySelector("#pdf-upload").addEventListener("change", function(e){
    var canvasElement = document.querySelector("canvas")
    var file = e.target.files[0]
    if(file.type != "application/pdf"){
        console.error(file.name, "is not a pdf file.")
        return
    }
    
    var fileReader = new FileReader();  

    fileReader.onload = function() {
        var typedarray = new Uint8Array(this.result);

        PDFJS.getDocument(typedarray).then(function(pdf) {
            // you can now use *pdf* here
            console.log("the pdf has ",pdf.numPages, "page(s).")
            pdf.getPage(pdf.numPages).then(function(page) {
                // you can now use *page* here
                var viewport = page.getViewport(2.0);
                var canvas = document.querySelector("canvas")
                canvas.height = viewport.height;
                canvas.width = viewport.width;


                page.render({
                    canvasContext: canvas.getContext('2d'),
                    viewport: viewport
                });
            });

        });
    };

    fileReader.readAsArrayBuffer(file);
})

Read Also: Build a PDF.js and Bootstrap 4 PDF Document Viewer With Page Numbering in Javascript

Final Words

PDF.js Example to Load Local PDF File From File Input and Render it in Browser Using Javascript We got to know our topic very clearly. And if you have any doubts about this article you can let us know your doubts via comment.

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Deekshi. Here, I post about programming to help developers.

Share on:

Leave a Comment