Empty PDF report is generated when we have multiple graphs using html2canvas and jsPDF library

后端 未结 1 694
一整个雨季
一整个雨季 2020-12-21 06:18

I have two flot charts in One page , and with the code below, I want to use jsPDF to create report of them in two different pages (but one PD file) here id my code: Lets use

相关标签:
1条回答
  • 2020-12-21 06:52

    Then problem was because of async execution of converting image and creating pdf.

    One solution is using Asynchronous functions.because the "doc.save()" was executing before Html2Canvas finished creating canvas from graph, so it was empty.

    I created a fiddle here. this is the code for Asynchronous execution using Promise API in JavaScript.(promise.all)

     var p1 = new Promise(function (resolve, reject) {
         var element = $("#placeholder").get(0);
           html2canvas(element,
                            {
                                onrendered: function (canvas) {
                                    resolve(canvas.toDataURL('image/png'));
                                }
                            });
            });
    
    
     var p2 = new Promise(function (resolve, reject) {
         var element = $("#placeholder_2").get(0);
           html2canvas(element,
                        {
                            onrendered: function (canvas) {
                                resolve(canvas.toDataURL('image/png'));
                            }
                        });
            });
    
      Promise.all([p1, p2]).then(function (screens) {
                var doc = new jsPDF();
                doc.addImage(screens[0], 'PNG', 10, 10, 180, 115);
                doc.addPage();
                doc.addImage(screens[1], 'PNG', 10, 10, 180, 60);
                doc.save('sample-file.pdf');
    
        });
    
    0 讨论(0)
提交回复
热议问题