I'm trying to render a page from a pdf with pdf.js
Normally, using a url, I can do this:
PDFJS.getDocument("http://www.server.com/file.pdf").then(function getPdfHelloWorld(pdf) {
//
// Fetch the first page
//
pdf.getPage(1).then(function getPageHelloWorld(page) {
var scale = 1.5;
var viewport = page.getViewport(scale);
//
// Prepare canvas using PDF page dimensions
//
var canvas = document.getElementById('the-canvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
//
// Render PDF page into canvas context
//
page.render({canvasContext: context, viewport: viewport});
});
});
But in this case, I have the file in base64 rather than an url:
data:application/pdf;base64,JVBERi0xLjUKJdDUxdgKNSAwIG9iaiA8PAovTGVuZ3RoIDE2NjUgICAgICAKL0ZpbHRlciAvRmxhdGVEZWNvZGUKPj4Kc3RyZWFtCnjarVhLc9s2...
How this can be done?
This question is related to
javascript
pdf
canvas
base64
pdf.js
Used the Accepted Answer to do a check for IE and convert the dataURI to UInt8Array; an accepted form by PDFJS
Ext.isIE ? pdfAsDataUri = me.convertDataURIToBinary(pdfAsDataUri): '';_x000D_
_x000D_
convertDataURIToBinary: function(dataURI) {_x000D_
var BASE64_MARKER = ';base64,',_x000D_
base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length,_x000D_
base64 = dataURI.substring(base64Index),_x000D_
raw = window.atob(base64),_x000D_
rawLength = raw.length,_x000D_
array = new Uint8Array(new ArrayBuffer(rawLength));_x000D_
_x000D_
for (var i = 0; i < rawLength; i++) {_x000D_
array[i] = raw.charCodeAt(i);_x000D_
}_x000D_
return array;_x000D_
},
_x000D_
According to the examples base64 encoding is directly supported, although I've not tested it myself. Take your base64 string (derived from a file or loaded with any other method, POST/GET, websockets etc), turn it to a binary with atob, and then parse this to getDocument on the PDFJS API likePDFJS.getDocument({data: base64PdfData});
Codetoffel answer does work just fine for me though.
Source: Stackoverflow.com