Print chart using chart js
Asked Answered
I

5

5

I am using Chart JS library to create charts https://www.chartjs.org/

Say I have the below code

 <div class="card-body ">
        <canvas id="bidStatus"></canvas>
  </div>

Using the FileSaver.js I am able to save the chart using the below code

function DownloadImage() {
    $("#bidStatus").get(0).toBlob(function (blob) {
        saveAs(blob, "BidStatus.png");
    });
}

But I am not sure how I can print the chart. Don't see any native API call to do that. Can some one please tell me how I can achieve this.

I tried using jquery print libraries which are mentioned in the Print an HTMl element example but they don't seem to load the chart generated using Chart js. I get a blank page for printing.

Thanks

Indissoluble answered 13/9, 2018 at 18:52 Comment(2)
Possible duplicate of How to print only a selected HTML element?Malcolm
I tried using jquery print libraries which are mentioned in the Print an HTMl element example but they don't seem to load the chart generated using Chart js. I get a blank page for printing.Indissoluble
I
3

This function prints the contents of a Canvas correctly

function PrintImage() {
    var canvas = document.getElementById("bidStatus");
    var win = window.open();
    win.document.write("<br><img src='" + canvas.toDataURL() + "'/>");
    win.print();
    win.location.reload();

}
Indissoluble answered 13/9, 2018 at 19:19 Comment(2)
Not working in Chrome, just opens a new tab blank page!Bodgie
Nice workaround. On my side i had to wrap the 'win.print()' in a 'setTimeout' for it to first render on the page. I also omitted the last line: 'win.location.reload()'. And also note the 'getElementById()' must reference your canvas element's ID attribute.Adelric
H
3

I was able to use jsPDF to print a canvas from chart.js with Chrome using the code below. There is already an accepted answer to this question, but as someone else pointed out in the comments, I could not get that solution to work with Chrome.

Here is a link to jsPDF documentation. I am still exploring this so you may find more useful tools to accomplish the same task. I had to use a PNG instead of a JPEG because of the transparent background of the chart. The JPEG would only appear black. If you want a colored background, add a colored rectangle(rect method in docs) that is the same size and position of the chart image before adding the image. Other text and features can also be added to the pdf you are building.

I do not like that the chart image has to be added at a specific location and size and will update this post if I find a better way of doing this.

EDIT: With jsPDF you can use pdf.save('Filename.pdf') to replace FileSaver.js, provided you want a pdf.

HTML

<button id="print-chart-btn">Print Chart</button>
<div class="canvas-container">
    <canvas id="random-chart" ></canvas>
</div>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jspdf.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/Chart.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>

JAVASCRIPT

$('#print-chart-btn').on('click', function() {
    var canvas = document.querySelector("#random-chart");
    var canvas_img = canvas.toDataURL("image/png",1.0); //JPEG will not match background color
    var pdf = new jsPDF('landscape','in', 'letter'); //orientation, units, page size
    pdf.addImage(canvas_img, 'png', .5, 1.75, 10, 5); //image, type, padding left, padding top, width, height
    pdf.autoPrint(); //print window automatically opened with pdf
    var blob = pdf.output("bloburl");
    window.open(blob);
});
Hiett answered 23/4, 2019 at 22:26 Comment(0)
P
1

I have had a similar problem. and my chart is very complex with custom drawings on it. to print the chart on paper you need to call chart.resize(parentContainer.clientWidth,parentContainer.clientWidth). this way chart width and height will automatically update to paper size.

The major problem is when do you call the above line? onBeforePrint will not work. we need to use const mediaQuery =window.matchMedia('print') then attach change Event Listener to it by mediaQuery.addEventListener("change",()=> chart.resize(parentContainer.clientWidth,parentContainer.clientWidth))

each and every time the user select a different paper size or change orientation this event will be triggered and new clientwidth and clientHeight will be updated to chart and it will render in it new dimensions

Pren answered 5/8, 2022 at 5:16 Comment(0)
M
1
onAnimationComplete: function(){
                const canvas = document.getElementById("bidStatus");
                const dataURL = canvas.toDataURL();
                document.getElementById("print-chart").addEventListener("click",function(){
                    var win = window.open();
                    win.document.write("<br><img src='" + dataURL + "'/>");
                    setTimeout(() => {
                        win.print();
                    }, 1000);
                });
            }

Do not forget to put the print inside timeout funtion and onAnimationComplete or onComplete, so as to avoid blank print output.

Marquez answered 2/2 at 14:29 Comment(0)
L
0

This code takes the answer given by SP1 and incorporates the comments provided by Sebastian. Also I have multiple chart.js graphs, so showing how to print that (for anyone that might need to do so):

PrintImage = function () {
    var canvas1 = document.getElementById('lineChart1'); //Use canvas ID, *not* div ID
    var canvas2 = document.getElementById('lineChart2');
    var win = window.open();
    win.document.write("<br>Graph #1");
    win.document.write("<br><img src='" + canvas1.toDataURL() + "'/>");
    win.document.write("<br>Graph #1");
    win.document.write("<br><img src='" + canvas2.toDataURL() + "'/>");
    setTimeout(() => { 
        win.print();
    }, 1000);
};
Lancelancelet answered 24/9, 2023 at 3:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.