How to display whole PDF (not only one page) with PDF.JS?

前端 未结 6 1704
无人及你
无人及你 2020-12-24 05:42

I\'ve created this demo:

http://polishwords.com.pl/dev/pdfjs/test.html

It displays one page. I would like to display all pages. One below another, or place s

6条回答
  •  温柔的废话
    2020-12-24 06:10

    PDFJS has a member variable numPages, so you'd just iterate through them. BUT it's important to remember that getting a page in pdf.js is asynchronous, so the order wouldn't be guaranteed. So you'd need to chain them. You could do something along these lines:

    var currPage = 1; //Pages are 1-based not 0-based
    var numPages = 0;
    var thePDF = null;
    
    //This is where you start
    PDFJS.getDocument(url).then(function(pdf) {
    
            //Set PDFJS global object (so we can easily access in our page functions
            thePDF = pdf;
    
            //How many pages it has
            numPages = pdf.numPages;
    
            //Start with first page
            pdf.getPage( 1 ).then( handlePages );
    });
    
    
    
    function handlePages(page)
    {
        //This gives us the page's dimensions at full scale
        var viewport = page.getViewport( 1 );
    
        //We'll create a canvas for each page to draw it on
        var canvas = document.createElement( "canvas" );
        canvas.style.display = "block";
        var context = canvas.getContext('2d');
        canvas.height = viewport.height;
        canvas.width = viewport.width;
    
        //Draw it on the canvas
        page.render({canvasContext: context, viewport: viewport});
    
        //Add it to the web page
        document.body.appendChild( canvas );
    
        //Move to next page
        currPage++;
        if ( thePDF !== null && currPage <= numPages )
        {
            thePDF.getPage( currPage ).then( handlePages );
        }
    }
    

提交回复
热议问题