Guides

February 5, 2023

3 Ways to Programmatically Convert HTML to Images

Introducing a quick reference guide to using Playwright, Puppeteer, Selenium and more to programmatically generate images, documents and screenshots.

Jonathan Markwell
Jonathan Markwell
2 min read
Share this article:

Making screenshots and converting HTML to images should be easy.

There are many open source projects that can help. But few of them are primarily made for generating images. Playwright, Puppeteer and Selenium are all purpose browser automation tools

That means things that should be simple often require digging deep into documentation, looking at source code or a chance find on StackOverflow.

What you need is the exact code, in your favorite language, to take the kind of screenshot you want.

Introducing HTMLtoImage.com

We've started creating just such a resource at HTMLtoImage.com.

Here are 3 examples giving a flavour of what you can find there:

Screenshot of a particular element with Python and Playwright

import asyncio
from playwright.async_api import async_playwright
 
async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        page = await browser.new_page()
        await page.goto('https://www.bbc.co.uk/news/business-63709754')
        await page.locator('.ssrcss-hmf8ql-BoldText').screenshot(path='element.png')
        await browser.close()
 

Find the full screenshot example on HTMLtoImage.com

More examples using Python and Playwright

Retina screenshots with Ruby and Selenium

require 'webdrivers'
 
options = Selenium::WebDriver::Chrome::Options.new
options.add_argument('--force-device-scale-factor=2')
 
driver = Selenium::WebDriver.for :chrome, options: options
 
driver.get "https://www.bbc.co.uk/news/business-63709754"
 
driver.manage.window.resize_to(480, 240)
 
driver.save_screenshot("./retina.png")

Find the full retina image example on HTMLtoImage.com

More examples using Ruby and Selenium

How to take a full page screenshot with Python and Puppeteer

import asyncio
from pyppeteer import launch
 
async def main():
    browser = await launch()
    page = await browser.newPage()
 
    await page.goto('https://www.bbc.co.uk/news/business-63709754')
    await page.screenshot({'path': "full-page.png", 'fullPage': True})
 
    await browser.close()

Find the full page screenshot example on HTMLtoImage.com

More examples using Python and Puppeteer

More to come

We've been providing an API to do all this an more for over a decade. But in many situations you don't need so much power.

Next time you just want to get some images from HTML head to HTMLtoImage.com

Free Trial

Ready to start rendering?

Designers, law firms and infrastructure engineers trust Urlbox to accurately and securely convert HTML to images at scale. Experience it for yourself.

7 day free trial.No credit card required.