Generate PDF from HTML in div using Javascript
The task that needs to be accomplished is to convert the content of a div with the ID "pdf" into a PDF document. This PDF document must be automatically downloaded with the filename "foobar.pdf."
While jspdf is commonly used for PDF generation, its text function limitation presents a challenge. It only accepts string values, whereas HTML input is required. To address this issue, plugins, such as jspdf.plugin.from_html.js and jspdf.plugin.split_text_to_size.js, are required. Here's how to use these plugins to achieve the desired result:
jspdf.js jspdf.plugin.from_html.js jspdf.plugin.split_text_to_size.js jspdf.plugin.standard_fonts_metrics.js
<!DOCTYPE html> <html> <body> <p>
var doc = new jsPDF(); var elementHandler = { '#ignorePDF': function (element, renderer) { return true; } }; var source = window.document.getElementsByTagName("body")[0]; doc.fromHTML( source, 15, 15, { 'width': 180,'elementHandlers': elementHandler }); doc.output("dataurlnewwindow");
This method will create a PDF containing the text "print this to pdf."
It's crucial to note that special element handlers primarily handle IDs in the current version. Consequently, using class selectors (e.g., '.ignorePDF') won't produce the intended result.
Moreover, jsPDF lacks support for CSS styling and will only print text within text nodes. Therefore, values from textareas and similar elements won't be included in the PDF.
The above is the detailed content of How to Generate a PDF from HTML within a Div using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!