The Node HTML transformers
class is designed to facilitate the conversion of HTML content to other formats, specifically to PDF and image. It provides methods to replace placeholders in the HTML content and then convert the processed HTML to a PDF file or an image.
Make sure you have Node.js and npm installed. Install the required dependencies using the following command:
npm install node-html-transformers
import HtmlTransformer from 'node-html-transformers';
// Create an instance of the HTMLTransformer class
const converter = new HtmlTransformer('path/to/html/file.html', 'utf-8', { variable1: 'value1', variable2: 'value2' });
// Convert HTML to PDF
const pdfContent = await converter.toPDF('output.pdf');
console.log('Base64-encoded PDF Content:', pdfContent);
// Convert HTML to Image
const imageContent = await converter.toImage('output.png');
console.log('Base64-encoded Image Content:', imageContent);
You can create placeholders in HTML documents and then Dynamically pass in data.
To do this you should surround the placeholder variable with double curly braces e.g {{placeholderVariable}}
.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test Document</title>
</head>
<body>
<h1>
Sample template in html
</h1>
<p>
My name is {{name}}, I am {{age}} years old.
</p>
<img src={{imageUrl}} />
</body>
</html>
Then, pass the same variable name as a field to the content {placeholderVariable:value}
argument when creating an instance of the HtmlTransformer class e.g
import HtmlTransformer from 'node-html-transformers';
// Create an instance of the HTMLTransformer class
const converter = new HtmlTransformer('path/to/html/file.html', 'utf-8', { name: 'Ayomikun', age: '20' });
Converts the HTML content to a string with replaced placeholders. returns a string
const htmlString = await converter.toString();
Converts the HTML content to a PDF file. -- returns a base64 encoded PDF string
const pdfContent = await converter.toPDF('output.pdf');
console.log('Base64-encoded PDF Content:', pdfContent);
Converts the HTML content to an image. -- returns a base64 encoded Image string
const imageContent = await converter.toImage('output.png');
console.log('Base64-encoded Image Content:', imageContent);
- filePath: The file path of the HTML file to be converted.
- encoding: The encoding of the HTML file. Defaults to 'utf-8'.
- content: An object containing key-value pairs for replacing placeholders in the HTML content.
- Dependencies
- puppeteer: Headless Chrome browser automation library.
Feel free to contribute by opening issues or submitting pull requests. Contributions are welcome!
This project is licensed under the MIT License.