html2image
is a simple Go package that renders the given HTML string into an
Image
.
It uses Ultralight under the hood to achieve this.
Note: Ultralight isn't distributed with this library. Please make sure you're familiar with the limitations of their Free License before you proceed.
See Ultralight's prerequisites for more information. If you're on Ubuntu, the following should be enough to get you started.
apt-get install \
build-essential \
clang \
clang-format \
clang-tidy \
clang-tools \
clangd \
cmake \
libc++-dev \
libc++1 \
libc++abi-dev \
libc++abi1 \
libclang-dev \
libclang1 \
libglu1-mesa-dev \
liblldb-dev \
libllvm-ocaml-dev \
libomp-dev \
libomp5 \
libstdc++-12-dev \
libx11-dev \
lld \
lldb \
llvm \
llvm-dev \
llvm-runtime \
python3-clang \
xorg-dev
This library expects the Ultralight SDK to be in the ultralight-sdk
folder in
this repo. You can find the latest SDK here.
Assuming you have curl
and 7-zip installed, the following should work.
curl -o /tmp/sdk.7z -L 'https://ultralight-sdk-dev.sfo2.cdn.digitaloceanspaces.com/ultralight-sdk-min-latest-linux-x64.7z'
7z x /tmp/sdk.7z -o./ultralight-sdk
export ULTRALIGHT_SDK_DIR="$(realpath ./ultralight-sdk)"
If you have github.com/fstanis/html2image
as a dependency, you must provide
the path to the Ultralight SDK downloaded in the previous steps via the
CGO_CXXFLAGS
and CGO_LDFLAGS
environment variables.
This examples assumes you set ULTRALIGHT_SDK_DIR
in the previous step.
cd /path/to/your/project
go mod tidy
CGO_CXXFLAGS="-I$ULTRALIGHT_SDK_DIR/include" CGO_LDFLAGS="-L$ULTRALIGHT_SDK_DIR/bin" go build .
The following files are required at runtime:
- cacert.pem
- icudt67l.dat
- libAppCore.so
- libUltralightCore.so
- libUltralight.so
- libWebCore.so
These files should be in the subdirectory named ultralight
relatitve to your
binary. They can be found in the Ultralight SDK.
The following command copies them from their respective locations.
cd /path/to/your/project
mkdir ultralight
cp \
"$ULTRALIGHT_SDK_DIR/bin/libAppCore.so" \
"$ULTRALIGHT_SDK_DIR/bin/libUltralightCore.so" \
"$ULTRALIGHT_SDK_DIR/bin/libUltralight.so" \
"$ULTRALIGHT_SDK_DIR/bin/libWebCore.so" \
"$ULTRALIGHT_SDK_DIR/resources/cacert.pem" \
"$ULTRALIGHT_SDK_DIR/resources/icudt67l.dat" \
"./ultralight"
Simple example that renders HTML into a PNG file.
// create a new instance of a renderer with a viewport of 800x600 and scale 2.0
renderer := html2image.NewRenderer(800, 600, 2)
defer renderer.Free()
// render an image
img := renderer.Render("<div style='background-color:red'>Hello world</div>")
// write PNG file
f, _ := os.Create("image.png")
png.Encode(f, img)
f.Close()