Gathering detailed insights and metrics for html-to-pdfmake
Gathering detailed insights and metrics for html-to-pdfmake
Gathering detailed insights and metrics for html-to-pdfmake
Gathering detailed insights and metrics for html-to-pdfmake
npm install html-to-pdfmake
Typescript
Module System
Node Version
NPM Version
99.3
Supply Chain
99.2
Quality
90.2
Maintenance
100
Vulnerability
100
License
JavaScript (100%)
Total Downloads
8,359,487
Last Day
19,260
Last Week
72,882
Last Month
275,164
Last Year
3,124,369
577 Stars
236 Commits
89 Forks
10 Watching
1 Branches
11 Contributors
Minified
Minified + Gzipped
Latest Version
2.5.20
Package Id
html-to-pdfmake@2.5.20
Unpacked Size
226.61 kB
Size
84.32 kB
File Count
16
NPM Version
10.2.3
Node Version
20.10.0
Publised On
06 Jan 2025
Cumulative downloads
Total Downloads
Last day
33.8%
19,260
Compared to previous day
Last week
4.5%
72,882
Compared to previous week
Last month
14.4%
275,164
Compared to previous month
Last year
8.8%
3,124,369
Compared to previous year
5
Convert HTML to PDFMake format with ease. This library bridges the gap between HTML content and PDFMake document definitions, allowing you to generate PDFs from basic HTML while maintaining based styling and structure.
Note: if you need to convert a complex HTML, check some online solutions, like Doppio, or you could try to convert your HTML to canvas and then to export it to PDF.
Try it live with the online demo.
1<!DOCTYPE html> 2<html> 3<head> 4 <!-- Include required libraries --> 5 <script src="https://cdn.jsdelivr.net/npm/pdfmake@latest/build/pdfmake.min.js"></script> 6 <script src="https://cdn.jsdelivr.net/npm/pdfmake@latest/build/vfs_fonts.min.js"></script> 7 <script src="https://cdn.jsdelivr.net/npm/html-to-pdfmake/browser.js"></script> 8</head> 9<body> 10 <script> 11 // Convert HTML to PDFMake format 12 const html = ` 13 <div> 14 <h1>Sample Document</h1> 15 <p>This is a <strong>simple</strong> example with <em>formatted</em> text.</p> 16 </div> 17 `; 18 19 const converted = htmlToPdfmake(html); 20 const docDefinition = { content: converted }; 21 22 // Generate PDF 23 pdfMake.createPdf(docDefinition).download('document.pdf'); 24 </script> 25</body> 26</html>
1npm install html-to-pdfmake jsdom
1const pdfMake = require('pdfmake/build/pdfmake'); 2const pdfFonts = require('pdfmake/build/vfs_fonts'); 3const htmlToPdfmake = require('html-to-pdfmake'); 4const jsdom = require('jsdom'); 5const { JSDOM } = jsdom; 6 7// the below line may vary depending on your version of PDFMake 8// please, check https://github.com/bpampuch/pdfmake to know how to initialize this library 9pdfMake.vfs = pdfFonts; 10 11// initiate the "window" object in Node 12const { window } = new JSDOM(''); 13 14// Convert HTML to PDFMake format 15const html = ` 16 <div> 17 <h1>Sample Document</h1> 18 <p>This is a <strong>simple</strong> example with <em>formatted</em> text.</p> 19 </div> 20`; 21 22const converted = htmlToPdfmake(html, { window }); 23const docDefinition = { content: converted }; 24 25// Generate PDF 26pdfMake.createPdf(docDefinition).getBuffer((buffer) => { 27 require('fs').writeFileSync('output.pdf', buffer); 28});
<div>
, <p>
, <h1>
to <h6>
<table>
, <thead>
, <tbody>
, <tfoot>
, <tr>
, <th>
, <td>
<ul>
, <ol>
, <li>
<pre>
<span>
, <strong>
, <b>
, <em>
, <i>
, <s>
<a>
(with support for external and internal links)<sub>
, <sup>
<img>
, <svg>
<br>
, <hr>
The library handles these CSS properties:
Property | Support Details |
---|---|
background-color | Good support |
border | Including individual borders |
color | Good support, including opacity |
font-family | Basic support |
font-style | Support for italic |
font-weight | Support for bold |
height | For tables and images |
width | For tables and images |
margin | Including individual margins |
text-align | Good support |
text-decoration | Support for underline , line-through |
text-indent | Basic support |
white-space | Support for nowrap , pre , break-spaces |
line-height | Basic support |
list-style-type | Good support |
The htmlToPdfmake
function accepts an options object as its second parameter:
1const options = { 2 defaultStyles: { 3 // Override default element styles that are defined below 4 b: {bold:true}, 5 strong: {bold:true}, 6 u: {decoration:'underline'}, 7 del: {decoration:'lineThrough'}, 8 s: {decoration: 'lineThrough'}, 9 em: {italics:true}, 10 i: {italics:true}, 11 h1: {fontSize:24, bold:true, marginBottom:5}, 12 h2: {fontSize:22, bold:true, marginBottom:5}, 13 h3: {fontSize:20, bold:true, marginBottom:5}, 14 h4: {fontSize:18, bold:true, marginBottom:5}, 15 h5: {fontSize:16, bold:true, marginBottom:5}, 16 h6: {fontSize:14, bold:true, marginBottom:5}, 17 a: {color:'blue', decoration:'underline'}, 18 strike: {decoration: 'lineThrough'}, 19 p: {margin:[0, 5, 0, 10]}, 20 ul: {marginBottom:5,marginLeft:5}, 21 table: {marginBottom:5}, 22 th: {bold:true, fillColor:'#EEEEEE'} 23 }, 24 tableAutoSize: false, // Enable automatic table sizing 25 imagesByReference: false, // Handle images by reference 26 removeExtraBlanks: false, // Remove extra whitespace 27 removeTagClasses: false, // Keep HTML tag classes 28 window: window, // Required for Node.js usage 29 ignoreStyles: [], // Style properties to ignore 30 fontSizes: [10, 14, 16, 18, 20, 24, 28], // Font sizes for legacy <font> tag 31 customTag: function(params) { /* Custom tag handler */ } 32}; 33 34const converted = htmlToPdfmake(html, options);
Object to override the default element styling. Useful for consistent document appearance:
1const options = { 2 defaultStyles: { 3 h1: { fontSize: 24, bold: true, marginBottom: 10 }, 4 p: { margin: [0, 5, 0, 10] }, 5 a: { color: 'purple', decoration: null } 6 } 7};
Boolean that enables automatic table sizing based on content and CSS properties
Example:
1const result = 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>`, { tableAutoSize:true });
For Web browser only, not for Node
Boolean that enables the images handling by reference instead of embedding. It will automatically load your images in your PDF using the {images}
option of PDFMake.
Using this option will change the output that will return an object with {content, images}
.
1const html = `<img src="https://picsum.photos/seed/picsum/200">`; 2const result = htmlToPdfmake(html, { imagesByReference:true }); 3// 'result' contains: 4// { 5// "content":[ 6// [ 7// { 8// "nodeName":"IMG", 9// "image":"img_ref_0", 10// "style":["html-img"] 11// } 12// ] 13// ], 14// "images":{ 15// "img_ref_0":"https://picsum.photos/seed/picsum/200" 16// } 17// } 18 19pdfMake.createPdf(result).download();
Function to handle custom HTML tags or modify existing tag behavior:
1const options = { 2 customTag: function({ element, ret, parents }) { 3 if (element.nodeName === 'CUSTOM-TAG') { 4 // Handle custom tag 5 ret.text = 'Custom content'; 6 ret.style = ['custom-style']; 7 } 8 return ret; 9 } 10};
Example with a QR code generator:
1const html = htmlToPdfMake(`<code typecode="QR" style="foreground:black;background:yellow;fit:300px">texto in code</code>`, { 2 customTag:function(params) { 3 let ret = params.ret; 4 let element = params.element; 5 let 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});
Boolean that will remove extra unwanted blank spaces from the PDF.
In some cases these blank spaces could appear. Using this option could be quite resource consuming.
Boolean to display the hidden elements (display:none
) in the PDF.
Boolean that permits to remove the html-TAG
classes added for each node.
Array of string to define a list of style properties that should not be parsed.
For example, to ignore font-family
:
1htmlToPdfmake("[the html code here]", { ignoreStyles:['font-family'] })
Array of 7 integers to overwrite the default sizes for the old HTML4 tag <font>
.
Function with two parameters (text
and nodes
) to modify the text of all the nodes in your HTML document.
Example:
1const result = 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});
Apply PDFMake-specific properties using the data-pdfmake
attribute:
1<!-- Custom table properties --> 2<table data-pdfmake='{"widths": [100, "*", "auto"], "heights": 40}'> 3 <tr> 4 <td>Fixed Width</td> 5 <td>Fill Space</td> 6 <td>Auto Width</td> 7 </tr> 8</table> 9 10<!-- Custom HR styling --> 11<hr data-pdfmake='{"color": "red", "thickness": 2}'>
Control page breaks using CSS classes and PDFMake's pageBreakBefore
:
1const html = ` 2 <div> 3 <h1>First Page</h1> 4 <h1 class="page-break">Second Page</h1> 5 </div> 6`; 7 8const docDefinition = { 9 content: htmlToPdfmake(html), 10 pageBreakBefore: function(node) { 11 return node.style && node.style.includes('page-break'); 12 } 13};
Support for various image formats and references:
1<!-- Best option: Base64 encoded image --> 2<!-- Required for Node environment --> 3<img src="data:image/jpeg;base64,/9j/4AAQ..."> 4 5<!-- Image by URL (with imagesByReference option) --> 6<!-- Only works with Web Browser --> 7<img src="https://example.com/image.jpg"> 8 9<!-- Image with custom headers --> 10<img data-src='{"url": "https://example.com/image.jpg", "headers": {"Authorization": "Bearer token"}}'>
For Base64 encoded image, please refer to the PDFMake documentation and here. And you can check this Stackoverflow question to know the different ways to get a base64 encoded content from an image.
1<table> 2 <thead> 3 <tr> 4 <th colspan="2">Header</th> 5 </tr> 6 </thead> 7 <tbody> 8 <tr> 9 <td rowspan="2">Cell 1</td> 10 <td>Cell 2</td> 11 </tr> 12 <tr> 13 <td>Cell 3</td> 14 </tr> 15 </tbody> 16</table>
1<ul style="margin-left: 20px"> 2 <li>First item</li> 3 <li style="color: red">Second item</li> 4 <li> 5 Nested list: 6 <ol style="list-style-type: lower-alpha"> 7 <li>Sub-item a</li> 8 <li>Sub-item b</li> 9 </ol> 10 </li> 11</ul>
1<!-- External link --> 2<a href="https://example.com">Visit Website</a> 3 4<!-- Internal link --> 5<a href="#section1">Jump to Section</a> 6<h2 id="section1">Section 1</h2>
PDFMake has a concept of columns
. We use <div data-pdfmake-type="columns"></div>
to identify it.
Example to center a table in the page:
1<div data-pdfmake-type="columns"> 2 <div data-pdfmake='{"width":"*"}'></div> 3 <div style="width:auto"> 4 <table><tr><th>Table</th><tr><tr><td>Centered</td></tr></table> 5 </div> 6 <div data-pdfmake='{"width":"*"}'></div> 7</div>
You can find more examples in example.js which will create example.pdf:
1npm install 2node example.js
You can support my work by making a donation, or by visiting my Github Sponsors page. Thank you!
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
10 commit(s) and 10 issue activity found in the last 90 days -- score normalized to 10
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
Found 3/25 approved changesets -- score normalized to 1
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
security policy file not detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2025-01-27
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