Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print canvas element by using javascript print method?

How can I print a created canvas element that has some content drawn on it using javascript? My print preview shows a blank box instead of the contents in the canvas element?

First i create my canvas image by using html2canvas, then i see that image is created. But i couldn't print the div which includes related image.

In IE i can see it when triggered button twice. In first click it opens blank print preview, in second click it opens it with related content. However in chrome it opens blank content at once, it cannot load second trigger; page freezes.

Here is my code;

function printDiv(index) {
var canvasImg = "";
var divToPrint = document.getElementById('hr'+index);
html2canvas(divToPrint, {
onrendered: function(canvas) {
var canvasImg = canvas.toDataURL("image/jpg");
$('#seckinCanvas').html('<img src="'+canvasImg+'" alt="">');
}
});

var printContent = document.getElementById("seckinCanvas");
var windowUrl = '';
var uniqueName = new Date();
var windowName = 'Print' + uniqueName.getTime();
var printWindow = window.open(windowUrl, windowName,'left=500,top=500,width=0,height=0');
printWindow.document.write(printContent.innerHTML);
printWindow.document.close();
printWindow.focus();
printWindow.print();
printWindow.close();
}
like image 493
Cracker Avatar asked Mar 21 '26 18:03

Cracker


1 Answers

Here's what worked for me (no JS needed):

  1. Include a print button in the HTML:

    <a id="btn-print" onclick="print()">Print</a>
  2. Add this to your CSS:

    @media print {
      // Make all your non-canvas things (divs and stuff) disappear:
      .notCanvas, .alsoNotCanvas, ... {
        display: none;
      }
      // Center your canvas (optional):
      canvas {
        padding: 0;
        margin: auto;
        display: block;
        position: absolute;
        width: 800px;
        height: 800px;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
      }
    }

This lets you print just the canvas.
I didn't cross-browser test this, but it definitely works in Chrome.

like image 175
strayblues Avatar answered Mar 23 '26 06:03

strayblues



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!