Search code examples
javascripttodataurl

Printing a toDataURL image using javaScript


Well the above is a mouthful. So I'm grabbing a canvas and converting it into a data URI using toDataURL(). The goal is to then create a print dialog to print that image. I'm running into an issue pushing the created image to a new window and calling print on it. See below:

var image = new Image();
var canvas = event.context.canvas;
var data = canvas.toDataURL();
image.src = data;
var printWindow = window.open('', 'to_print', 'height=600,width=800');
var html = '<html><head><title></title></head><body style="width: 100%; padding: 0; margin: 0;" onload="window.focus(); window.print(); window.close()">' + image + '</body></html>';
printWindow.document.write(html);
printWindow.document.close();

As a workaround to printing something, especially lodash templates, this works. It's not pretty but it works.

Anyway, when I run this I get back:

[object HTMLImageElement]

I don't know why it's giving me that instead of displaying the image. Does anyone have experience trying to print an image built off of a toDataURL() method?


Solution

  • You can't concatenate an image object into a string of HTML, or rather you can, but that gives you the string representation of that object, which is [object HTMLImageElement].

    You'd have to create an <img> tag in the HTML instead

    var x=window.open(); x.document.open(); x.document.write('content'); x.document.close();

    var canvas = event.context.canvas;
    var data = canvas.toDataURL();
    
    var html  = '<html><head><title></title></head>';
        html += '<body style="width: 100%; padding: 0; margin: 0;"';
        html += ' onload="window.focus(); window.print(); window.close()">';
        html += '<img src="' + data + '" /></body></html>';
    
    var printWindow = window.open('', 'to_print', 'height=600,width=800');
    
    printWindow.document.open();
    printWindow.document.write(html);
    printWindow.document.close();
    printWindow.close();