This is a fork of node-html-to-image
A Node.js library that generates images from HTML
🏠 Homepage
- Fix case where base64 strings during encoding mode base64 gets wrapped in a Buffer object. By this change following the same spec as v4.0.0 of node-html-to-image
- Stricter typing for the exported function to better understand options and return data type
- Fix issue where the package might do a full process exit upon crashing. node-html-snap-image will instead simply throw and you may use a try-catch if necessary
- Added missig function parameters to the exported function
- JS Doc on the exposed function (nodeHtmlSnapImage), leading to easier use
- Update dependencies to stay up to date and fix vulnerabilities
This module exposes a function that generates images (png, jpeg) from HTML. It uses puppeteer in headless mode to achieve it. Additionally, it embarks Handlebars to provide a way to add logic in your HTML.
npm install node-html-snap-imageNote: When you install Puppeteer, it downloads a recent version of Chromium (~170MB Mac, ~282MB Linux, ~280MB Win) that is guaranteed to work with the API.
- Simple example
- TypeScript Support
- Options
- Setting output image resolution
- Example with Handlebars
- Using Handlebars helpers
- Dealing with images
- Using the buffer instead of saving to disk
- Generating multiple images
- Using different puppeteer libraries
const nodeHtmlSnapImage = require('node-html-snap-image')
nodeHtmlSnapImage({
output: './image.png',
html: '<html><body>Hello world!</body></html>'
})
.then(() => console.log('The image was created successfully!'))The library is written in Typescript so it is available out of the box:
import nodeHtmlSnapImage from 'node-html-snap-image'List of all available options:
| option | description | type | required |
|---|---|---|---|
| output | The ouput path for generated image | string | optional |
| html | The html used to generate image content | string | required |
| type | The type of the generated image | jpeg or png (default: png) | optional |
| quality | The quality of the generated image (only applicable to jpg) | number (default: 80) | optional |
| content | If provided html property is considered an handlebars template and use content value to fill it | object or Array | optional |
| waitUntil | Define when to consider markup succeded. Learn more. | string or Array (default: networkidle0) | optional |
| puppeteer | The puppeteer property let you use a different puppeteer library (like puppeteer-core or puppeteer-extra). | object (default: puppeteer) | optional |
| puppeteerArgs | The puppeteerArgs property let you pass down custom configuration to puppeteer. Learn more. | object | optional |
| beforeScreenshot | An async function that will execute just before screenshot is taken. Gives access to puppeteer page element. | Function | optional |
| transparent | The transparent property lets you generate images with transparent background (for png type). | boolean | optional |
| encoding | The encoding property of the image. Options are binary (default) or base64. |
string | optional |
| selector | The selector property lets you target a specific element to perform the screenshot on. (default body) |
string | optional |
| handlebarsHelpers | The handlebarsHelpers property lets add custom logic to the templates using Handlebars sub-expressions. Learn more. | object | optional |
| timeout | Timeout for a puppeteer-cluster (in ms). Defaults to 30000 (30 seconds). |
number | optional |
node-html-snap-image takes a screenshot of the body tag's content. If you want to set output image's resolution you need to set its dimension using CSS like in the following example.
const nodeHtmlSnapImage = require('node-html-snap-image')
nodeHtmlSnapImage({
output: './image.png',
html: `<html>
<head>
<style>
body {
width: 2480px;
height: 3508px;
}
</style>
</head>
<body>Hello world!</body>
</html>
`
})
.then(() => console.log('The image was created successfully!'))Handlerbars is a templating language. It generates HTML from a template and an input object. In the following example we provide a template to node-html-snap-image and a content object to fill the template.
const nodeHtmlSnapImage = require('node-html-snap-image')
nodeHtmlSnapImage({
output: './image.png',
html: '<html><body>Hello {{name}}!</body></html>',
content: { name: 'you' }
})
.then(() => console.log('The image was created successfully!'))Handlebars provides a lot of expressions to handle common use cases like conditions or loops.
Handlerbars sub-expressions can be used to add custom logic to the templates. To do this, you must pass a handlebarsHelpers object with functions defined within.
For example, if you had a variable and wanted to do some conditional rendering depending on its value, you could do this:
const nodeHtmlSnapImage = require('node-html-snap-image')
nodeHtmlSnapImage({
output: './image.png',
content: { myVar: 'foo' },
handlebarsHelpers: {
equals: (a, b) => a === b,
},
html: `
<html>
<body>
{{#if (equals myVar 'foo')}}<div>Foo</div>{{/if}}
{{#if (equals myVar 'bar')}}<div>Bar</div>{{/if}}
</body>
</html>`
})If you want to display an image which is stored remotely do it as usual. In case your image is stored locally I recommend having your image in base64. Then you need to pass it to the template with the content property. Here is an example:
const nodeHtmlSnapImage = require('node-html-snap-image')
const fs = require('fs');
const image = fs.readFileSync('./image.jpg');
const base64Image = new Buffer.from(image).toString('base64');
const dataURI = 'data:image/jpeg;base64,' + base64Image
nodeHtmlSnapImage({
output: './image.png',
html: '<html><body><img src="{{{imageSource}}}" /></body></html>',
content: { imageSource: dataURI }
})If you want to apply fonts, you need to synchronize your parts loading of your website. One way doing it is to convert your font to base64 and add it to your style in your html. For example:
const font2base64 = require('node-font2base64')
const _data = font2base64.encodeToDataUrlSync('../my/awesome/font.ttf')
const html = `
<html>
<head>
<style>
@font-face {
font-family: 'testFont';
src: url("{{{_data}}}") format('woff2'); // don't forget the format!
}
</style>
</head>
...If you don't want to save the image to disk and would rather do something with it immediately, you can use the returned value instead! The example below shows how you can generate an image and send it back to a client via using express.
const express = require('express');
const router = express.Router();
const nodeHtmlSnapImage = require('node-html-snap-image');
router.get(`/api/tweet/render`, async function(req, res) {
const image = await nodeHtmlSnapImage({
html: '<html><body><div>Check out what I just did! #cool</div></body></html>'
});
res.writeHead(200, { 'Content-Type': 'image/png' });
res.end(image, 'binary');
});If you want to generate multiple images in one call you must provide an array to the content property.
To save on the disk you must provide the output property on each object in the content property.
nodeHtmlSnapImage({
html: '<html><body>Hello {{name}}!</body></html>',
content: [{ name: 'Pierre', output: './image1.png' }, { name: 'Paul', output: './image2.png' }, { name: 'Jacques', output: './image3.png' }]
})
.then(() => console.log('The images were created successfully!'))If you don't want to save the images to disk you can use the returned value instead. It returns an array of Buffer objects.
const images = await nodeHtmlSnapImage({
html: '<html><body>Hello {{name}}!</body></html>',
content: [{ name: 'Pierre' }, { name: 'Paul' }, { name: 'Jacques' }]
})If you want to use different puppeteer library you must provide the puppeteer property.
const chrome = require('chrome-aws-lambda');
const nodeHtmlSnapImage = require('node-html-snap-image')
const puppeteerCore = require('puppeteer-core');
const image = await nodeHtmlSnapImage({
html: '<html><body><div>Hello</div></body></html>',
puppeteer: puppeteerCore,
puppeteerArgs: {
args: chromium.args,
executablePath: await chrome.executablePath,
}
})The main project node-html-snap-image originates from inlcudes a CLI tool
- node-html-to-image-cli - CLI for this module
npm run testOriginal Author of node-html-to-image
👤 FRIN Yvonnick frin.yvonnick@gmail.com
- Website: https://yvonnickfrin.dev
- Twitter: @yvonnickfrin
- Github: @frinyvonnick
Contributions, issues and feature requests are welcome!
Feel free to check issues page.
Give a ⭐️ if this project helped you!
Copyright © 2019 FRIN Yvonnick frin.yvonnick@gmail.com.
This project is Apache--2.0 licensed.
This README was generated with ❤️ by readme-md-generator