I have a content div with the id as "content". In the content div I have some graphs and some tables. I want to download that div as a pdf when user click on download button. Is there a way to do that using javascript or jQuery?
To download a div in a HTML page as PDF using JavaScript, we can use the jsPDF library. import { jsPDF } from "jspdf"; const doc = new jsPDF(); doc. text("Hello world!", 10, 10); doc. save("a4.
Generate PDF using JavaScript The following example shows how to use the jsPDF library to generate PDF file using JavaScript. Specify the content in text() method of jsPDF object. Use the addPage() method to add new page to PDF. Use the save() method to generate and download PDF file.
To save HTML page as PDF using JavaScript, we can use the html2pdf library. const element = document. getElementById("element-to-print"); const opt = { margin: 1, filename: "myfile.
You can do it using jsPDF
HTML:
<div id="content"> <h3>Hello, this is a H3 tag</h3> <p>A paragraph</p> </div> <div id="editor"></div> <button id="cmd">generate PDF</button>
JavaScript:
var doc = new jsPDF(); var specialElementHandlers = { '#editor': function (element, renderer) { return true; } }; $('#cmd').click(function () { doc.fromHTML($('#content').html(), 15, 15, { 'width': 170, 'elementHandlers': specialElementHandlers }); doc.save('sample-file.pdf'); });
Content inside a <div class='html-content'>....</div>
can be downloaded as pdf with styles using jspdf & html2canvas.
You need to refer both js libraries,
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script> <script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>
Then call below function,
//Create PDf from HTML... function CreatePDFfromHTML() { var HTML_Width = $(".html-content").width(); var HTML_Height = $(".html-content").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($(".html-content")[0]).then(function (canvas) { 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("Your_PDF_Name.pdf"); $(".html-content").hide(); }); }
Ref: pdf genration from html canvas and jspdf.
May be this will help someone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With