最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Print chart using chart js - Stack Overflow

programmeradmin5浏览0评论

I am using Chart JS library to create charts /

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

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

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

Share Improve this question edited Sep 13, 2018 at 19:06 SP1 asked Sep 13, 2018 at 18:52 SP1SP1 1,2023 gold badges25 silver badges52 bronze badges 2
  • 1 Possible duplicate of How to print only a selected HTML element? – Blue Commented Sep 13, 2018 at 18:55
  • 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. – SP1 Commented Sep 13, 2018 at 19:08
Add a ment  | 

5 Answers 5

Reset to default 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();

}

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 ments, 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 acplish 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/npm/[email protected]/dist/jspdf.min.js"></script>
<script src="https://cdn.jsdelivr/npm/[email protected]/dist/Chart.min.js"></script>
<script src="https://code.jquery./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);
});

I have had a similar problem. and my chart is very plex 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

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.

This code takes the answer given by SP1 and incorporates the ments 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);
};
发布评论

评论列表(0)

  1. 暂无评论