How to convert HTML to pdf?

  By Ahsan   Posted on September-07-2023   97

Javascript

@*Your button*@


<button id="btnExport" class="btn_Export">Save as PDF</button>

 


@*section which is going to capture *@


<div class="recent-orders" id="sectionToCapture">
<p>Add your Html here which is going to convert into pdf</p>
</div>

 

 

@*JS File and Code (file download the from that link--->  https://www.transfernow.net/dl/20230907ZuNDinKN  *@

<script src="/Content/Jspdf/jspdf.min.js"></script>
<script src="/Content/Jspdf/html2canvas.js"></script>

<script>
    $("body").on("click", "#btnExport", function () {
        var HTML_Width = $("#sectionToCapture").width();
        var HTML_Height = $("#sectionToCapture").height();
        var top_left_margin = 15;
        var PDF_Width = HTML_Width + (top_left_margin * 2);
        var PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
        var canvas_image_width = HTML_Width;
        var canvas_image_height = HTML_Height;

        var totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;


        html2canvas($("#sectionToCapture")[0], { allowTaint: true }).then(function (canvas) {
            canvas.getContext('2d');

            console.log(canvas.height + "  " + canvas.width);


            var imgData = canvas.toDataURL("image/jpeg", 1.0);
            var pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]);
            pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, canvas_image_width, canvas_image_height);


            for (var i = 1; i <= totalPDFPages; i++) {
                pdf.addPage(PDF_Width, PDF_Height);
                pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height * i) + (top_left_margin * 4), canvas_image_width, canvas_image_height);
            }

            pdf.save("YourFileName.pdf");
        });
    });
</script>

 

Microsoft Net Framework
By      07-Sep-2023 Views  97



You may also read following recent Post