How to Replace Text During HTML-to-PDFMake Conversion: A Complete Guide
Use the replaceText option in html-to-pdfmake to intercept and modify text content during conversion by providing a function that receives the raw text and its ancestor nodes, then returns the modified string.
The html-to-pdfmake library transforms HTML strings into PDFMake-compatible document definitions, but raw HTML often contains characters or patterns that need sanitization before rendering to PDF. Whether you need to substitute special characters, redact sensitive information, or apply context-specific formatting, the replaceText hook allows you to replace text during HTML-to-PDFMake conversion without preprocessing your HTML string.
Understanding the replaceText Hook in html-to-pdfmake
The conversion engine processes HTML node-by-node in index.js. When it encounters a text node, it extracts the raw string and checks for the replaceText option before creating the PDFMake text object.
At lines 166–168 in index.js, the library implements the hook:
if (options && typeof options.replaceText === "function")
text = options.replaceText(text, parents);
The function receives two parameters:
text– The raw string content of the current text node.parents– An array of all ancestor DOM elements, enabling context-aware logic based on parent tags or classes.
Your function must return a string. Return the modified text to apply changes, or return the original text to leave it unchanged.
Implementing Text Replacement: Three Practical Examples
Basic Character Substitution
Replace all regular hyphens with non-breaking hyphens to prevent unwanted line breaks in specific content:
const html = `<p>Lorem-ipsum dolor-sit amet.</p>`;
const docDefinition = {
content: htmlToPdfmake(html, {
replaceText: (text, nodes) => text.replace(/-/g, '\u2011')
})
};
Context-Aware Replacement
Use the parents array to apply transformations only within specific HTML elements. This example masks digits only when they appear inside <code> blocks:
const html = `
<p>Version: 1.2.3</p>
<code>12345</code>
`;
const docDefinition = {
content: htmlToPdfmake(html, {
replaceText: (text, nodes) => {
const insideCode = nodes.some(node => node.nodeName === 'CODE');
return insideCode ? text.replace(/\d/g, '#') : text;
}
})
};
Advanced Text Transformation
While replaceText modifies the string content, you can use it to inject markdown-style markers that PDFMake can interpret, or prepare text for post-processing. This example wraps the word "important" with markers for later styling:
const html = `<p>This is important information.</p>`;
const docDefinition = {
content: htmlToPdfmake(html, {
replaceText: (text) => text.replace(/important/g, '**important**')
})
};
Technical Implementation Details
The Core Logic in index.js
The replaceText integration occurs within the parseElement function in index.js. The library traverses the DOM recursively, and when it identifies a node of type 3 (text node), it immediately checks for the replacement function before applying any default styling or wrapping.
This placement ensures that text modifications happen before PDFMake object creation, allowing your custom logic to affect the final output without interfering with style inheritance or layout calculations.
Return Value Requirements
The replaceText function must always return a string value. Returning undefined, null, or an object will cause the conversion to fail or produce invalid PDFMake definitions. If no modification is required for a particular node, simply return the original text parameter unchanged.
The function executes synchronously; asynchronous text processing is not supported within this hook. For complex async transformations, preprocess your HTML before passing it to html-to-pdfmake.
Summary
- The
replaceTextoption inhtml-to-pdfmakeprovides a synchronous hook to modify text content during conversion atindex.jslines 166–168. - The function receives the raw
textstring and aparentsarray containing all ancestor DOM elements for context-aware processing. - Return a modified string to change the output, or return the original string to leave content unchanged; never return
undefinedor non-string values. - Use this hook for character substitution, sensitive data redaction, or conditional formatting based on parent HTML elements.
Frequently Asked Questions
Can I use replaceText to remove text content entirely?
Yes. To remove text content, return an empty string "" from your replaceText function. This will effectively delete that text node from the final PDF output. Be cautious when removing text inside inline elements, as this may affect layout or leave empty parent containers.
Does replaceText affect text inside tables, lists, and other complex structures?
Yes. The replaceText hook processes every text node in the HTML document regardless of its parent structure. Text inside <td>, <li>, <span>, or any other element passes through this function. Use the parents parameter to detect specific container types if you need to apply different logic for text in tables versus paragraphs.
Can I change text styling using the replaceText option?
No. The replaceText function can only modify the string content of text nodes. It cannot directly alter PDFMake style properties like bold, italics, or fontSize. To apply conditional styling, you would need to either use the customTag option to handle specific elements, or post-process the resulting PDFMake document definition after conversion.
What happens if my replaceText function returns undefined or null?
Returning undefined, null, or any non-string value from replaceText will cause the conversion to fail or produce invalid PDFMake document definitions. The library expects a string return value to populate the text content of the PDF node. Always ensure your function returns a string, even if it's just the original text parameter unchanged.
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 →