Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to render a full PDF using Mozilla's pdf.js
<html>
<body>
<!-- really dirty! this is just a test drive ;) -->
<script type="text/javascript" src="https://raw.github.com/mozilla/pdf.js/gh-pages/build/pdf.js"></script>
<script type="text/javascript">
function renderPDF(url, canvasContainer, options) {
var options = options || { scale: 1 };
function renderPage(page) {
var viewport = page.getViewport(options.scale);
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var renderContext = {
canvasContext: ctx,
viewport: viewport
};
canvas.height = viewport.height;
canvas.width = viewport.width;
canvasContainer.appendChild(canvas);
page.render(renderContext);
}
function renderPages(pdfDoc) {
for(var num = 1; num <= pdfDoc.numPages; num++)
pdfDoc.getPage(num).then(renderPage);
}
PDFJS.disableWorker = true;
PDFJS.getDocument(url).then(renderPages);
}
</script>
<div id="holder"></div>
<script type="text/javascript">
renderPDF('sample.pdf', document.getElementById('holder'));
</script>
</body>
</html>
@Diffio

This comment has been minimized.

Copy link

@Diffio Diffio commented Apr 22, 2013

Thank you!!!

@resendes

This comment has been minimized.

Copy link

@resendes resendes commented Aug 4, 2014

nice :)

@coderaw8

This comment has been minimized.

Copy link

@coderaw8 coderaw8 commented Jan 16, 2015

Thank you for that!!

@jeremy-wagner

This comment has been minimized.

Copy link

@jeremy-wagner jeremy-wagner commented Feb 11, 2015

I have followed this exactly and I'm getting an error on the line:

PDFJS.getDocument(url).then(renderPages);

When this line runs I get a 404 Not Found error on "worker.js". I've made sure

PDFJS.diableWorker = true;

is included. Any thoughts?

@mikechabot

This comment has been minimized.

Copy link

@mikechabot mikechabot commented Feb 20, 2015

This is awesome!

@Huespal

This comment has been minimized.

Copy link

@Huespal Huespal commented Apr 9, 2015

Hey jeremy-wagner,

I think you missed an 's'.

PDFJS.disableWorker = true;

@chituno1

This comment has been minimized.

Copy link

@chituno1 chituno1 commented Jun 14, 2015

I need to convert file given by user without uploading to server

then what will be content of my url?

if I specify local machine path of user then it gives error

please help me

@Targun

This comment has been minimized.

Copy link

@Targun Targun commented Jul 6, 2015

Unreal!

Thank you Dude.

@marchrius

This comment has been minimized.

Copy link

@marchrius marchrius commented Oct 27, 2015

How I can "clean up" the pdfDoc ? I can clean the canvas by clearRect()

@Ethaan

This comment has been minimized.

Copy link

@Ethaan Ethaan commented Jan 4, 2016

It is possible to load a pdf inside a div instead of a canvas?

@marcommas

This comment has been minimized.

Copy link

@marcommas marcommas commented Mar 16, 2016

thank's!!
How can I print my pdf in a printer using pdf.js?

@tanmayrajani

This comment has been minimized.

Copy link

@tanmayrajani tanmayrajani commented Sep 26, 2016

In order to keep text-selection from PDF, this won't be useful right? (since this is using canvas..) Any other workaround for that?

@nikhilreddy93

This comment has been minimized.

Copy link

@nikhilreddy93 nikhilreddy93 commented Oct 17, 2016

