Export div content to PDF using javascript

jquery code to generate pdf from div with automatic height and width –

Its can be easily done with html2canvas and jspdf. So, to generate pdf, first of all we have to include html2canvas and jspdf library.

For example –

Let’s say we have a div with id content and on a button(say Generate pdf) click, we want to export its content as a pdf.

First, write the code for creating button and include the required libraries(html2canvas and jspdf) –

<button id=”generatePDFbtn”>Generate PDF</div>
<div id=”content”>hello</div>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js”></script>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.5.0-beta4/html2canvas.min.js”></script>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/jspdf/0.9.0rc1/jspdf.min.js”></script>
Then, create an event handler function to handle button click(Generate pdf button in our example) and write the code to generate the pdf –
<script>
$(document).on(“click”, “#generatePDFbtn”, function() {
        html2canvas(document.getElementById(“content”)).then(function(canvas) {
            var imgData = canvas.toDataURL(“image/jpeg”, 1.0);
            var pdf = new jsPDF(‘p’, ‘mm’, [400, 480]);
            pdf.addImage(imgData, ‘JPEG’, 0, 0, 400, 480);
            pdf.save(“search-result.pdf”);
        });
    });
</script>

For more related queries, please VISIT.

In case, if you did not find your solution or have any query/question, please contact us.

Leave a Reply

Your email address will not be published. Required fields are marked *