Question

can i pass data like this to PDFJS.getDocument instead of URL. my data:

PDF-1.4 %���� 9 0 obj <> endobj xref 9 36 0000000016 00000 n 0000001259 00000 n 0000001336 00000 n...

Was it helpful?

Solution

The PDFJS.getDocument method is defined pretty clearly, and you can read it for yourself: http://mozilla.github.io/pdf.js/api/draft/PDFJS.html#getDocument

You can open a PDF using a URL:

PDFJS.getDocument('/url/to/file.pdf').then(function(pdf){ 

    var pageNumber = 1;

    pdf.getPage(pageNumber).then(function (page) {
        var scale = 1;
        var viewport = page.getViewport(scale);
        var canvas = document.getElementById('the-canvas');
        var context = canvas.getContext('2d');
        canvas.height = viewport.height;
        canvas.width = viewport.width;
        page.render({canvasContext: context, viewport: viewport});
    });
});

In this case, PDFJS makes a call to the URL for you, but if you already have the PDF file, you can just give the data to PDFJS, like this:

var docInitParams = { data: myPdfContent };
PDFJS.getDocument(docInitParams).then(function(pdf){
    //render a page here
});

The question is what format is your raw PDF data in?

If you just retrieved the file from your webserver using an Ajax call, then perhaps the data is in an ArrayBuffer. If so, you'll need to make it accessible to PDFJS by putting it in a Uint8Array, as follows:

//However you get the data, let's say it ends up here in this variable
var arrayBufferOfPdfData = blah..blah..blah;

var myData = new Uint8Array(arrayBufferOfPdfData); //put it in a Uint8Array

var docInitParams = {data: myData};
PDFJS.getDocument(docInitParams).then(function(pdf){
    //render a page here
});

In the end, you need to know what format your data is in so that you can get it into an acceptable format for PDFJS to make use of. I didn't describe what to do if your data is encoded as a Base64 string, but there is another SO question that answers exactly that.

My answer is much more descriptive than your one-liner question. So, if I haven't addressed your question well enough, then you should provide more detail.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top