user3055938 user3055938 - 1 month ago 17
HTML Question

Getting a base64 png from a PDF.JS pdf converted to a canvas tag?

I'm trying to get a base64 encoded png value from a canvas that was created by converting a pdf with the PDF.JS library by Mozilla.

So I had a base64 encoded PDF that I converted into a HTML canvas. I now need to convert that HTML canvas into a base64 encoded png value that I can use with a HTML img tag that displays properly.

I tried the HTMLCanvasElement.toDataURL(), however it doesn't display anything. I tried using the same method with some green boxes drawn in canvas and it worked fine, meaning that the base64 encoded pdf converted to canvas just doesn't want to work with that method.

Any other solutions or a workaround for the solution I tried?

**I need to do this inside my JS code with my HTML.

function convertDataURIToBinary() {
var raw = window.atob(BASE64 OF PDF);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));

for(var i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
return array;
var pdfAsArray = convertDataURIToBinary();

PDFJS.workerSrc = "";
var canvas = _el.querySelector(".insertHere");
PDFJS.getDocument(pdfAsArray).then(function getPdfHelloWorld(pdf) {
pdf.getPage(1).then(function getPageHelloWorld(page) {
var scale = 1.5;
var viewport = page.getViewport(scale);

var context = canvas.getContext("2d");
canvas.height = viewport.height;
canvas.width = viewport.width;

var renderContext = {
canvasContext: context,
viewport: viewport
canvas = _el.querySelector(".insertHere");
var imgSrc = canvas.toDataURL("image/png");
var img = new Image();
img.src = imgSrc;



You are not waiting on the promise returned by render() to finish async operation. See how to wait on completion:

  var renderTask = page.render(renderContext);
  // Wait for rendering to finish
  renderTask.promise.then(function () {
    // Page rendered, now take snapshot.