Skip to content
Advertisement

Render PDF using PDF.JS and AngularJS from byte array

I’ve been following the following links to try to render a byte stream returned from an API to a PDF in browser using PDF.JS:

Here is the JavaScript used to run render. Note: stream is a byte array returned from an API.

var file = new Blob([stream], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$scope.renderPDF(fileURL, document.getElementById('pdf-holder'));

Here is $scope.renderPDF:

$scope.renderPDF = function(url, canvasContainer) {
    var scale= 1.5;  //"zoom" factor for the PDF

    function renderPage(page) {
        var viewport = page.getViewport(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);

}

Here is the HTML in my template page:

<script type="text/javascript" src="https://cdn.rawgit.com/mozilla/pdf.js/gh-pages/build/pdf.js"></script>

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

When the code runs

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

I get a 404 Not Found error on worker.js, which makes sense because I’m following these examples and disabling worker so I shouldn’t need it. Does anyone have any advice or an easy way around this that I can render a pdf in browser from a byte stream?

Advertisement

Answer

You still need pdf.worker.js even if you have disabled it. Disabling it means that PDFJS will use faked workers for which it is also using the worker library. Just set it in the following way:

PDFJS.workerSrc = 'pdf.worker.js';
Advertisement