### Run Project Examples Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/README.md Commands to install dependencies and execute the provided example script. ```bash npm install node example.js ``` -------------------------------- ### Run Node.js Setup Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/08-complete-example.md Command to execute the setup script. ```bash node setup.js ``` -------------------------------- ### Install Dependencies Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/08-complete-example.md Install the required packages for PDF generation and HTML parsing. ```bash npm install pdfmake jsdom html-to-pdfmake ``` -------------------------------- ### HTML Input Example Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/06-conversion-flow.md A sample HTML structure used as the starting point for the conversion process. ```html
Paragraph with bold text.
Border on all sides
Top border only
Left border only
Four colors
Varying widths
Mixed sides
``` -------------------------------- ### Node.js Font Setup Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/04-configuration.md Required initialization for pdfMake fonts when running in a Node.js environment. ```javascript // Must set vfs fonts before use const pdfMake = require('pdfmake/build/pdfmake'); const pdfFonts = require('pdfmake/build/vfs_fonts'); pdfMake.vfs = pdfFonts; ``` -------------------------------- ### Valid HTML Element Nesting Examples Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/02-supported-elements.md Demonstrates various valid nesting combinations for block and inline elements within the library. ```htmlText
Bold text
Paragraph in list
| Cell |
https://example.com';
const result = htmlToPdfmake(html, {
customTag: function({ element, ret, parents }) {
if (element.nodeName === 'CODE' &&
element.getAttribute('typecode') === 'QR') {
// Generate QR code from text
ret.qr = ret.text[0].text;
delete ret.text;
}
return ret;
}
});
```
--------------------------------
### Add Markers to Links
Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/04-configuration.md
Example of using replaceText to conditionally wrap text in brackets based on the parent node hierarchy.
```javascript
replaceText: function(text, nodes) {
// Add brackets around links
const isInLink = nodes.some(n => n.nodeName === 'A');
return isInLink ? `[${text}]` : text;
}
```
--------------------------------
### Normalize Whitespace in Text
Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/04-configuration.md
Example of using replaceText to collapse multiple whitespace characters into a single space.
```javascript
replaceText: function(text, nodes) {
return text.replace(/\s+/g, ' ').trim();
}
```
--------------------------------
### Legacy Font Tag Conversion
Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/02-supported-elements.md
Examples of legacy HTML font tags converted to PDFMake properties.
```html
Red text
```
```html
Small
```
--------------------------------
### Basic Usage in Browser and Node.js
Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/07-quick-reference.md
Demonstrates the primary conversion function in different environments.
```javascript
const result = htmlToPdfmake('Content
'); const docDef = { content: result }; pdfMake.createPdf(docDef).download('file.pdf'); ``` ```javascript const htmlToPdfmake = require('html-to-pdfmake'); const { JSDOM } = require('jsdom'); const { window } = new JSDOM(''); const result = htmlToPdfmake(html, { window }); ``` -------------------------------- ### Image Handling Configuration Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/04-configuration.md Enables image reference handling and demonstrates how to pass the resulting images to pdfMake. ```javascript const result = htmlToPdfmake(htmlString, { imagesByReference: true }); pdfMake.createPdf({ content: result.content, images: result.images }).download('document.pdf'); ``` -------------------------------- ### Converter Initialization Logic Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/06-conversion-flow.md Initializes the converter instance with user-provided options, default styles, and internal state tracking before executing the conversion. ```javascript function htmlToPdfMake(htmlText, options) { this.wndw = options.window || window; this.tableAutoSize = options.tableAutoSize || false; this.imagesByReference = options.imagesByReference || false; this.removeExtraBlanks = options.removeExtraBlanks || false; this.showHidden = options.showHidden || false; this.removeTagClasses = options.removeTagClasses || false; this.ignoreStyles = options.ignoreStyles || []; this.fontSizes = options.fontSizes || [10, 14, 16, 18, 20, 24, 28]; this.defaultStyles = { /* built-in defaults */ }; if (options && options.defaultStyles) { this.changeDefaultStyles(); // Merge custom defaults } this.imagesRef = []; // Track image references // ... method definitions ... // Main execution var result = this.convertHtml(htmlText); return result; // Or wrapped for imagesByReference } ``` -------------------------------- ### Replace Dashes with Non-Breaking Hyphens Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/04-configuration.md Example of using replaceText to perform global string replacement on text nodes. ```javascript const html = 'Text-with-dashes here
'; const result = htmlToPdfmake(html, { replaceText: function(text, nodes) { return text.replace(/-/g, '‑'); // Replace with non-breaking hyphen } }); ``` -------------------------------- ### Node.js Conversion Implementation Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/08-complete-example.md A complete script demonstrating HTML parsing, custom style configuration, and custom tag handling for PDF generation. ```javascript // setup.js const pdfMake = require('pdfmake/build/pdfmake'); const pdfFonts = require('pdfmake/build/vfs_fonts'); const htmlToPdfmake = require('html-to-pdfmake'); const { JSDOM } = require('jsdom'); const fs = require('fs'); // Initialize PDFMake pdfMake.vfs = pdfFonts; const { window } = new JSDOM(''); // HTML content const htmlContent = `This report demonstrates html-to-pdfmake features:
| Product | Quantity | Price | Total |
|---|---|---|---|
| Widget A | 10 | $25.00 | $250.00 |
| Widget B | 5 | $50.00 | $250.00 |
| Widget C | 15 | $15.00 | $225.00 |
| Total: | $725.00 | ||
Red text using hex
Green text using RGB
Yellow background
Blue text with 70% opacity
Visit the GitHub repository or read the internal section.
This is section 1 with an internal link reference.
Generated with html-to-pdfmake
`; // Configuration const conversionOptions = { window, defaultStyles: { h1: { fontSize: 28, bold: true, marginBottom: 10, color: '#333333' }, h2: { fontSize: 20, bold: true, marginTop: 10, marginBottom: 8, color: '#555555' }, h3: { fontSize: 16, marginBottom: 5 }, p: { margin: [0, 5, 5, 0], lineHeight: 1.4 }, a: { color: '#0066cc', decoration: 'underline' }, table: { marginTop: 10, marginBottom: 10 }, td: { margin: [3, 3, 3, 3] }, th: { bold: true, fillColor: '#f0f0f0', margin: [3, 3, 3, 3] } }, tableAutoSize: true, removeExtraBlanks: false, removeTagClasses: true, customTag: function({ element, ret, parents }) { // Custom handling for alert boxes if (element.className.includes('alert')) { ret.background = '#fff3cd'; ret.margin = [5, 5, 5, 5]; ret.padding = [8, 8, 8, 8]; } if (element.className.includes('success')) { ret.background = '#d4edda'; ret.border = [true, true, true, true]; ret.borderColor = ['#c3e6cb', '#c3e6cb', '#c3e6cb', '#c3e6cb']; } return ret; }, replaceText: function(text, nodes) { // Optional: normalize whitespace return text.replace(/\s+/g, ' '); } }; ``` -------------------------------- ### Apply CSS Margin Properties Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/03-css-properties.md Demonstrates various margin shorthand and individual property applications. ```html10px on all sides
5px top/bottom, 10px left/right
5px top, 10px sides, 15px bottom
5px top, 10px right, 15px bottom, 20px left
Custom margins
``` -------------------------------- ### Common Configuration Options Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/README.md Available options for customizing the conversion process, including environment-specific settings and style overrides. ```javascript { window, // JSDOM window (Node.js) defaultStyles, // Override element styles tableAutoSize, // Auto-size tables imagesByReference, // Image references customTag, // Custom element handler replaceText // Text modification } ``` -------------------------------- ### Process LIST elements Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/06-conversion-flow.md Maps UL and OL elements to list structures, handling type variations and start attributes. ```javascript // For UL/OL elements: // 1. Collect all LI children ret[nodeNameLowerCase] = children; // 2. Handle list type variations if (element.getAttribute('type') === 'A') { ret.type = 'upper-alpha'; } // 3. Handle start attribute if (element.getAttribute('start')) { ret.start = parseInt(value); } // 4. Handle CSS list-style-type if (ret.listStyleType) { ret.type = ret.listStyleType; } ``` -------------------------------- ### Create Styled Lists Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/README.md Shows how to apply inline styles to lists and create nested structures with custom markers. ```htmlRed text
Green text
Blue text with opacity
Green from HSL
``` -------------------------------- ### Measure conversion performance with html-to-pdfmake Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/08-complete-example.md Wraps the conversion process to capture execution time and memory usage metrics. Requires access to the performance API and process.memoryUsage. ```javascript function convertHtmlWithMetrics(htmlText, options) { const startTime = performance.now(); const startMemory = process.memoryUsage().heapUsed; const result = htmlToPdfmake(htmlText, options); const endTime = performance.now(); const endMemory = process.memoryUsage().heapUsed; const metrics = { conversionTimeMs: endTime - startTime, memoryUsedBytes: endMemory - startMemory, htmlLength: htmlText.length, resultSize: JSON.stringify(result).length }; console.log('Conversion Metrics:', metrics); return { result, metrics }; } ``` -------------------------------- ### Node.js Usage for HTML to PDF Conversion Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/README.md Initialize JSDOM to provide a window object for the library when running in a Node.js environment. ```javascript const pdfMake = require('pdfmake/build/pdfmake'); const pdfFonts = require('pdfmake/build/vfs_fonts'); const htmlToPdfmake = require('html-to-pdfmake'); // if you need to run it in a terminal console using "node", then you need the below two lines: const jsdom = require('jsdom'); const { JSDOM } = jsdom; // the below line may vary depending on your version of PDFMake // please, check https://github.com/bpampuch/pdfmake to know how to initialize this library pdfMake.vfs = pdfFonts; // if you need to run it in a terminal console using "node", then you need to initiate the "window" object with the below line: const { window } = new JSDOM(''); // Convert HTML to PDFMake format const html = `This is a simple example with formatted text.
16px text
1.5em text
Large text
``` -------------------------------- ### Usage Pattern Workflow Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/README.md Visual representation of the conversion pipeline from HTML string to final PDF file. ```text HTML String ↓ htmlToPdfmake(html, options) ↓ PDFMake Definition Object ↓ pdfMake.createPdf(docDef) ↓ PDF File ``` -------------------------------- ### Handle Images by Reference Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/04-configuration.md Returns images as references for external loading. This option is browser-only and requires passing the images object to PDFMake. ```javascript { content: { /* PDFMake definition */ }, images: { 'img_ref_abc123': 'https://example.com/image.jpg', 'img_ref_abc124': 'https://example.com/photo.png' } } ``` ```javascript const result = htmlToPdfmake(html, { imagesByReference: true }); pdfMake.createPdf({ content: result.content, images: result.images }).download('document.pdf'); ``` -------------------------------- ### Public API Export Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/06-conversion-flow.md The primary entry point for the library, which initializes the conversion process. ```javascript module.exports = function(htmlText, options) { return new htmlToPdfMake(htmlText, options); } ``` -------------------------------- ### Combining Multiple Style Sources Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/05-advanced-usage.md Illustrates how to combine default tag styles, custom class styles, and inline styles during conversion. ```javascript const html = 'Warning message
'; const converted = htmlToPdfmake(html, { defaultStyles: { p: { margin: [0, 5, 0, 5] } } }); const docDefinition = { content: converted, styles: { 'alert': { background: 'yellow', bold: true } } }; pdfMake.createPdf(docDefinition).download(); ``` -------------------------------- ### Import PDF.js Library Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/docs/index.html Import the PDF.js library as an ES module from a CDN. Ensure the workerSrc is correctly pointed to the matching worker file on the CDN. ```javascript import * as pdfjsLib from 'https://cdn.jsdelivr.net/npm/pdfjs-dist@5.4.149/build/pdf.min.mjs'; pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdn.jsdelivr.net/npm/pdfjs-dist@5.4.149/build/pdf.worker.min.mjs'; ``` -------------------------------- ### Apply text-decoration to text Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/03-css-properties.md Shows how underline and strikethrough decorations are mapped to PDFMake properties. ```htmlUnderlined
Strikethrough
``` -------------------------------- ### Define Links and Anchors Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/README.md Illustrates the syntax for external hyperlinks and internal document navigation anchors. ```html Visit Website Jump to Section
';
const result = htmlToPdfmake(html, { imagesByReference: true });
// result: {
// content: { text: [...] },
// images: { img_ref_abc123: 'https://example.com/image.jpg' }
// }
// Use with pdfMake
const doc = pdfMake.createPdf({
content: result.content,
images: result.images
});
```
--------------------------------
### Handle Color Opacity
Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/05-advanced-usage.md
Demonstrates how RGBA and HSLA colors are parsed into separate color and opacity properties.
```javascript
const html = 'Semi-transparent red
'; const result = htmlToPdfmake(html); // Returns: {text: "Semi-transparent red", color: "#ff0000", opacity: 0.7} ``` -------------------------------- ### Apply font-weight to text Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/03-css-properties.md Demonstrates how font-weight values are mapped to boolean bold properties in PDFMake. ```htmlBold text
Bold text
Normal text
``` -------------------------------- ### Generate PDF from HTML in React Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/08-complete-example.md Uses html-to-pdfmake to parse HTML content and pdfmake to generate a downloadable PDF file. Requires configuring pdfMake.vfs with vfs_fonts. ```jsx import React, { useState } from 'react'; import htmlToPdfmake from 'html-to-pdfmake'; import pdfMake from 'pdfmake/build/pdfmake'; import pdfFonts from 'pdfmake/build/vfs_fonts'; pdfMake.vfs = pdfFonts; export function PdfGenerator({ htmlContent, fileName = 'document.pdf' }) { const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); const handleGeneratePdf = async () => { try { setIsLoading(true); setError(null); // Convert HTML to PDFMake const pdfMakeContent = htmlToPdfmake(htmlContent, { defaultStyles: { h1: { fontSize: 28, bold: true, marginBottom: 10 }, h2: { fontSize: 20, bold: true, marginBottom: 8 }, p: { lineHeight: 1.4, marginBottom: 5 }, table: { marginBottom: 10 } }, tableAutoSize: true }); // Create document definition const docDefinition = { pageSize: 'A4', pageMargins: [40, 40, 40, 40], content: pdfMakeContent, footer: { text: 'Generated with React', alignment: 'center', fontSize: 10, color: '#999999' } }; // Generate PDF pdfMake.createPdf(docDefinition).download(fileName); } catch (err) { setError(err.message); } finally { setIsLoading(false); } }; return ({error}
}
';
const result = htmlToPdfmake(html, { imagesByReference: true });
pdfMake.createPdf({
content: result.content,
images: result.images
}).download('document.pdf');
```
--------------------------------
### Node.js Execution Output
Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/08-complete-example.md
Expected console output after running the conversion script.
```text
Converting HTML to PDFMake format...
Generating PDF...
PDF created: output.pdf
```
--------------------------------
### Inline Style Priority
Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/05-advanced-usage.md
Demonstrates the highest priority style application using an inline HTML attribute.
```html
Text
``` -------------------------------- ### Configure showHidden Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/04-configuration.md Enable this to include elements with display: none or visibility: hidden in the generated PDF. ```javascript const html = `Visible paragraph
`; // Without showHidden: Only "Visible paragraph" in PDF // With showHidden: Both paragraphs in PDF const result = htmlToPdfmake(html, { showHidden: true }); ``` -------------------------------- ### Enable table auto-sizing Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/01-api-reference.md Automatically calculate table column widths based on content. ```javascript const html = `| Fixed width | Auto width |
| Centered | Table |
|---|
https://example.com`;
const result = htmlToPdfmake(html, {
customTag: function({ element, ret, parents }) {
if (element.getAttribute('data-type') === 'qr') {
// QR code must be generated before calling this
ret.qr = ret.text[0].text;
delete ret.text;
ret.fit = [200, 200];
}
return ret;
}
});
```
--------------------------------
### Apply subscript and superscript
Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/02-supported-elements.md
Render text as subscript or superscript using sub and sup tags.
```html
H2O is water. E=mc2
```