### 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

Title

Paragraph with bold text.

``` -------------------------------- ### Node.js Conversion Setup Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/04-configuration.md Standard setup for Node.js using jsdom to provide a window object for the conversion. ```javascript const pdfMake = require('pdfmake/build/pdfmake'); const pdfFonts = require('pdfmake/build/vfs_fonts'); const htmlToPdfmake = require('html-to-pdfmake'); const { JSDOM } = require('jsdom'); pdfMake.vfs = pdfFonts; const { window } = new JSDOM(''); const result = htmlToPdfmake(htmlString, { window }); ``` -------------------------------- ### Node.js Project Installation Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/README.md Install the necessary dependencies for using the library in a Node.js environment. ```bash npm install html-to-pdfmake jsdom ``` -------------------------------- ### Styled Conversion Configuration Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/04-configuration.md Example of overriding default styles and enabling cleanup options during conversion. ```javascript const result = htmlToPdfmake(htmlString, { defaultStyles: { h1: { fontSize: 32, bold: true }, p: { margin: [0, 10, 0, 10] }, a: { color: 'green', decoration: null } }, removeExtraBlanks: true, removeTagClasses: true }); ``` -------------------------------- ### Example output formats Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/06-conversion-flow.md Shows the structure of the returned object for standard conversion versus conversion with images enabled. ```javascript { text: "Simple text", // or array or complex object nodeName: "BODY", style: ["html-body"], // ... other PDFMake properties } ``` ```javascript { content: { /* main definition */ }, images: { "img_ref_abc0": "https://example.com/1.jpg", "img_ref_abc1": "https://example.com/2.jpg" } } ``` -------------------------------- ### Convert HTML to PDF in Browser Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/08-complete-example.md Full HTML example showing how to integrate pdfmake and html-to-pdfmake in a browser environment to trigger a PDF download. ```html

HTML to PDF Converter



``` -------------------------------- ### Complete HTML to PDF conversion workflow Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/05-advanced-usage.md Shows the full integration process including PDFMake setup, JSDOM initialization, HTML conversion, document definition, and file generation. ```javascript // 1. Setup PDFMake const pdfMake = require('pdfmake/build/pdfmake'); const pdfFonts = require('pdfmake/build/vfs_fonts'); pdfMake.vfs = pdfFonts; // 2. Node.js setup const { JSDOM } = require('jsdom'); const { window } = new JSDOM(''); // 3. Convert HTML const htmlToPdfmake = require('html-to-pdfmake'); const html = fs.readFileSync('template.html', 'utf8'); const converted = htmlToPdfmake(html, { window, defaultStyles: { h1: { fontSize: 28, bold: true } } }); // 4. Create document const docDefinition = { pageSize: 'A4', pageMargins: [40, 40, 40, 40], content: converted, styles: { 'html-h1': { fontSize: 28 }, 'html-p': { alignment: 'justify' } }, footer: { text: 'Page {page} of {pages}', alignment: 'center' } }; // 5. Generate and save pdfMake.createPdf(docDefinition) .download('output.pdf'); ``` -------------------------------- ### CSS unit conversion examples Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/03-css-properties.md Shows how various CSS units are converted into points (pt) for PDFMake compatibility. ```javascript // Examples "12px" → 9 (12 × 0.7529) "1em" → 12 (1 × 12) "1in" → 72 (1 × 72) "2.54cm" → 72 (2.54 × 28.3465) "42" → 42 (no conversion) "auto" → false (unsupported) ``` -------------------------------- ### Complex Border Configurations Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/05-advanced-usage.md Examples of applying borders to specific sides, using different colors, and varying widths. ```html

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. ```html

Text

Bold text

``` -------------------------------- ### Convert HTML to PDF in Node.js Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/08-complete-example.md Demonstrates the conversion process, document definition setup, and file generation using Node.js file system streams. ```javascript // Convert HTML console.log('Converting HTML to PDFMake format...'); const pdfMakeContent = htmlToPdfmake(htmlContent, conversionOptions); // Create PDF definition const docDefinition = { pageSize: 'A4', pageMargins: [40, 40, 40, 40], content: pdfMakeContent, styles: { // Additional PDFMake styles }, defaultStyle: { font: 'Roboto' } }; // Generate PDF console.log('Generating PDF...'); const pdf = pdfMake.createPdf(docDefinition); // Save to file pdf.getBuffer(buffer => { fs.writeFileSync('output.pdf', buffer); console.log('PDF created: output.pdf'); }); // Also create a download version (for Node CLI) pdf.getStream(function(stream) { stream.on('end', () => { console.log('Stream complete'); }); }); ``` -------------------------------- ### Configure List Type Variations Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/05-advanced-usage.md Shows how to customize list markers using CSS styles, HTML attributes, and the start attribute for ordered lists. ```html
  1. Roman I
  2. Roman II
  1. Letter a
  2. Letter b
  1. Ten
  2. Eleven
``` -------------------------------- ### Implement Custom Badge Tag Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/04-configuration.md Example of using customTag to style a custom badge element with specific background and padding properties. ```javascript const html = 'New'; const result = htmlToPdfmake(html, { customTag: function({ element, ret }) { if (element.nodeName === 'BADGE') { ret.background = '#e3f2fd'; ret.bold = true; ret.padding = [3, 8]; ret.style = ['badge', 'badge-' + element.getAttribute('type')]; } return ret; } }); ``` -------------------------------- ### Implement Custom QR Code Tag Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/04-configuration.md Example of using customTag to transform a specific HTML code element into a PDFMake QR code object. ```javascript const html = '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('

Title

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 = `

Product Report

This report demonstrates html-to-pdfmake features:

Features Included

Note: This is an alert box with styling.

Ordered List

  1. First item
  2. Second item
  3. Third item

Product Table

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

Color Support

Red text using hex

Green text using RGB

Yellow background

Blue text with 70% opacity

Links

Visit the GitHub repository or read the internal section.

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. ```html

10px 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. ```html ``` -------------------------------- ### Conversion Pipeline Overview Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/07-quick-reference.md The standard workflow for converting HTML strings into PDF files using the library. ```text HTML String → htmlToPdfmake() → PDFMake Definition → pdfMake.createPdf() → PDF File ``` -------------------------------- ### Project File Structure Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/README.md The directory layout of the html-to-pdfmake documentation repository. ```text output/ ├── README.md (this file) ├── 01-api-reference.md (functions and methods) ├── 02-supported-elements.md (HTML element catalog) ├── 03-css-properties.md (CSS support reference) ├── 04-configuration.md (configuration options) ├── 05-advanced-usage.md (advanced patterns) ├── 06-conversion-flow.md (architecture) ├── 07-quick-reference.md (quick lookup) └── 08-complete-example.md (working examples) ``` -------------------------------- ### Apply color and opacity to text Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/03-css-properties.md Demonstrates support for various color formats including Hex, RGB, and HSL, with automatic opacity extraction for alpha channels. ```html

Red 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 = `

Sample Document

This is a simple example with formatted text.

`; const converted = htmlToPdfmake(html, { window }); const docDefinition = { content: converted }; // Generate PDF pdfMake.createPdf(docDefinition).getBuffer((buffer) => { // when running the command in a terminal console using "node", then we can save the file using the 'fs' native package require('fs').writeFileSync('output.pdf', buffer); }); ``` -------------------------------- ### Apply font-size to text Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/03-css-properties.md Demonstrates conversion of various font-size units and keywords into point values. ```html

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. ```html

Underlined

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

Section 1

``` -------------------------------- ### Configure htmlToPdfmake options Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/README.md Pass an options object as the second parameter to htmlToPdfmake to customize element styles, table sizing, and image handling. ```javascript const options = { defaultStyles: { // Override default element styles that are defined below b: {bold:true}, strong: {bold:true}, u: {decoration:'underline'}, del: {decoration:'lineThrough'}, s: {decoration: 'lineThrough'}, em: {italics:true}, i: {italics:true}, h1: {fontSize:24, bold:true, marginBottom:5}, h2: {fontSize:22, bold:true, marginBottom:5}, h3: {fontSize:20, bold:true, marginBottom:5}, h4: {fontSize:18, bold:true, marginBottom:5}, h5: {fontSize:16, bold:true, marginBottom:5}, h6: {fontSize:14, bold:true, marginBottom:5}, a: {color:'blue', decoration:'underline'}, strike: {decoration: 'lineThrough'}, p: {margin:[0, 5, 0, 10]}, ul: {marginBottom:5,marginLeft:5}, table: {marginBottom:5}, th: {bold:true, fillColor:'#EEEEEE'} }, tableAutoSize: false, // Enable automatic table sizing imagesByReference: false, // Handle images by reference removeExtraBlanks: false, // Remove extra whitespace removeTagClasses: false, // Keep HTML tag classes window: window, // Required for Node.js usage ignoreStyles: [], // Style properties to ignore fontSizes: [10, 14, 16, 18, 20, 24, 28], // Font sizes for legacy tag customTag: function(params) { /* Custom tag handler */ } }; const converted = htmlToPdfmake(html, options); ``` -------------------------------- ### Handle images by reference Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/README.md Enable imagesByReference to return an object containing both content and image references, suitable for browser environments. ```javascript const html = ``; const result = htmlToPdfmake(html, { imagesByReference:true }); // 'result' contains: // { // "content":[ // [ // { // "nodeName":"IMG", // "image":"img_ref_0", // "style":["html-img"] // } // ] // ], // "images":{ // "img_ref_0":"https://picsum.photos/seed/picsum/200" // } // } pdfMake.createPdf(result).download(); ``` -------------------------------- ### Render Headings Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/02-supported-elements.md Use standard heading tags to generate text with predefined font sizes and bold styling. ```html

Level 1 Heading

Level 2 Heading

``` -------------------------------- ### Handle image references Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/01-api-reference.md Enable image reference handling to separate image sources from the main content structure. ```javascript const html = ''; 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. ```html

Bold 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 &&

{error}

}
); } ``` -------------------------------- ### Configure Window Object for Node.js Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/04-configuration.md Required for server-side usage to provide DOM APIs. Browser environments use the global window automatically. ```javascript const { JSDOM } = require('jsdom'); const { window } = new JSDOM(''); const result = htmlToPdfmake('

Title

', { window }); ``` ```javascript // Automatically uses window const result = htmlToPdfmake('

Title

'); ``` -------------------------------- ### Create Multi-Level Nested Lists Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/05-advanced-usage.md Demonstrates nesting unordered and ordered lists within each other. The stack layout automatically handles these nested block elements. ```html ``` -------------------------------- ### Margin and Padding Shorthand Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/07-quick-reference.md Shorthand syntax for defining margins. Note that the underlying PDFMake format expects [left, top, right, bottom]. ```css margin: 10px; // All sides margin: 5px 10px; // Vertical, horizontal margin: 5px 10px 15px; // Top, horizontal, bottom margin: 5px 10px 15px 20px; // Top, right, bottom, left ``` -------------------------------- ### Complete Options Object Structure Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/04-configuration.md The full structure of the options object available for customizing conversion behavior. ```javascript const options = { // DOM/Environment window: window, // window object (required for Node.js) // Style Defaults defaultStyles: { // Override default element styles h1: {fontSize: 24, bold: true, marginBottom: 5}, p: {margin: [0, 5, 0, 10]}, a: {color: 'blue', decoration: 'underline'} }, // Layout & Sizing tableAutoSize: false, // Auto-size tables based on CSS width/height // Image Handling imagesByReference: false, // Return images as references object // Content Processing removeExtraBlanks: false, // Remove extra blank lines showHidden: false, // Show display:none elements removeTagClasses: false, // Remove html-TAG classes // Style Filtering ignoreStyles: [], // CSS properties to skip fontSizes: [10, 14, 16, 18, 20, 24, 28], // Font sizes for tag // Callbacks customTag: function(params) { return params.ret; }, // Custom tag handler replaceText: function(text, nodes) { return text; } // Text replacement }; ``` -------------------------------- ### Reference External Images Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/05-advanced-usage.md Use images by reference to reduce document size and enable dynamic loading. Requires browser environment and internet access. ```javascript const html = ''; 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

Hidden 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
`; const result = htmlToPdfmake(html, { tableAutoSize: true }); ``` -------------------------------- ### Apply styles with applyStyle Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/06-conversion-flow.md Combines styles from HTML tags, classes, default styles, and inline attributes. Styles are applied in a specific order of priority. ```javascript this.applyStyle = function(params) { var ret = params.ret; var parents = params.parents; parents.forEach(function(parent, parentIndex) { // 1. Add html-TAG class if needed if (!this.removeTagClasses) { ret.style = ret.style || []; ret.style.push('html-' + parent.nodeName.toLowerCase()); } // 2. Add user-defined classes from HTML var classes = parent.getAttribute('class') || ''; classes.forEach(c => ret.style.push(c)); // 3. Apply default styles for tag if (this.defaultStyles[tagName]) { for (key in this.defaultStyles[tagName]) { ret[key] = this.defaultStyles[tagName][key]; } } // 4. Parse and apply inline styles var inlineStyles = this.parseStyle(parent); inlineStyles.forEach(stl => { ret[stl.key] = stl.value; }); }); return ret; } ``` -------------------------------- ### Render Lists Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/02-supported-elements.md Supports unordered and ordered lists with nested structures and specific list-style attributes. ```html
  1. Item C
  2. Item D
``` -------------------------------- ### Implement Centered Multi-Column Layouts Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/05-advanced-usage.md Uses the data-pdfmake-type="columns" attribute to define a column layout, utilizing width properties to center content between spacers. ```html
Centered Table
``` -------------------------------- ### Create PDFMake Columns Layout Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/02-supported-elements.md Defines a multi-column layout using the data-pdfmake-type attribute. ```html
Content here
``` -------------------------------- ### Configure fontSizes Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/04-configuration.md Define an array of 7 integers to map legacy HTML4 font size tags to specific point sizes. ```javascript → fontSizes[0] = 10pt → fontSizes[1] = 14pt → fontSizes[2] = 16pt → fontSizes[3] = 18pt → fontSizes[4] = 20pt → fontSizes[5] = 24pt → fontSizes[6] = 28pt ``` ```javascript const html = 'Small Large'; const result = htmlToPdfmake(html, { fontSizes: [8, 10, 12, 14, 16, 20, 28] // Custom scale }); ``` -------------------------------- ### Generate QR codes with customTag Source: https://github.com/aymkdn/html-to-pdfmake/blob/master/_autodocs/05-advanced-usage.md Transform specific elements into QR codes by manipulating the return object. Requires an external QR library to be loaded. ```javascript const html = `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

```