Installations
npm install umesh-html-to-pdfmake
Developer Guide
Typescript
No
Module System
CommonJS
Node Version
16.15.1
NPM Version
8.12.1
Score
74.4
Supply Chain
98.6
Quality
75.4
Maintenance
100
Vulnerability
100
License
Releases
Contributors
Unable to fetch Contributors
Languages
JavaScript (100%)
Developer
Download Statistics
Total Downloads
461
Last Day
1
Last Week
3
Last Month
18
Last Year
85
GitHub Statistics
578 Stars
236 Commits
89 Forks
10 Watching
1 Branches
11 Contributors
Bundle Size
12.89 kB
Minified
4.49 kB
Minified + Gzipped
Package Meta Information
Latest Version
2.4.6
Package Id
umesh-html-to-pdfmake@2.4.6
Unpacked Size
193.12 kB
Size
78.93 kB
File Count
14
NPM Version
8.12.1
Node Version
16.15.1
Total Downloads
Cumulative downloads
Total Downloads
461
Last day
0%
1
Compared to previous day
Last week
-57.1%
3
Compared to previous week
Last month
500%
18
Compared to previous month
Last year
-32.5%
85
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dev Dependencies
5
html-to-pdfmake
pdfmake permits to easily create a PDF with JavaScript; however there is no support of HTML code, so 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
How to use
This module will convert some basic and valid HTML code to its equivalent in pdfmake.
Node
1npm install html-to-pdfmake
1var htmlToPdfmake = require("html-to-pdfmake"); 2// or: 3// import htmlToPdfmake from "html-to-pdfmake"
Example:
1var pdfMake = require("pdfmake/build/pdfmake"); 2var pdfFonts = require("pdfmake/build/vfs_fonts"); 3pdfMake.vfs = pdfFonts.pdfMake.vfs; 4var htmlToPdfmake = require("html-to-pdfmake"); 5 6var html = htmlToPdfmake(` 7 <div> 8 <h1>My title</h1> 9 <p> 10 This is a sentence with a <strong>bold word</strong>, <em>one in italic</em>, 11 and <u>one with underline</u>. And finally <a href="https://www.somewhere.com">a link</a>. 12 </p> 13 </div> 14`); 15 16/* 17it will return: 18{ 19 stack:[ 20 { 21 text: 'My title', 22 fontSize: 24, 23 bold: true, 24 marginBottom: 5, 25 style: ['html-h1'] 26 }, 27 { 28 text: [ 29 { 30 text: 'This is a sentence with a ' 31 }, 32 { 33 text: 'bold word', 34 bold: true, 35 style: ['html-strong'] 36 }, 37 { 38 text: ', ' 39 }, 40 { 41 text: 'one in italic', 42 italics: true, 43 style: ['html-em'] 44 }, 45 { 46 text: ', and ' 47 }, 48 { 49 text: 'one with underline', 50 decoration: 'underline', 51 style: ['html-u'] 52 }, 53 { 54 text: '. And finally ' 55 }, 56 { 57 text: 'a link', 58 color: 'blue', 59 decoration: 'underline', 60 link: 'https://www.somewhere.com', 61 style: ['html-a'] 62 }, 63 { 64 text: '.' 65 } 66 ], 67 margin: [0, 5, 0, 10], 68 style: ['html-p'] 69 } 70 ], 71 style: ['html-div'] 72} 73 */
Browser
1<script src="https://cdn.jsdelivr.net/npm/html-to-pdfmake/browser.js"></script>
Example:
1<!doctype html> 2<html lang='en'> 3<head> 4 <meta charset='utf-8'> 5 <title>my example</title> 6 <!-- pdfmake files: --> 7 <script src='https://cdn.jsdelivr.net/npm/pdfmake@latest/build/pdfmake.min.js'></script> 8 <script src='https://cdn.jsdelivr.net/npm/pdfmake@latest/build/vfs_fonts.min.js'></script> 9 <!-- html-to-pdfmake file: --> 10 <script src="https://cdn.jsdelivr.net/npm/html-to-pdfmake/browser.js"></script> 11</head> 12<body> 13 […] 14 <script> 15 var val = htmlToPdfmake("your html code here"); 16 var dd = {content:val}; 17 pdfMake.createPdf(dd).download(); 18 </script> 19</body> 20</html>
Documentation
Options
Some options can be passed to htmlToPdfmake
function as a second argument.
window
If you use Node, then you'll have to pass the window
object (see below).
defaultStyles
You can overwrite the default styles using defaultStyles
(see below).
removeExtraBlanks
In some cases, you may see some extra blank spaces in the PDF. Because removing them could be quite resource consuming, the option is false
by default.
imagesByReference
If you're using html-to-pdfmake
in a web browser with images, then you can set this option to true
and it will automatically load your images in your PDF using the {images}
option of PDFMake.
Using this option will change the output of html-to-pdfmake
that will return an object with {content, images}
.
Example:
1var ret = htmlToPdfmake(`<img src="https://picsum.photos/seed/picsum/200">`, { 2 imagesByReference:true 3}); 4// 'ret' contains: 5// { 6// "content":[ 7// [ 8// { 9// "nodeName":"IMG", 10// "image":"img_ref_0", 11// "style":["html-img"] 12// } 13// ] 14// ], 15// "images":{ 16// "img_ref_0":"https://picsum.photos/seed/picsum/200" 17// } 18// } 19 20var dd = { 21 content:ret.content, 22 images:ret.images 23} 24pdfMake.createPdf(dd).download();
fontSizes
You can overwrite the default sizes for the old HTML4 tag <font>
by using fontSizes
. It must be an array with 7 values (see below).
tableAutoSize
By passing tableAutoSize
with true
, then the program will try to define widths
and heights
for the tables, based on CSS properties width
and height
that have been provided to TH
or TD
.
Example:
1var html = htmlToPdfmake(`<table> 2 <tr style="height:100px"> 3 <td style="width:250px">height:100px / width:250px</td> 4 <td>height:100px / width:'auto'</td> 5 </tr> 6 <tr> 7 <td style="width:100px">Here it will use 250px for the width because we have to use the largest col's width</td> 8 <td style="height:200px">height:200px / width:'auto'</td> 9 </tr> 10</table>`, { 11 tableAutoSize:true 12}); 13 14// it will return something like: 15[ { 16 "table": { 17 "body": [ [ … ] ], 18 "widths": [ 188, "auto" ], 19 "heights": [ 75, 151 ] 20 } 21} ]
replaceText
By passing replaceText
as a function with two parameters (text
and nodes
) you can modify the text of all the nodes in your HTML document.
Example:
1var html = htmlToPdfmake(`<p style='text-align: justify;'>Lorem Ipsum is simply d-ummy text of th-e printing and typese-tting industry. Lorem Ipsum has b-een the industry's standard dummy text ever since the 1500s</p>`, { 2 replaceText:function(text, nodes) { 3 // 'nodes' contains all the parent nodes for the text 4 return text.replace(/-/g, "\\u2011"); // it will replace any occurrence of '-' with '\\u2011' in "Lorem Ipsum is simply d-ummy text […] dummy text ever since the 1500s" 5 } 6});
customTag
If your HTML code doesn't use regular HTML tags, then you can use customTag
to define your own result.
Example with a QR code generator:
1var html = htmlToPdfMake(`<code typecode="QR" style="foreground:black;background:yellow;fit:300px">texto in code</code>`, {, 2 customTag:function(params) { 3 var ret = params.ret; 4 var element = params.element; 5 var parents = params.parents; 6 switch(ret.nodeName) { 7 case "CODE": { 8 ret = this.applyStyle({ret:ret, parents:parents.concat([element])}); 9 ret.qr = ret.text[0].text; 10 switch(element.getAttribute("typecode")){ 11 case 'QR': 12 delete ret.text; 13 ret.nodeName='QR'; 14 if(!ret.style || !Array.isArray(ret.style)){ 15 ret.style = []; 16 } 17 ret.style.push('html-qr'); 18 break; 19 } 20 break; 21 } 22 } 23 return ret; 24 } 25});
HTML tags supported
The below HTML tags are supported:
A
(with external and internal links)DIV
/P
/SPAN
B
/STRONG
I
/EM
S
UL
/OL
/LI
TABLE
/THEAD
/TBODY
/TFOOTER
/TR
/TH
/TD
H1
toH6
FONT
IMG
SVG
SUP
/SUB
CSS properties supported
CSS can create very complex design, however this framework can only handle the most simple HTML / CSS. The support of CSS style is limited and might not work in all cases with all values:
background-color
border
color
font-family
font-style
(withitalic
)font-weight
(withbold
)height
margin
text-align
text-decoration
text-indent
white-space
(withbreak-spaces
andpre*
)width
Default styles
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...
Here is the list of defaults styles:
1{ 2 b: {bold:true}, 3 strong: {bold:true}, 4 u: {decoration:'underline'}, 5 s: {decoration: 'lineThrough'}, 6 em: {italics:true}, 7 i: {italics:true}, 8 h1: {fontSize:24, bold:true, marginBottom:5}, 9 h2: {fontSize:22, bold:true, marginBottom:5}, 10 h3: {fontSize:20, bold:true, marginBottom:5}, 11 h4: {fontSize:18, bold:true, marginBottom:5}, 12 h5: {fontSize:16, bold:true, marginBottom:5}, 13 h6: {fontSize:14, bold:true, marginBottom:5}, 14 a: {color:'blue', decoration:'underline'}, 15 strike: {decoration: 'lineThrough'}, 16 p: {margin:[0, 5, 0, 10]}, 17 ul: {marginBottom:5}, 18 li: {marginLeft:5}, 19 table: {marginBottom:5}, 20 th: {bold:true, fillColor:'#EEEEEE'} 21 }
For the old HTML4 tag <font>
, the size
attributes can have a value from 1 to 7, which will be converted to 10pt, 14pt, 16pt, 18pt, 20pt, 24pt, or 28pt.
Please, note that the above default styles are stronger than the ones defined in the style classes. Read below how to overwrite them.
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:
1var html = htmlToPdfmake(` 2 <p> 3 This sentence has <strong>a highlighted word</strong>, but not only. 4 </p> 5 `); 6 7var docDefinition = { 8 content: [ 9 html 10 ], 11 styles:{ 12 'html-strong':{ 13 background:'yellow' // it will add a yellow background to all <STRONG> elements 14 } 15 } 16}; 17 18var pdfDocGenerator = pdfMake.createPdf(docDefinition);
CSS class and style
The class
and styles
for the elements will also be added.
1var html = htmlToPdfmake(` 2 <p> 3 This sentence has <span style="font-weight:bold" class="red">a bold and red word</span>. 4 </p> 5 `); 6 7/* 8It returns: 9{ 10 text: [ 11 { 12 text: 'This sentence has ' 13 }, 14 { 15 text: 'a bold and red word', 16 style: ['red', 'html-span'], // 'red' added because of `class="red"` 17 bold: true // added because of `style="font-weight:bold"` 18 }, 19 { 20 text: '.' 21 } 22 ], 23 margin: [0, 5, 0, 10], 24 style: ['html-p'] 25} 26*/ 27 28var docDefinition = { 29 content: [ 30 html 31 ], 32 styles:{ 33 red:{ // we define the class called "red" 34 color:'red' 35 } 36 } 37}; 38 39var pdfDocGenerator = pdfMake.createPdf(docDefinition);
Please, note that the default styles are stronger than the ones defined in the style classes. For example, if you define a class html-a
to change all links in purple, then it won't work because the default styles will overwrite it:
1var docDefinition = { 2 content: [ 3 html 4 ], 5 styles:{ 6 'html-a':{ 7 color:'purple' // it won't work: all links will remain 'blue' 8 } 9 } 10}; 11
To make it work, you have to either delete the default styles, or change it with a new value. Starting v1.1.0
, an option parameter is available as a second parameter.
Example: you want <li>
to not have a margin-left, and <a>
to be 'purple' and without 'underline' style:
1var html = htmlToPdfmake('<ul><li>this is <a href="...">a link</a></li><li>another item</li><li class="with-margin">3rd item with a margin</li></ul>', { 2 defaultStyles:{ // change the default styles 3 a:{ // for <A> 4 color:'purple', // all links should be 'purple' 5 decoration:'' // remove underline 6 }, 7 li:'' // remove all default styles for <LI> 8 } 9}); 10 11var docDefinition = { 12 content: [ 13 html 14 ], 15 styles:{ 16 'with-margin':{ 17 marginLeft: 30 // apply a margin with the specific class is used 18 } 19 } 20};
Units
PDFMake uses pt
units for the numbers. html-to-pdfmake
will check the inline style to see if a number with unit is provided, then it will convert it to pt
.
It only works for px
, pt
, em
and rem
(for em
/rem
it's based on 1rem = 16px
);
Examples:
font-size:16px
will be converted tofontSize:12
margin:1em
will be converted tomargin:12
<img>
If you use html-to-pdfmake
in a Web browser, then you could just pass the option imagesByReference
with the value true
and the images will be passed by references (starting from PDFMake v0.1.67).
Otherwise the src
attribute must be a base64 encoded content (as describe in the PDFMake documentation) or a reference (see more here).
You can check this Stackoverflow question to know the different ways to get a base64 encoded content from an image.
page break
You can use pageBreakBefore
and a CSS class that you'll apply to your elements to identify when to add a page break:
1var html = htmlToPdfmake(` 2 <div> 3 <h1>My title on page 1</h1> 4 <p> 5 This is my paragraph on page 1. 6 </p> 7 <h1 class="pdf-pagebreak-before">My title on page 2</h1> 8 <p>This is my paragraph on page 2.</p> 9 </div> 10`); 11 12var docDefinition = { 13 content: [ 14 html 15 ], 16 pageBreakBefore: function(currentNode) { 17 return currentNode.style && currentNode.style.indexOf('pdf-pagebreak-before') > -1; 18 } 19}; 20 21var pdfDocGenerator = pdfMake.createPdf(docDefinition);
See example.js to see another example.
Special properties
PDFMake provides some special attributes, like widths
or heights
for table
, or fit
for image
, and more.
To apply these special attributes, you have to use the attribute data-pdfmake
on your HTML elements, and then pass the special attributes as a JSON string.
1<!-- Example with `widths:[100,"*","auto"]` and `heights:40` to apply to a `table`. --> 2 3<table data-pdfmake="{'widths':[100,'*','auto'],'heights':40}"> 4 <tr> 5 <td colspan="3">Table with <b>widths=[100,"*","auto"]</b> and <b>heights=40</b></td> 6 </tr> 7 <tr> 8 <td>Cell1</td> 9 <td>Cell2</td> 10 <td>Cell3</td> 11 </tr> 12</table>
The expression provided by data-pdfmake
must be a valid JSON string because it will be translated with JSON.parse()
.
<hr>
An <hr>
can also be customized using data-pdfmake
. Some default styles are applied to this element:
1{ 2 left:0, // the left position 3 width:514, // should be OK with a A4 page 4 color:'black', // the color of the line 5 thickness:0.5, // how thick the line must be 6 margin:[0,12,0,12] // same order as PDFMake, meaning: [left, top, right, bottom] 7}
See the example.js file to see a <hr>
example.
Use with Node
To use it in a Node script you need to install jsdom
:
1npm install jsdom
Then in your JS file:
1var pdfMake = require("pdfmake/build/pdfmake"); 2var pdfFonts = require("pdfmake/build/vfs_fonts"); 3pdfMake.vfs = pdfFonts.pdfMake.vfs; 4var fs = require('fs'); 5var jsdom = require("jsdom"); 6var { JSDOM } = jsdom; 7var { window } = new JSDOM(""); 8var htmlToPdfMake = require("html-to-pdfmake"); 9 10var html = htmlToPdfMake(`<div>the html code</div>`, {window:window}); 11 12var docDefinition = { 13 content: [ 14 html 15 ] 16}; 17 18var pdfDocGenerator = pdfMake.createPdf(docDefinition); 19pdfDocGenerator.getBuffer(function(buffer) { 20 fs.writeFileSync('example.pdf', buffer); 21});
Examples
You can find more examples in example.js which will create example.pdf:
1npm install 2node example.js
Donate
You can support my work by making a donation, or by visiting my Github Sponsors page. Thank you!
No vulnerabilities found.
Reason
9 commit(s) and 8 issue activity found in the last 90 days -- score normalized to 10
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
Found 3/25 approved changesets -- score normalized to 1
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/needs-reply-remove.yml:1
- Warn: no topLevel permission defined: .github/workflows/needs-reply.yml:1
- Info: no jobLevel write permissions found
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/needs-reply-remove.yml:16: update your workflow using https://app.stepsecurity.io/secureworkflow/Aymkdn/html-to-pdfmake/needs-reply-remove.yml/master?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/needs-reply.yml:12: update your workflow using https://app.stepsecurity.io/secureworkflow/Aymkdn/html-to-pdfmake/needs-reply.yml/master?enable=pin
- Info: 0 out of 2 third-party GitHubAction dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 8 are checked with a SAST tool
Score
4.5
/10
Last Scanned on 2025-02-03
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More