How can i get the page number of the page which is clicked? here is my code
$("div").click(function() { PDFJS.getDocument(url) .then(function(pdf) { pdf.getPage(2).then(function(page) { console.log('pagenum1 = '+page.pageIndex); }); });

@santasachin

This comment has been minimized.

Copy link

@santasachin santasachin commented Oct 25, 2016

How to get HTML5 code from the pdf file?

@gregdorian

This comment has been minimized.

Copy link

@gregdorian gregdorian commented Jan 19, 2017

Hmm ....and how Make this with jQuery and Modal Boostrap?

@SupFrig

This comment has been minimized.

Copy link

@SupFrig SupFrig commented Aug 3, 2017

Using this snippet the pages of my PDF are not rendering in chronogical order, the first page that is ready is rendering first so the pdf order is kinda random. Any trick to avoid this behaviour ?

@SupFrig

This comment has been minimized.

Copy link

@SupFrig SupFrig commented Aug 3, 2017

my terrible fix for my issue with pdf pages rendering in wrong order. The use of interval make it longer to render, if someone has a better fix i'll take it

function renderPages(pdfDoc) {

            var maxIterations = pdfDoc.numPages + 1;
            var intervalIterator = 1;

            var i = window.setInterval(function(){
                pdfDoc.getPage(intervalIterator).then(renderPage);
                intervalIterator += 1;

                if(maxIterations == intervalIterator){
                    window.clearInterval(i);
                }
            },50);
            
        }
@ChristianFlack

This comment has been minimized.

Copy link

@ChristianFlack ChristianFlack commented Oct 15, 2017

my terrible fix for my issue with pdf pages rendering in wrong order. The use of interval make it longer to render, if someone has a better fix i'll take it

@SupFrig
The issue is that all pages are rendered simultaneously. To render them in order, you could use ES6 Promises or a promise library like kriskowal's Q.

An example implementation would be:

// [...] renderPage implementation stays the same

var renderPageFactory = function (pdfDoc, num) {
    return function () {
        return pdfDoc.getPage(num).then(renderPage);
    };
};

var renderPages = function (pdfDoc) {
    var renderedPage = $q.resolve();
    for (var num = 1; num <= pdfDoc.numPages; num++) {
    	// Wait for the last page t render, then render the next
        renderedPage = renderedPage.then(renderPageFactory(pdfDoc, num));
    }
};
@dardinier

This comment has been minimized.

Copy link

@dardinier dardinier commented Nov 9, 2017

my terrible fix for my issue with pdf pages rendering in wrong order. The use of interval make it longer to render, if someone has a better fix i'll take it

@SupFrig & @ChristianFlack

I found another solution.

First, I create my canvas and then I render the page passing the canvas as argument. That way, you get all canvas ordered and you load the page in the right canvas !

Here's the code :

function renderPDF (url) {
  PDFJS.getDocument(url).then((pdf) => {
    for (let i = 1; i <= pdf.numPages; i += 1) {
      const canvas = document.createElement('canvas');
      /* This indentify the canvas as the location of the page */
      canvas.id = i;
      document.getElementById('pdf-viewer').appendChild(canvas);
      pdf.getPage(i).then((page) => {
        renderPage(page, canvas);
      }
    }
  });
}

renderPage(page, canvas) {
  const viewport = page.getViewport(1);
  const canvasContext = canvas.getContext('2d');
  const renderContext = {
    canvasContext,
    viewport
  };
  canvas.height = viewport.height;
  canvas.width = viewport.width;
  page.render(renderContext);
}
@DevKamran

This comment has been minimized.

Copy link

@DevKamran DevKamran commented Jan 31, 2018

asdasdasd

@mandy6720

This comment has been minimized.

Copy link

@mandy6720 mandy6720 commented Feb 8, 2018

Couldn't you also use Promise.all()?

renderPages() {
  const pagePromises = [];
  PDFJS.getDocument(url).then((pdf) => {
    for (let i = 1; i <= pdf.numPages; i += 1) {
      // Push the promises into promise array
      pagePromises.push(pdf.getPage(i));
    }
    // When loop finishes, call Promise.all() to 
    // wait until all promises resolve and returns 
    // results array
    Promise.all(pagePromises).then((resultsArr) => {
      // render pdf pages
    })
  });
}

Since the promises are pushed into the promise array in the correct order, they would render in the correct order :)

@Sreekanthp74

This comment has been minimized.

Copy link

@Sreekanthp74 Sreekanthp74 commented Jun 12, 2018

How can I get an editable PDF in the canvas using pdfjs?

@WilsonYesidRiveraCasas

This comment has been minimized.

Copy link

@WilsonYesidRiveraCasas WilsonYesidRiveraCasas commented Aug 2, 2018

Hi, I have a problem.
index.html:34 Uncaught ReferenceError: PDFJS is not defined at renderPDF (index.html:34) at index.html:43 renderPDF @ index.html:34 (anonymous) @ index.html:43

Line 34:

PDFJS.disableWorker = true;

Here's the code :

<html>
<body>

<!-- really dirty! this is just a test drive ;) -->

<script type="text/javascript" src="pdf.js"></script>
<script type="text/javascript">
function renderPDF(url, canvasContainer, options) {

    var options = options || { scale: 1 };
        
    function renderPage(page) {
        var viewport = page.getViewport(options.scale);
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        var renderContext = {
          canvasContext: ctx,
          viewport: viewport
        };
        
        canvas.height = viewport.height;
        canvas.width = viewport.width;

        canvasContainer.appendChild(canvas);
        
        page.render(renderContext);
    }
    
    function renderPages(pdfDoc) {
        for(var num = 1; num <= pdfDoc.numPages; num++)
            pdfDoc.getPage(num).then(renderPage);
    }

    PDFJS.disableWorker = true;
    PDFJS.getDocument(url).then(renderPages);

}   
</script> 

<div id="holder"></div>

<script type="text/javascript">
renderPDF('file.pdf', document.getElementById('holder'));
</script>  

</body>
</html>
@The-Don-Himself

This comment has been minimized.

Copy link

@The-Don-Himself The-Don-Himself commented Aug 5, 2018

@WilsonYesidRiveraCasas don't use the unreleased/unstable version 2, please stick to version 1.x

@DevTheUIDeveloper

This comment has been minimized.

Copy link

@DevTheUIDeveloper DevTheUIDeveloper commented Sep 11, 2018

how to add zoom functionality in above mention code so that after zoom it stay on the same page?

@kishandonepudi

This comment has been minimized.

Copy link

@kishandonepudi kishandonepudi commented Sep 11, 2018

@amazingalain

This comment has been minimized.

Copy link

@amazingalain amazingalain commented Dec 16, 2018

is it possible to JUST render specific range or page o a pdf ? like... page 3 to page 6 ?

@parmodkumarr

This comment has been minimized.

Copy link

@parmodkumarr parmodkumarr commented Feb 20, 2019

`

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="pdf.js"></script> <script src="jquery.js"></script>

PDF.js 'Hello, world!' example

<script> // If absolute URL from the remote server is provided, configure the CORS // header on that server. var url = 'pdff.pdf';
        // 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 = 'worker.js';
        var loadingTask = pdfjsLib.getDocument(url);
            loadingTask.promise.then(function(pdf) {
        			 var __TOTAL_PAGES = pdf.numPages; 
        			  // Fetch the first page
        			  var pageNumber = 1;			  
        			for( let i=1; i<=__TOTAL_PAGES; i+=1){
        	var id ='the-canvas'+i;
        	$('#canvas_div').append("<div style='background-color:gray;text-align: center;padding:20px;' ><canvas calss='the-canvas' id='"+id+"'></canvas></div>");				
        				  var canvas = document.getElementById(id);
        				  //var pageNumber = 1;
        				  renderPage(canvas, pdf, pageNumber++, function pageRenderingComplete() {
        					if (pageNumber > pdf.numPages) {
        					  return; 
        					}
        					// Continue rendering of the next page
        					renderPage(canvas, pdf, pageNumber++, pageRenderingComplete);
        				  });				
        			}
        	  
            });
        
            function renderPage(canvas, pdf, pageNumber, callback) {
              pdf.getPage(pageNumber).then(function(page) {
                var scale = 1.5;
                var viewport = page.getViewport({scale: scale});
        
                var pageDisplayWidth = viewport.width;
                var pageDisplayHeight = viewport.height;
        		//var pageDivHolder = document.createElement();
                // Prepare canvas using PDF page dimensions
                //var canvas = document.createElement(id);
                var context = canvas.getContext('2d');
                canvas.width = pageDisplayWidth;
                canvas.height = pageDisplayHeight;
               // pageDivHolder.appendChild(canvas);
        
                // Render PDF page into canvas context
                var renderContext = {
                  canvasContext: context,
                  viewport: viewport
                };
                page.render(renderContext).promise.then(callback);
              });
            }           
     </script>
     <html>

`

@JMIdeaMaker

This comment has been minimized.

Copy link

@JMIdeaMaker JMIdeaMaker commented Sep 11, 2020

doesn't work with the newest version, 2.6.347

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.