How to split page after adding the image using HTML2Canvas and jspdf

Discussão em 'Angular' iniciado por Manmeet Khurana, Dezembro 28, 2024.

  1. Using html2canvas and JsPDF for converting HTML to pdf and using the below code for generating the code this code will give convert the complete HTML of the div to a single image and will show in the pdf as a single page.

    import * as jsPDF from 'jspdf';
    import html2canvas from 'html2canvas';

    htmltoPDF()
    {
    // parentdiv is the html element which has to be converted to PDF
    html2canvas(document.querySelector("#parentdiv")).then(canvas => {

    var pdf = new jsPDF('p', 'pt', [canvas.width, canvas.height]);

    var imgData = canvas.toDataURL("image/jpeg", 1.0);
    pdf.addImage(imgData,0,0,canvas.width, canvas.height);
    pdf.save('converteddoc.pdf');

    });

    }


    For split the code i used below code which split the pages into the multiple pages but not spliting the space correctly because my pdf has small images attached pdf.

    var imgWidth = 210;
    var pageHeight = 295;
    var imgHeight = canvas.height * imgWidth / canvas.width;
    var heightLeft = imgHeight;

    enter code here

    var doc = new jsPDF('p', 'mm');
    var position = 0;

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

    while (heightLeft >= 0) {
    position = heightLeft - imgHeight;
    doc.addPage();
    doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
    heightLeft -= pageHeight;
    }
    doc.save( 'file.pdf');


    Is there any approach to split the page according to the static height which split the image from a particular position?

    Continue reading...

Compartilhe esta Página