How to Configure Fonts in html-to-pdfmake: A Complete Guide
To configure fonts in html-to-pdfmake, register your font files with PDFMake's fonts dictionary, then reference the font name in your HTML's CSS font-family property—the library forwards the name while PDFMake handles the actual rendering.
html-to-pdfmake is a lightweight parser that converts HTML/CSS into PDFMake-compatible document definitions. While it extracts typographic styles from your markup, the library does not embed font files itself. Instead, it acts as a bridge, propagating the font-family values from your HTML to PDFMake's rendering engine, where the actual font resources must be registered separately.
How Font Propagation Works
Understanding the internal flow helps debug font-related issues. The library processes fonts through four distinct stages:
Parsing and Style Extraction
In index.js, the applyStyle() function traverses the DOM tree and extracts CSS properties for each element. When it encounters a font-family declaration, it normalizes the value and stores it as a PDFMake style key.
The critical logic resides around lines 856–864 of index.js:
case "font-family":
// value is trimmed and first letter capitalized
ret.push({key: "font", value: value.charAt(0).toUpperCase() + value.slice(1)});
break;
This code block trims whitespace, capitalizes the first character of the font name (e.g., "roboto" becomes "Roboto"), and creates a style entry with the key "font". The resulting node resembles { text: "Content", font: "Roboto" }.
PDFMake Resolution
PDFMake receives this document definition and attempts to resolve "Roboto" against its pdfMake.fonts registry. If the font name matches a registered entry, PDFMake applies the corresponding TTF/OTF files. If no match exists, the document falls back to default fonts or fails to render, depending on your PDFMake configuration.
Registering Custom Fonts with PDFMake
Since html-to-pdfmake only forwards the font name, you must supply the actual font files to PDFMake through its virtual file system (VFS) or file paths.
Node.js Implementation
In Node.js environments, load PDFMake, initialize the VFS with your font files, and map the font names to file paths:
const pdfMake = require('pdfmake/build/pdfmake');
const pdfFonts = require('pdfmake/build/vfs_fonts');
const htmlToPdfmake = require('html-to-pdfmake');
const { JSDOM } = require('jsdom');
// Initialize virtual file system
pdfMake.vfs = pdfFonts.vfs;
// Register custom fonts - keys must match CSS font-family values
pdfMake.fonts = {
Roboto: {
normal: 'fonts/Roboto-Regular.ttf',
bold: 'fonts/Roboto-Bold.ttf',
italics: 'fonts/Roboto-Italic.ttf',
bolditalics: 'fonts/Roboto-BoldItalic.ttf'
}
};
// Parse HTML with font-family: Roboto
const html = `<p style="font-family: Roboto; font-size: 14px;">Custom font text</p>`;
const { window } = new JSDOM('');
const content = htmlToPdfmake(html, { window });
// Generate PDF
const docDefinition = { content };
pdfMake.createPdf(docDefinition).write('output.pdf');
Critical requirement: Pass the window object from jsdom to htmlToPdfmake() when running in Node.js. The parser requires a DOM environment to resolve CSS units and styles.
Browser Implementation
In browser environments, include the PDFMake scripts and register fonts available in your virtual file system:
<script src="https://cdn.jsdelivr.net/npm/pdfmake@latest/build/pdfmake.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/pdfmake@latest/build/vfs_fonts.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/html-to-pdfmake/browser.js"></script>
<script>
// Register fonts that exist in the VFS
pdfMake.fonts = {
OpenSans: {
normal: 'OpenSans-Regular.ttf',
bold: 'OpenSans-Bold.ttf',
italics: 'OpenSans-Italic.ttf',
bolditalics: 'OpenSans-BoldItalic.ttf'
}
};
// Convert HTML - no window option needed in browser
const html = '<p style="font-family: OpenSans;">Browser font rendering</p>';
const content = htmlToPdfmake(html);
pdfMake.createPdf({ content }).download('document.pdf');
</script>
Disabling Font Family Inheritance
If you want html-to-pdfmake to ignore font-family declarations entirely—forcing PDFMake to use its default font regardless of CSS—add the property to the ignoreStyles array:
const content = htmlToPdfmake(
'<p style="font-family: Arial;">Ignored font</p>',
{ ignoreStyles: ['font-family'] }
);
This prevents the library from creating font style entries, allowing PDFMake to apply its built-in default typography.
Summary
html-to-pdfmakeforwards font names: It extractsfont-familyfrom CSS and passes normalized names (capitalized first letter) to PDFMake as thefontproperty.- Font registration is external: You must register matching font names in
pdfMake.fontswith paths to TTF/OTF files or base64-encoded data. - Source code location: The font-family parsing logic resides in
index.jswithin theapplyStyle()function, specifically thecase "font-family":block at lines 856–864. - Node.js requires jsdom: Always provide the
windowoption when parsing HTML in Node.js environments. - Use
ignoreStylesto bypass: Add'font-family'to theignoreStylesoption to prevent CSS fonts from affecting output.
Frequently Asked Questions
Why are my custom fonts not appearing in the generated PDF?
Your fonts are not registered correctly with PDFMake. html-to-pdfmake successfully forwards the font name (visible in the generated document definition), but PDFMake cannot find matching files in pdfMake.fonts. Ensure the font name in your CSS exactly matches the key in your pdfMake.fonts object, accounting for the automatic capitalization that html-to-pdfmake applies to the first letter.
Can I use web fonts like Google Fonts directly?
No. html-to-pdfmake does not download or embed web fonts. You must download the font files (TTF or OTF format) and register them with PDFMake's virtual file system. The library only handles the CSS-to-PDFMake mapping, not font file management or network requests.
How do I prevent specific HTML font styles from affecting my PDF?
Use the ignoreStyles option when calling htmlToPdfmake(). Pass an array containing 'font-family' to strip all font declarations, or include other CSS properties like 'font-size' or 'color' to ignore those specific styles while preserving others.
Does html-to-pdfmake support font weights like bold or italic?
Yes, but indirectly. When you register a font family with PDFMake, you must provide separate file paths for normal, bold, italics, and bolditalics variants in the pdfMake.fonts dictionary. If your HTML uses <strong> or <em> tags, PDFMake automatically selects the corresponding variant from your registered font family.
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 →