Plugins can be used with jsPDF. To enable the printing of HTML, certain plugins must be included by following these steps:
- Visit https://github.com/MrRio/jsPDF and download the latest version.
- Add the following scripts to your project:
- jspdf.js
- jspdf.plugin.from_html.js
- jspdf.plugin.split_text_to_size.js
- jspdf.plugin.standard_fonts_metrics.js
If you wish to exclude specific elements, they must be given an ID to be ignored through a special element handler in jsPDF. Your HTML should then resemble this:
<!DOCTYPE html>
<html>
<body>
<p id="ignorePDF">don't print this to pdf</p>
<div>
<p><font size="3" color="red">print this to pdf</font></p>
</div>
</body>
</html>
Use the following JavaScript code to open the generated PDF in a new window:
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 resulted in a clean PDF that only contained the text 'print this to pdf' for me.
It's important to note that in the current version, the special element handlers only recognize IDs, as mentioned in a GitHub Issue. It states:
Matching is done against every element in the node tree, focusing on speed. Only element IDs are matched in jQuery style "#id", not all jQuery selectors.
Using class selectors like '.ignorePDF' did not work for me, so individual handlers had to be added for each ignored element:
var elementHandler = {
'#ignoreElement': function (element, renderer) {
return true;
},
'#anotherIdToBeIgnored': function (element, renderer) {
return true;
}
};
From the examples, it's noted that selecting tags like 'a' or 'li' is possible but may be too broad for some cases:
Special element handlers can be registered using jQuery-style ID selector for either ID or node name. No support for other selectors like class or compound at present.
An important point to mention is that CSS styling is lost when converting to PDF. However, jsPDF can format headings (h1, h2, h3, etc.) and only prints text nodes, omitting textarea values. For example:
<body>
<ul>
<!-- This is printed as it contains a textnode -->
<li>Print me!</li>
</ul>
<div>
<!-- Not printed because jsPDF doesn't handle value attribute -->
<input type="textarea" value="Please print me, too!">
</div>
</body>