Examples

How to convert HTML to a base64 image with Playwright and Go

Heads up before you start

playwright-go's module path moved from github.com/playwright-community/playwright-go to github.com/mxschmitt/playwright-go in v0.6100.0. Older tutorials use the old path, which no longer receives updates — use the new path in go get and your imports.

Install Playwright for Go and Chromium

go get github.com/mxschmitt/playwright-go
go run github.com/mxschmitt/playwright-go/cmd/playwright install chromium

playwright-go is the community-maintained Go client for Playwright. Run the commands inside a Go module (go mod init myproject first if you need one). The install command downloads the Playwright driver and a Chromium build for it automatically.

Get the base64 encoded image of some HTML and print to screen

package main

import (
	"encoding/base64"
	"fmt"
	"log"

	"github.com/mxschmitt/playwright-go"
)

func main() {
	pw, err := playwright.Run()
	if err != nil {
		log.Fatal(err)
	}
	defer pw.Stop()

	browser, err := pw.Chromium.Launch()
	if err != nil {
		log.Fatal(err)
	}
	defer browser.Close()

	page, err := browser.NewPage()
	if err != nil {
		log.Fatal(err)
	}

	if err := page.SetContent("<html><body><h1>Hello World</h1></body></html>"); err != nil {
		log.Fatal(err)
	}
	image, err := page.Screenshot()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(base64.StdEncoding.EncodeToString(image))
}

Find out how to generate a PNG from HTML with Go and Playwright.

That was 37 lines of code — plus a browser to run in production

Keeping headless browsers fed, patched and scaled is a job in itself. We built Urlbox so the same screenshot is one API call:

curl "https://api.urlbox.com/v1/YOUR_API_KEY/png?url=https://example.com"

Try the Urlbox screenshot API — free trial, no browser babysitting.