How to Set Up html-to-pdfmake in Node.js: Complete Installation Guide
To set up html-to-pdfmake in Node.js, install the package via npm and provide a JSDOM window instance through the window option, as the core conversion engine in index.js relies on window.DOMParser to parse HTML strings into pdfmake document definitions.
The html-to-pdfmake library transforms HTML strings or DOM trees into JSON structures compatible with pdfmake. According to the aymkdn/html-to-pdfmake source code, this conversion happens in index.js through a three-stage pipeline that creates a DOM, recursively walks the tree via parseElement, and aggregates styles through applyStyle before emitting the final document definition.
Installation
Install html-to-pdfmake along with jsdom, which provides the required browser environment for Node.js:
npm install html-to-pdfmake jsdom
You will also need pdfmake itself to generate the actual PDF files:
npm install pdfmake
Basic Node.js Setup
The Window Requirement
The library is environment-agnostic but requires a window object containing DOMParser. In index.js at line 44, the constructor initializes the window context:
this.wndw = (options && options.window ? options.window : window);
When running in Node.js, you must supply a fake window using JSDOM. Without this option, the library cannot parse the HTML string.
Minimal Working Example
This example demonstrates the essential setup to convert HTML to a pdfmake definition and write a PDF file:
// file: generate-pdf.js
const htmlToPdfMake = require('html-to-pdfmake');
const pdfMake = require('pdfmake/build/pdfmake');
const pdfFonts = require('pdfmake/build/vfs_fonts');
pdfMake.vfs = pdfFonts;
// Create a fake window for the library
const { JSDOM } = require('jsdom');
const { window } = new JSDOM('');
// Convert HTML to pdfmake definition
const html = `
<h1>Hello World</h1>
<p>This is <strong>bold</strong> and <em>italic</em> text.</p>
`;
const docDef = htmlToPdfMake(html, { window });
// Build and save PDF
const pdfDoc = { content: [docDef] };
pdfMake.createPdf(pdfDoc).getBuffer(buf => {
const fs = require('fs');
fs.writeFileSync('output.pdf', buf);
console.log('PDF created successfully');
});
Key point: The window option passed to htmlToPdfMake is mandatory in Node.js environments.
Configuration Options
As documented in the JSDoc header of index.js (lines 13-22), you can fine-tune the conversion by passing an options object as the second argument:
window– The JSDOM window instance (required for Node.js).defaultStyles– Override or delete preset styles for HTML tags.tableAutoSize– Boolean to make table cells respectwidthandheightCSS properties.imagesByReference– Boolean to return{content, images}structure for deduplicating large base-64 images.showHidden– Boolean to render elements withdisplay:none.removeExtraBlanks– Remove unnecessary blank nodes from the output.removeTagClasses– Prevent the library from addinghtml-${tag}classes to elements.ignoreStyles– Array of CSS properties to ignore during parsing.
Advanced Usage Examples
Handling Images by Reference
When converting HTML containing inline images, use imagesByReference to separate image data from the document structure:
const htmlToPdfMake = require('html-to-pdfmake');
const { JSDOM } = require('jsdom');
const { window } = new JSDOM('');
const html = `
<h2>Report</h2>
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUg..." />
<p>End of report</p>
`;
const result = htmlToPdfMake(html, {
window,
imagesByReference: true
});
// result contains { content, images }
console.log(Object.keys(result.images)); // ['img_ref_...']
The result.images object maps reference IDs to base-64 strings, allowing you to manage image assets separately from the document definition.
Rendering Hidden Elements and Complex Tables
To process hidden HTML elements and respect table cell dimensions:
const html = `
<div style="display:none">Hidden administrative note</div>
<table>
<tr>
<th style="width:200px">Product</th>
<th style="width:100px">Price</th>
</tr>
<tr>
<td>Widget</td>
<td>$10.00</td>
</tr>
</table>
`;
const docDef = htmlToPdfMake(html, {
window,
showHidden: true,
tableAutoSize: true
});
The showHidden option forces the parser to include elements with display:none, while tableAutoSize applies CSS width/height values to the resulting pdfmake table layout.
Summary
- html-to-pdfmake converts HTML strings into pdfmake-compatible document definitions through the logic defined in
index.js. - Node.js requires a JSDOM window instance passed via the
windowoption because the library depends onwindow.DOMParser(line 44). - The conversion pipeline creates a DOM, recursively processes nodes via
parseElement, and applies styles throughapplyStyle. - Configure output using options like
tableAutoSize,imagesByReference, andshowHiddento control table layouts, image handling, and visibility. - See
example.jsin the repository for a complete end-to-end implementation andtest/unit.jsfor supported HTML constructs.
Frequently Asked Questions
Why does html-to-pdfmake require jsdom in Node.js?
The library relies on the browser's DOMParser API to convert HTML strings into traversable DOM trees. In index.js, the constructor explicitly looks for this.wndw.DOMParser to parse the input. Since Node.js lacks a native DOM implementation, you must provide a JSDOM window object that supplies this parser.
What is the difference between using imagesByReference: true and the default image handling?
By default, html-to-pdfmake embeds base-64 image data directly into the content nodes. When you set imagesByReference: true, the function returns an object with content and images properties, where images is a separate map of reference IDs to base-64 strings. This allows pdfmake to deduplicate repeated images and reduces document definition size.
How do I customize the default styles for HTML elements?
Pass a defaultStyles object in the options to override or remove preset styles. For example, to change how <h1> elements render, you would provide { defaultStyles: { h1: { fontSize: 24, bold: true } } }. You can also delete defaults by setting a tag to null.
Can I use html-to-pdfmake without installing jsdom as a dependency?
No, jsdom (or an equivalent library providing a window with DOMParser) is mandatory for Node.js usage. The source code in index.js cannot parse HTML without this browser API. However, jsdom can be listed as a devDependency if you only use the library at build time, or you can use the pre-built browser.js bundle in environments where a real DOM is available.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →