Zeenobit
Zeenobit

Reputation: 5194

Render HTML as image into Buffer in Node.js

What is the easiest way to render a raw HTML string, such as:

<b>Hello World</b>

into a standard Node.js Buffer as a PNG image?

I've been searching all over npm for a module that'd let me do this, but I haven't been able to find one. They all seem to render directly into a file.

Upvotes: 3

Views: 4841

Answers (1)

Sirko
Sirko

Reputation: 74076

One way to do this is to simulate a browser environment using something like puppeteer and then use its screenshot/printing functions to create the PNG file.

Some code (after the puppeteer docu - not tested):

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.setContent( yourHTMLCode );
  await page.screenshot({path: 'example.png'});

  await browser.close();
})();

Upvotes: 8

Related Questions