skip to Main Content

I have an example of two websites that uses google drive and whenever they have a new document they just change unique id (drive uploaded document) in URL (after ?id=) and than the documentis display in on a canvas. It’s also SEO friendly and indexed by google. So what should be it’s raw code?

I just want to use google drive for storage and call document on my website’s pdf.js canvas for increase page view, user time, and display ads on PDF web pages like the demo that above.

3

Answers


  1. Here are is the demo for PDF.JS showing PDF in the webpage

    var url = 'https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/web/compressed.tracemonkey-pldi-09.pdf'; //Loaading the PDF from URL
    
    // Loaded via <script> tag, create shortcut to access PDF.js exports.
    var pdfjsLib = window['pdfjs-dist/build/pdf'];
    
    // The workerSrc property shall be specified.
    pdfjsLib.GlobalWorkerOptions.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';
    
    var pdfDoc = null,
        pageNum = 1,
        pageRendering = false,
        pageNumPending = null,
        scale = 0.8,
        canvas = document.getElementById('canvas'),
        ctx = canvas.getContext('2d');
    
    /**
     * Get page info from document, resize canvas accordingly, and render page.
     * @param num Page number.
     */
    function renderPage(num) {
      pageRendering = true;
      // Using promise to fetch the page
      pdfDoc.getPage(num).then(function(page) {
        var viewport = page.getViewport({scale: scale});
        canvas.height = viewport.height;
        canvas.width = viewport.width;
    
        // Render PDF page into canvas context
        var renderContext = {
          canvasContext: ctx,
          viewport: viewport
        };
        var renderTask = page.render(renderContext);
    
        // Wait for rendering to finish
        renderTask.promise.then(function() {
          pageRendering = false;
          if (pageNumPending !== null) {
            // New page rendering is pending
            renderPage(pageNumPending);
            pageNumPending = null;
          }
        });
      });
    
      // Update page counters
      document.getElementById('page_num').textContent = num;
    }
    
    /**
     * If another page rendering in progress, waits until the rendering is
     * finised. Otherwise, executes rendering immediately.
     */
    function queueRenderPage(num) {
      if (pageRendering) {
        pageNumPending = num;
      } else {
        renderPage(num);
      }
    }
    
    /**
     * Displays previous page.
     */
    function onPrevPage() {
      if (pageNum <= 1) {
        return;
      }
      pageNum--;
      queueRenderPage(pageNum);
    }
    document.getElementById('prev').addEventListener('click', onPrevPage);
    
    /**
     * Displays next page.
     */
    function onNextPage() {
      if (pageNum >= pdfDoc.numPages) {
        return;
      }
      pageNum++;
      queueRenderPage(pageNum);
    }
    document.getElementById('next').addEventListener('click', onNextPage);
    
    /**
     * Asynchronously downloads PDF.
     */
    pdfjsLib.getDocument(url).promise.then(function(pdfDoc_) {
      pdfDoc = pdfDoc_;
      document.getElementById('page_count').textContent = pdfDoc.numPages;
    
      // Initial/first page rendering
      renderPage(pageNum);
    });
    #canvas {
      border: 1px solid black;
    }
    button{
      border: none;
      background: #000;
      color: #fff;
      margin: 10px;
      padding: 10px;
    }
    <script src="//mozilla.github.io/pdf.js/build/pdf.js"></script>
    
    <h1>PDF.js Example</h1>
    
    <div>
      <button id="prev">Previous</button>
      <button id="next">Next</button>
      &nbsp; &nbsp;
      <span>Page: <span id="page_num"></span> / <span id="page_count"></span></span>
    </div>
    
    <canvas id="canvas"></canvas>

    For more details and documentation visit:

    https://mozilla.github.io/pdf.js/getting_started/

    Login or Signup to reply.
  2. Changed pdf URLs to see the result

    Tested here:
    https://codepen.io/max-makhrov/pen/JjpLxXP

    Here’re failed URLs:

    https://drive.google.com/open?id=1MUgtKfMqpyTtTFt2hEff23Emcg14Cj4O
    https://drive.google.com/1MUgtKfMqpyTtTFt2hEff23Emcg14Cj4O/export?exportFormat=pdf&format=pdf
    https://drive.google.com/export?id=1MUgtKfMqpyTtTFt2hEff23Emcg14Cj4O
    https://drive.google.com/uc?export=download&id=1MUgtKfMqpyTtTFt2hEff23Emcg14Cj4O&exportFormat=pdf&format=pdf
    https://drive.google.com/uc?export=download&format=pdf&id=1MUgtKfMqpyTtTFt2hEff23Emcg14Cj4O
    https://drive.google.com/uc?export?format=pdf&id=1MUgtKfMqpyTtTFt2hEff23Emcg14Cj4O
    https://docs.google.com/viewer?srcid=1MUgtKfMqpyTtTFt2hEff23Emcg14Cj4O&pid=explorer&efh=false&a=v&chrome=false&embedded=true
    https://drive.google.com/file/d/1MUgtKfMqpyTtTFt2hEff23Emcg14Cj4O/
    https://drive.google.com/file/export?format=pdf&id=1MUgtKfMqpyTtTFt2hEff23Emcg14Cj4O
    

    Here’s a surprise: you may use a range from existing Google Sheet if it has an Access. This URL works:

    https://docs.google.com/spreadsheets/d/1qNQ6iCMoBCQgJzBB63ymtBQ6BedXZFhjgZZKGItjeVA/export?exportFormat=pdf&format=pdf&size=1.87x1.386&portrait=true&scale=2&top_margin=0&bottom_margin=0&left_margin=0&right_margin=0&sheetnames=false&printtitle=false&horizontal_alignment=LEFT&gridlines=false&fmcmd=12&gid=0&r1=1&r2=7&c1=1&c2=4
    
    Login or Signup to reply.
  3. I added a demo to load pdf with lazy load. We need to implement drive api to fetch the pdf from drive or it will give cross-origin error.

    <!DOCTYPE html>
    <html>
      <head>
        <title>PDF Demo for Qdev</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/build/pdf.min.js"></script>
        <style>
            body {
                margin: 0;
                background-color: #dfdfdf; /* Grey background */
            }
            .center {
                text-align: center; /* center pages */
            }
        </style>
      </head>
      <body>
          <div id="pages" class="center"></div>
          <script>
            // download the pdf
            var pdfTask = pdfjsLib.getDocument("https://atikur-rabbi.github.io/data/sample.pdf");
            // parse the get params
            var queryString = window.location.hash.split("#")[1];
            // default params
            var params = {pg: 1};
            var pagen = 0;
            // if get params are present
            if (queryString) {
                // update the default settings
                params = Object.assign(params, parseParams(queryString));
            }
            // Load the pages div from the DOM
            var pages = document.getElementById("pages");
            // handle the pdf once loaded (asyncronous)
            pdfTask.promise.then(function(pdf) {
                // globalize pdf
                window.pdf = pdf;
                // load the first page
                loadPage(pdf, parseInt(params.pg));
                pagen++;
            });
            // stores the page number of the page currently in the viewport
            var curpage = parseInt(params.pg) + pagen;
            // every half a second, check for scroll updates
            setInterval(function() {
                // if we're within 200px of the bottom of the page
                if (document.body.scrollHeight - (window.scrollY + window.innerHeight) < 200) {
                    if (window.pdf != undefined) {
                        // load 5 more pages
                        for (var i=0; i<5; i++) {
                            loadPage(pdf, parseInt(params.pg)+pagen);
                            pagen++;
                        }
                    }
                }
                // if the page in our viewport has changed, update the url
                if (curpage != parseInt(params.pg) + parseInt(window.scrollY /
                        (document.body.scrollHeight / pagen))) {
                    curpage = parseInt(params.pg) + parseInt(window.scrollY /
                        (document.body.scrollHeight / pagen));
                    window.location.hash = "#pg=" + curpage;
                }
            }, 500);
    
            // render `pg` from `pdf` and append it to the pages div
            function loadPage(pdf, pg){
                pdf.getPage(pg).then(function(page){
                    var scale = 1.7;
                    var viewport = page.getViewport({scale: scale});
                    var canvas = document.createElement('canvas');
                    var context = canvas.getContext('2d');
    
                    canvas.id = "page-" + pg;
                    canvas.height += viewport.height;
                    canvas.width = viewport.width;
    
                    pages.appendChild(canvas);
    
                    var renderContext = {
                        canvasContext: context,
                        viewport: viewport
                    };
                    page.render(renderContext);
                });
            }
    
            // parses get params from a query string into an object
            function parseParams(queryString) {
                var query = {};
                var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
                for (var i = 0; i < pairs.length; i++) {
                    var pair = pairs[i].split('=');
                    query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
                }
                return query;
            }
          </script>
      </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search