Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a image in multiple pages of pdf using jspdf

I have a table(columns aligned differently) which is to be saved as pdf.I converted the table to image using html2canvas and then saved the image into pdf usng jspdf. It works well if the size of the image is less than or equal to page size of pdf but if the image size is bigger than the page size then it saves only first page of pdf(which has only a part of the image) and rest of the image is not displayed/saved in pdf. here the javascript code I used.

       $("#btnVC_saveGLSummary").click(function () {
        html2canvas($("#tblSaveAsPdf1"), {
        onrendered: function (canvas) {
        var myImage = canvas.toDataURL("image/jpeg");            
        var d = new Date().toISOString().slice(0, 19).replace(/-/g, "");
        filename = 'report_' + d + '.pdf';
        var doc = new jsPDF();
        doc.addImage(myImage, 'JPEG', 12, 10);
        doc.save(filename);
          }
         });
       });

Any ideas how to get the remaining part of the image on the second page of pdf.

like image 452
user3687972 Avatar asked Jun 05 '14 19:06

user3687972


1 Answers

It works for html2canvas and jspdf.

var imgData = canvas.toDataURL('image/png');
var imgWidth = 210; 
var pageHeight = 295;  
var imgHeight = canvas.height * imgWidth / canvas.width;
var heightLeft = imgHeight;
var doc = new jsPDF('p', 'mm');
var position = 10; // give some top padding to first page

doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;

while (heightLeft >= 0) {
  position += heightLeft - imgHeight; // top padding for other pages
  doc.addPage();
  doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
  heightLeft -= pageHeight;
}
doc.save( 'file.pdf');
like image 64
Shuvro Akash Avatar answered Sep 19 '22 21:09

Shuvro Akash