html-to-pdfmake
pdfmake permits to easily create a PDF with JavaScript, but the support of HTML was missing. After reviewing issue #205 I decided to create a module to handle this feature.
Online Demo
You can find the online demo at https://aymkdn.github.io/html-to-pdfmake/index.html
Install
npm install html-to-pdfmake
How to use
This module will convert some basic and valid HTML code to its equivalent in pdfmake.
var pdfMake = require("pdfmake/build/pdfmake");
var pdfFonts = require("pdfmake/build/vfs_fonts");
pdfMake.vfs = pdfFonts.pdfMake.vfs;
var htmlToPdfMake = require("html-to-pdfmake");
var html = htmlToPdfMake(`
<div>
<h1>My title</h1>
<p>
This is a sentence with a <strong>bold word</strong>, <em>one in italic</em>,
and <u>one with underline</u>. And finally <a href="https://www.somewhere.com">a link</a>.
</p>
</div>
`);
Documentation
HTML tags supported
The below HTML tags are supported:
- DIV / P / SPAN
- BR
- B / STRONG
- I / EM
- UL / OL / LI
- TABLE / THEAD / TBODY / TFOOTER / TR / TH / TD
- H1 to H6
- IMG
Default style
I've defined some default styles for the supported element.
For example, using a <STRONG> will display the word in bold. Or, a link will appear in blue with an underline, and so on...
Customize style
Each converted element will have an associated style-class called html-tagname
.
For example, if you want all <STRONG> tags to be highlighted with a yellow backgroud you can use html-strong
in the styles
definition:
var html = htmlToPdfMake(`
<p>
This sentence has <strong>a highlighted word</strong>, but not only.
</p>
`);
var docDefinition = {
content: [
html
],
styles:{
'html-strong':{
background:'yellow'
}
}
};
var pdfDocGenerator = pdfMake.createPdf(docDefinition);
CSS class and style
The class
and styles
for the elements will also be added.
var html = htmlToPdfMake(`
<p>
This sentence has <span style="font-weight:bold" class="red">a bold and red word</span>.
</p>
`);
var docDefinition = {
content: [
html
],
styles:{
red:{
color:'red'
}
}
};
var pdfDocGenerator = pdfMake.createPdf(docDefinition);
<img>
The <img>
tag is supported, however the src
attribute must already be a base64 encoded content (as describe in the PDFMake documentation).
This is too complex and out of the scope of this module to find and convert the image source to a base64 format. You can check this Stackoverflow question to know the different ways to get a base64 encoded content from an image.
Examples
You can find more examples in example.js which will create example.pdf:
node example.js