add pdf viewer to website easily Full guide 2022

    By: Thad Mertz
    2 years ago

    Hi devs In this guide we are going to add Pdf viewer to a Laravel / PHP application. So lets see how we can add it. So we need to have a project where we want to add pdf viewer feature.


    Don't have project, Then Create a Project


    We create a laravel project go to these link for complete guide.

    Full installation guide

    Documentation

    For basic setup you need composer and node js Installed in your system. And then you can run these commands to create Laravel project.

    // Creates project.
    
    composer create-project laravel/laravel projectName 
    
    // Get into project folder using terminal/cmd.
    cd example-app
    
    // Run server to see project.
    php artisan serve
    


    Work with UI for pdf viewer


    In any application you can go to main HTML or PHP. file where the UI (user interface) is powered from. And there we can add some html content. In Laravel we need to go to recourse/views directory. There by default laravel provides "welcome.blade.php". You can use this file.

    Our HTML code for PDF Viewer Looks like this

    <body class="antialiased text-center mt-5">
        <div class="container text-center">
            <div class="jumbotron">
                <h2 class="display-4">Pdf Viewer</h2>
            </div>
        </div>
        <div class="row justify-content-md-center m-3 p-3">
            <button class="btn btn-primary col-3 p-2 m-2" id="prev-page"
            onclick="PdfViewer.showPrevPage()">Prev</button>
            <button class="btn btn-info col-3 p-2 m-2" id="next-page"
            onclick="PdfViewer.showNextPage()">Next</button>
        </div>
        <div class="row justify-content-md-center">
            <canvas id="pdfArea"  class="pdfArea justify-content-center">
            </canvas>
        </div>
    </body>
    

    We need to have minor css for styling. You can customize it more if you want to.

    // add this css in welcome.blade.php to match the guide.
    
    <style>
        body {
            font-family: 'Nunito', sans-serif;
        }
    
        .pdfCanvas{
            width:100%;
            height:500px;
            border: solid 1px red;
        }
    </style>
    


    Include Bootstrap cdn

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    


    Add Pdf viewer functionality using javascript


    create a file named "main.js" in "public/assets/js/main.js".

    and include this file in welcome.blade.php like this along with

    pdf.js cdn

    Check Abut pdfjs package here

    <script src="https://mozilla.github.io/pdf.js/build/pdf.js"></script>
    <script src="{ asset('assets/js/main.js') }"></script>
    

    Code in main.js file looks like this

    class PdfViewer {
        url = '../../pdf/pdf.pdf';
        static pdfDoc = null;
        static pageNum = 1;
        static numPages = 0;
    
        constructor() {
            this.getData(PdfViewer.pageNum);
        }
    
        getData(pageNum){
            // Get Document
            pdfjsLib
                .getDocument(this.url)
                .promise.then(res => {
                PdfViewer.pdfDoc = res;
                PdfViewer.numPages = PdfViewer.pdfDoc.numPages;
    
                PdfViewer.renderPage(pageNum);
            });
        }
    
        // Render the page
        static renderPage(num) {
            let canvas = document.querySelector('#pdfArea');
            let ctx = canvas.getContext('2d');
    
            let scale = 1.5;
            // Get page
            PdfViewer.pdfDoc.getPage(num).then(page => {
                // Set scale
                const viewport = page.getViewport({ scale });
                canvas.height = viewport.height;
                canvas.width = viewport.width;
    
                const renderCtx = {
                    canvasContext: ctx,
                    viewport
                };
    
                page.render(renderCtx);
            });
        }
    
        static reRenderCanvas(){
            setTimeout(()=>{
                PdfViewer.renderPage(PdfViewer.pageNum);
            },1000);
        }
    
    
    
        // Show Prev Page
        static showPrevPage() {
            if (PdfViewer.pageNum <= 1) {
                return;
            }
            PdfViewer.pageNum--;
            this.reRenderCanvas();
        }
    
        // Show Next Page
        static showNextPage() {
    
            if (PdfViewer.pageNum >= PdfViewer.numPages) {
                return;
            }
            PdfViewer.pageNum++;
            this.reRenderCanvas();
        }
    
    }
    


    Having doubts about how this code works, check our video guide. It explains everything.