Search code examples
jquerychartsflotjspdfhtml2canvas

Export graph to pdf use jquery flot


I had a problem about export more graphs which used jquery flot to pdf

I used html2canvas.js and jspdf-min.js to export graphs to pdf, but i had two problems:

First, it exported to pdf too ugly.

Second, i want to export two graphs inside one page, but it exported to two pages.

Here my code:

var _canvas = null;
$(function() {
  $("#id_generate_pdf").on("click", function (e) {
    window.allcanvas = [];
    var allcontainers = $('[id^="flot-placeholder"]');

    allcontainers.each(function (index, elem) {
      html2canvas($(elem).get(0), {
        onrendered: function (canvas) {
          window.allcanvas.push(canvas);
          if(allcontainers.length == allcanvas.length){
            finalpdf();
          }
        }
      });
    });
  });

  finalpdf = function(){
    var doc = new jsPDF('landscape');
    for(var i = 0; i< allcanvas.length; i++){
      var imgData = allcanvas[i].toDataURL('image/jpeg');
      doc.addImage(imgData, 'JPEG', 10, 10, 280, 65);
      if(i != allcanvas.length-1) {
        doc.addPage();
      }
    }
    doc.save('testingPDF.pdf');
  };
});

Here is my demo: My demo code

Hope every body can support me. Thank you very much.

Update:

I want to export pdf and this pdf include this text same as image which i attached.

I don't know how to do that. Please give me some ideas or some advises. Thank you very much.

My demo code update

enter image description here


Solution

    • Remove the call to doc.addPage();
    • Change the width and height in the parameters of doc.addImage() to something with the same ratio as your chart.
    • Change the y-position for the second chart so it doesn't overlap the first.
    • Set white background to the charts and the canvas.

    See this updated fiddle: http://jsfiddle.net/g2CTz/515/