Socket
Socket
Sign inDemoInstall

node-image-from-html

Package Overview
Dependencies
65
Maintainers
1
Versions
15
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    node-image-from-html

This single-dependency library provides a simple API to render HTML content using Puppeteer (A headless chromium brower) into png and jpeg images, insuring security and efficiency in the process. Writte


Version published
Weekly downloads
1
decreased by-83.33%
Maintainers
1
Created
Weekly downloads
 

Readme

Source

Node-Image-From-HTML🖼️

Discord Banner 2

About

This single-dependency library provides a simple API to render HTML content using Puppeteer (A headless chromium brower) into png and jpeg images, insuring security and efficiency in the process. Written in TypeScript, it comes with native typings, supporting both CommonJS & ES6 imports.

 

Question: Why use this over other libraries?

This library is actively maintained, and uses a persistant browser instance to render the content, allowing it to render images within a matter of milliseconds after starting. On top of this, Network Requests & Javascript can be disabled within the rendering process to avoid any potential security issues.

Question: What processing power is needed?

Anything that's able to run an instance of chrome is able to render images, only one instance of chromium is open at a time, with each 'concurrent' instance just being an additional tab on the browser, so the overhead isn't too bad.

Question: Can I use CSS?

Yes, all css is supported, and can be done inline or as a <style></style> block.

Question: Why can't the library do xyz?

If it can't do something, create an issue for it and i'll be happy to add any missing features!

Usage:

Configuration:

BrowserHandlerOptions

NameDescriptionType
concurrencyThe amount of tabs/render jobs that can process at oncenumber
timeoutThe max timeout a tab should wait before giving up.number
disableJavaScriptDisable JavaScript in the browser.boolean
disableNetworkDisable network in the browser.boolean

ScreenshotOptions

NameDescriptionType
omitBackgroundAn optional parameter to disable the white background behind the image when rendering a PNG.boolean
selectorAn optional parameter to select which element to render an image of. If unspecified, the entire page will be rendered. View https://www.w3schools.com/cssref/css_selectors.asp for more information on CSS selectors.string
fullPageA deprecated parameter to choose to screenshot the whole page or a portion of it.boolean
qualityAn optional number from 1 to 100 to determine the quality of a JEPG exported image.number
typeAn optional parameter to choose the type of image to take. jpeg, png, or webp, (PNG being the default.)string

Examples

Simple Rendering

// In an Async Context,

const NodeImageFromHtml = require("node-image-from-html");
const fs = require("fs");

const engine = new NodeImageFromHtml.BrowserHandler();

await engine.start();
const rendered = await engine.render("<h1>Node-Image-From-HTML</h1>");

// Write the rendered buffer
fs.writeFileSync("renderedImage.png", rendered);

Multiple Renders

In the situation where there's more rendering jobs than there are available tabs, the engine will automatically queue the jobs, only processing a new one when the previous one is finished, while still making sure that all the tabs are rendering.

const NodeImageFromHtml = require("..");
const fs = require("fs");

// 5 concurrent rendering jobs. 
const engine = new NodeImageFromHtml.BrowserHandler({ concurrency: 5 });

// Using an IIFE to provide an async context.
(async () => {
    await engine.start();

    const renders = 25;

    // Giving the element a unique id allows us to only screenshot the element using a CSS selector,
    // https://www.w3schools.com/cssref/css_selectors.asp
    const html = "<h1 id='title'>Node-Image-From-HTML</h1>";
    const promises = [];

    // Add the promises to queue
    for (let i = 0; i < renders; i++) {
        promises.push(engine.render(html, {
            omitBackground: true,
            fullPage: false,
            selector: "#title"
        }));
    }

    // Write the files once they finish.
    const startTime = Date.now();
    const results = await Promise.all(promises)
    console.log(`Finished in ${Date.now() - startTime}ms`);

    for (let i = 0; i < results.length; i++) {
        fs.writeFileSync(`renderedImage${i}.png`, results[i]);
    }
})()

Embedding Images

The library exposes a 'utils' object, containing methods useful for the library. In this case, we can transform an image buffer into a data URI, letting us insert into the rendered image.

const NodeImageFromHtml = require("..");

const fs = require("fs");

const engine = new NodeImageFromHtml.BrowserHandler();

(async () => {
    await engine.start();

    const buffer = fs.readFileSync("./myImage.png");
    const html = `
    <div id="ImageExample">
        <h1>An embedded image!</h1>
        <img src="${NodeImageFromHtml.utils.toDataUri(buffer)}" />
    </div>
    `;

    const rendered = await engine.render(html, { selector: "#ImageExample" });
    fs.writeFileSync("myImage.png", rendered);
    engine.dispose();
})()

Commit Guidelines

The latest version of the code base will always be under the 'next' branch!

  • All pull requiests must provide a valid reason for the change or implementation
  • All CORE CHANGES require an issue with reasoning made before a PR will even be addressed.
  • All PR's must follow the general structure of the code base
  • If you have questions, feel free to make an issue and i'll get to it right away!

Buy Me A Coffee

Keywords

FAQs

Last updated on 22 Jun 2022

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc