Convert HTML code to PDFMake format with ease, bridging the gap between HTML content and PDFMake document definitions
npx @tessl/cli install tessl/npm-html-to-pdfmake@2.5.00
# html-to-pdfmake
1
2
html-to-pdfmake is a JavaScript library that converts HTML markup into PDFMake document definitions, allowing you to generate PDFs from HTML content while maintaining basic styling and structure. It supports a wide range of HTML elements, CSS properties, and works seamlessly in both browser and Node.js environments.
3
4
## Package Information
5
6
- **Package Name**: html-to-pdfmake
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install html-to-pdfmake`
10
- **Browser Support**: UMD bundle available at `html-to-pdfmake/browser.js`
11
12
## Core Imports
13
14
```javascript
15
// CommonJS (Node.js)
16
const htmlToPdfmake = require('html-to-pdfmake');
17
18
// ES6 (with bundler)
19
import htmlToPdfmake from 'html-to-pdfmake';
20
```
21
22
For browser usage:
23
```html
24
<script src="https://cdn.jsdelivr.net/npm/html-to-pdfmake/browser.js"></script>
25
<!-- Creates global htmlToPdfmake function -->
26
```
27
28
## Basic Usage
29
30
```javascript
31
const htmlToPdfmake = require('html-to-pdfmake');
32
const jsdom = require('jsdom');
33
const { JSDOM } = jsdom;
34
const { window } = new JSDOM('');
35
36
// Simple HTML conversion
37
const html = '<h1>Hello World</h1><p>This is a <strong>bold</strong> paragraph.</p>';
38
const pdfmakeContent = htmlToPdfmake(html, { window });
39
40
// Use with PDFMake
41
const pdfMake = require('pdfmake/build/pdfmake');
42
const docDefinition = { content: pdfmakeContent };
43
pdfMake.createPdf(docDefinition).getBuffer((buffer) => {
44
require('fs').writeFileSync('output.pdf', buffer);
45
});
46
```
47
48
## Architecture
49
50
html-to-pdfmake is built around several core components:
51
52
- **HTML Parser**: Uses DOM parser to convert HTML strings into document trees
53
- **Element Processor**: Recursively processes each HTML element and converts to PDFMake format
54
- **Style Engine**: Converts CSS properties to PDFMake styling properties
55
- **Table Handler**: Specialized processing for HTML tables with colspan/rowspan support
56
- **Image Manager**: Handles image references with optional reference-based loading
57
- **Color Parser**: Converts various CSS color formats (hex, rgb, rgba, hsl, named) to PDFMake format
58
59
## Capabilities
60
61
### HTML to PDFMake Conversion
62
63
Main conversion function that transforms HTML markup into PDFMake document definitions.
64
65
```javascript { .api }
66
/**
67
* Transform HTML code to a PDFMake object
68
* @param {string} htmlText - The HTML code to transform
69
* @param {object} [options] - Configuration options
70
* @returns {object|{content: object, images: object}} PDFMake document definition or content with images
71
*/
72
function htmlToPdfmake(htmlText, options);
73
```
74
75
**Parameters:**
76
- `htmlText` (string): The HTML code to transform
77
- `options` (object, optional): Configuration options
78
79
**Returns:**
80
- PDFMake document definition object
81
- If `options.imagesByReference` is true, returns `{content, images}` object
82
- If input is plain text, returns `{text: string}` object
83
84
### Configuration Options
85
86
Comprehensive options object for customizing conversion behavior.
87
88
```javascript { .api }
89
interface ConversionOptions {
90
/** Override default styles for HTML elements */
91
defaultStyles?: {
92
[elementName: string]: object;
93
};
94
/** Enable automatic table sizing based on content and CSS properties */
95
tableAutoSize?: boolean;
96
/** Handle images by reference instead of embedding (browser only) */
97
imagesByReference?: boolean;
98
/** Remove extra blank spaces that may cause extra lines in PDF */
99
removeExtraBlanks?: boolean;
100
/** Display elements with display:none or visibility:hidden */
101
showHidden?: boolean;
102
/** Don't add 'html-TAG' classes to converted elements */
103
removeTagClasses?: boolean;
104
/** Array of CSS property names to ignore during conversion */
105
ignoreStyles?: string[];
106
/** Font sizes array for legacy <font> tag size attribute (1-7) */
107
fontSizes?: number[];
108
/** Custom function to handle non-standard HTML tags */
109
customTag?: (params: CustomTagParams) => object;
110
/** The window object (required for Node.js server-side use) */
111
window?: Window;
112
/** Custom text replacement function to modify text content during conversion */
113
replaceText?: (text: string, parents: Element[]) => string;
114
}
115
116
interface CustomTagParams {
117
/** The HTML element being processed */
118
element: Element;
119
/** Array of parent elements */
120
parents: Element[];
121
/** Current PDFMake object being built */
122
ret: object;
123
}
124
```
125
126
**Default Styles Object:**
127
128
The library includes built-in default styles for HTML elements, which can be overridden:
129
130
```javascript { .api }
131
const defaultStyles = {
132
b: { bold: true },
133
strong: { bold: true },
134
u: { decoration: 'underline' },
135
del: { decoration: 'lineThrough' },
136
s: { decoration: 'lineThrough' },
137
em: { italics: true },
138
i: { italics: true },
139
h1: { fontSize: 24, bold: true, marginBottom: 5 },
140
h2: { fontSize: 22, bold: true, marginBottom: 5 },
141
h3: { fontSize: 20, bold: true, marginBottom: 5 },
142
h4: { fontSize: 18, bold: true, marginBottom: 5 },
143
h5: { fontSize: 16, bold: true, marginBottom: 5 },
144
h6: { fontSize: 14, bold: true, marginBottom: 5 },
145
a: { color: 'blue', decoration: 'underline' },
146
strike: { decoration: 'lineThrough' },
147
p: { margin: [0, 5, 0, 10] },
148
ul: { marginBottom: 5, marginLeft: 5 },
149
table: { marginBottom: 5 },
150
th: { bold: true, fillColor: '#EEEEEE' }
151
};
152
```
153
154
**Usage Examples:**
155
156
```javascript
157
// Override default styles
158
const options = {
159
window,
160
defaultStyles: {
161
h1: { fontSize: 28, bold: true, marginBottom: 8, color: 'darkblue' },
162
p: { margin: [0, 6, 0, 12], lineHeight: 1.2 },
163
a: { color: 'purple', decoration: null } // Remove underline from links
164
}
165
};
166
167
// Enable automatic table sizing
168
const tableOptions = {
169
window,
170
tableAutoSize: true
171
};
172
173
// Handle images by reference (browser only)
174
const imageOptions = {
175
imagesByReference: true
176
};
177
178
const result = htmlToPdfmake('<table><tr><td width="200">Cell</td></tr></table>', tableOptions);
179
180
// Custom text replacement
181
const textOptions = {
182
window,
183
replaceText: function(text, parents) {
184
// Replace soft hyphens with non-breaking hyphens for better PDF rendering
185
return text.replace(/-/g, "\\u2011");
186
}
187
};
188
189
const htmlWithHyphens = '<p>Some hy-phenated text that might break across lines</p>';
190
const resultWithReplacement = htmlToPdfmake(htmlWithHyphens, textOptions);
191
```
192
193
### Supported HTML Elements
194
195
**Block Elements:**
196
- `div`, `p`: Basic block containers
197
- `h1`, `h2`, `h3`, `h4`, `h5`, `h6`: Headings with built-in styling
198
- `table`, `thead`, `tbody`, `tfoot`, `tr`, `th`, `td`: Full table support with rowspan/colspan
199
- `ul`, `ol`, `li`: Lists with nesting support and custom styling
200
- `pre`: Preformatted text with whitespace preservation
201
- `hr`: Horizontal rules with customizable styling via data-pdfmake
202
203
**Inline Elements:**
204
- `span`: Generic inline container
205
- `strong`, `b`: Bold text formatting
206
- `em`, `i`: Italic text formatting
207
- `u`: Underlined text
208
- `s`, `del`, `strike`: Strikethrough text
209
- `a`: Links (external URLs and internal anchors with # prefix)
210
- `sub`, `sup`: Subscript and superscript with offset styling
211
- `img`: Images with src or data-src attributes
212
- `svg`: SVG elements (preserved as raw SVG)
213
- `br`: Line breaks
214
- `font`: Legacy font tag with size and color attribute support
215
216
**Special Elements:**
217
- Custom HTML tags via `customTag` function
218
- `div[data-pdfmake-type="columns"]`: Creates PDFMake columns layout
219
- Elements with `data-pdfmake` attributes for custom PDFMake properties
220
221
### CSS Properties Support
222
223
**Typography:**
224
- `font-family`: First font in comma-separated list
225
- `font-size`: Including keyword sizes (xx-small to xxx-large)
226
- `font-weight`: Bold support (bold keyword or numeric >= 700)
227
- `font-style`: Italic support
228
- `line-height`: Line height with percentage and unit support
229
- `color`: Full color support (hex, rgb, rgba, hsl, hsla, named colors)
230
- `text-align`: Text alignment (left, center, right, justify)
231
- `text-decoration`: underline, lineThrough, overline
232
- `text-indent`: Leading indent with unit conversion
233
- `white-space`: nowrap, pre variants, break-spaces
234
235
**Layout:**
236
- `margin`: Full margin support with shorthand and individual properties
237
- `width`, `height`: For tables, images, and table cells
238
- `background-color`: Background colors with opacity support
239
- `border`: Complete border support (width, style, color, individual sides)
240
241
**Table-Specific:**
242
- `rowspan`, `colspan`: Table cell spanning attributes
243
- Cell and table width/height sizing
244
- `fillColor`, `fillOpacity`: Table cell backgrounds
245
246
### Data Attributes
247
248
**data-pdfmake:** Add custom PDFMake properties via JSON data attribute.
249
250
```html
251
<!-- Table layout -->
252
<table data-pdfmake='{"layout":"noBorders"}'>
253
<tr><td>No border table</td></tr>
254
</table>
255
256
<!-- Custom HR styling -->
257
<hr data-pdfmake='{"width":400,"thickness":2,"color":"red"}'>
258
259
<!-- Custom element properties -->
260
<div data-pdfmake='{"pageBreak":"before","margin":[0,10,0,10]}'>
261
Content with page break
262
</div>
263
```
264
265
**data-pdfmake-type:** Special element type handling.
266
267
```html
268
<!-- Create PDFMake columns layout -->
269
<div data-pdfmake-type="columns">
270
<div>Column 1</div>
271
<div>Column 2</div>
272
<div>Column 3</div>
273
</div>
274
```
275
276
### Advanced Usage Examples
277
278
**Custom Tag Handling:**
279
280
```javascript
281
const options = {
282
window,
283
customTag: function({ element, parents, ret }) {
284
if (element.nodeName === 'HIGHLIGHT') {
285
ret.background = 'yellow';
286
ret.color = 'black';
287
} else if (element.nodeName === 'CALLOUT') {
288
ret.margin = [10, 5, 10, 5];
289
ret.fillColor = '#f0f0f0';
290
ret.border = [true, true, true, true];
291
}
292
return ret;
293
}
294
};
295
296
const html = '<p>Normal text <highlight>highlighted text</highlight> more text</p>';
297
const result = htmlToPdfmake(html, options);
298
```
299
300
**Image Handling by Reference:**
301
302
```javascript
303
// Browser environment only
304
const html = '<img src="https://example.com/image.jpg" width="200">';
305
const result = htmlToPdfmake(html, { imagesByReference: true });
306
307
// Result structure:
308
// {
309
// content: [{ image: 'img_ref_abc123', width: 200, style: ['html-img'] }],
310
// images: { 'img_ref_abc123': 'https://example.com/image.jpg' }
311
// }
312
313
// Use with PDFMake
314
pdfMake.createPdf(result).download();
315
```
316
317
**Complex Table with Auto-sizing:**
318
319
```javascript
320
const tableHtml = `
321
<table style="width:100%">
322
<colgroup>
323
<col width="30%">
324
<col width="70%">
325
</colgroup>
326
<tr style="height:50px">
327
<td style="width:200px;background-color:#eee">Header 1</td>
328
<td>Header 2</td>
329
</tr>
330
<tr>
331
<td rowspan="2" style="height:100px">Spanning cell</td>
332
<td>Regular cell</td>
333
</tr>
334
<tr>
335
<td>Another cell</td>
336
</tr>
337
</table>
338
`;
339
340
const result = htmlToPdfmake(tableHtml, {
341
window,
342
tableAutoSize: true
343
});
344
```
345
346
## Types
347
348
```javascript { .api }
349
// Return type when imagesByReference is false (default)
350
interface PDFMakeDocumentDefinition {
351
text?: string | PDFMakeElement[];
352
stack?: PDFMakeElement[];
353
table?: {
354
body: PDFMakeElement[][];
355
widths?: (number | string)[];
356
heights?: (number | string)[];
357
};
358
ul?: PDFMakeElement[];
359
ol?: PDFMakeElement[];
360
image?: string;
361
svg?: string;
362
canvas?: CanvasElement[];
363
// ... other PDFMake properties
364
}
365
366
// Return type when imagesByReference is true
367
interface PDFMakeWithImages {
368
content: PDFMakeDocumentDefinition;
369
images: {
370
[key: string]: string;
371
};
372
}
373
374
interface PDFMakeElement {
375
text?: string | PDFMakeElement[];
376
style?: string[];
377
bold?: boolean;
378
italics?: boolean;
379
decoration?: string[];
380
color?: string;
381
background?: string;
382
fontSize?: number;
383
font?: string;
384
alignment?: string;
385
margin?: number[];
386
border?: boolean[];
387
borderColor?: string[];
388
fillColor?: string;
389
fillOpacity?: number;
390
opacity?: number;
391
lineHeight?: number;
392
leadingIndent?: number;
393
noWrap?: boolean;
394
preserveLeadingSpaces?: boolean;
395
width?: number | string;
396
height?: number | string;
397
colSpan?: number;
398
rowSpan?: number;
399
link?: string;
400
linkToDestination?: string;
401
nodeName?: string;
402
id?: string;
403
[key: string]: any; // Custom data-pdfmake properties
404
}
405
406
interface CanvasElement {
407
type: string;
408
x1: number;
409
y1: number;
410
x2: number;
411
y2: number;
412
lineWidth: number;
413
lineColor: string;
414
}
415
```