t2i

package module
v0.0.0-...-073c9d7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 29, 2026 License: MIT Imports: 19 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

htmlrender

Render HTML and Markdown cards into images from Go. Use an embedded renderer, a shared HTTP service, or a lightweight HTTP client. Both Blitz and Chromium are available.

简体中文 · AlonaBot integration · Native build

Use case Entry point
Small server or several bots sharing a renderer client → a service you operate
Rendering inside a Go application t2i.New with the required backends
Shell commands and a persistent local service cmd/t2i
AlonaBot plugins sharing connection settings Separate alonabot module

The Go package name is t2i; its module path is github.com/AlonaBot/htmlrender.

Call a remote service

go get github.com/AlonaBot/htmlrender@main
import (
    t2i "github.com/AlonaBot/htmlrender"
    "github.com/AlonaBot/htmlrender/client"
)

c, err := client.New(client.Config{
    Endpoint: "https://render.example.com",
    Token:    token,
})
if err != nil {
    return err
}
defer c.Close()

result, err := c.Render(ctx, t2i.Request{
    HTML: `<article id="card" style="width:600px;padding:24px"><h1>Hello, world</h1></article>`,
    Engine: t2i.Chromium,
    Options: t2i.Options{Width: 800, Selector: "#card"},
})
// result.Data contains the image bytes; result.Width/Height are physical pixels.

The client builds with CGO_ENABLED=0. Chrome and the Blitz native library run on the rendering host. The HTTP example sends an embedded card, font, CSS and images; it reads the token from HTMLRENDER_TOKEN.

Render inside a Go application

import (
    t2i "github.com/AlonaBot/htmlrender"
    "github.com/AlonaBot/htmlrender/backend/chromium"
)

renderer, err := t2i.New(t2i.Config{
    DefaultEngine: t2i.Chromium,
    Engines: map[string]t2i.EngineConfig{
        t2i.Chromium: {New: chromium.Factory(""), Concurrency: 2},
    },
})
if err != nil {
    return err
}
defer renderer.Close()

result, err := renderer.Render(ctx, t2i.Request{Markdown: "# A card from Go"})

Pass the same renderer to callers in the process. Chromium shares one browser across task slots and creates an independent browser context for each request. Blitz creates one native context per task slot. Engines initialize on first use; Warmup(engine) initializes one early. Close waits for admitted tasks and closes initialized backends.

To use Blitz, register t2i.Blitz: {New: blitz.New} and follow the native linking instructions. The embedded example registers both engines. An empty default engine selects Blitz; an omitted request engine uses the configured default. Engine failures preserve their cause.

Send fonts and images with the card

assets, err := t2i.AssetsFromFS(os.DirFS("assets"))
if err != nil {
    return err
}
result, err := c.Render(ctx, t2i.Request{
    HTML: `<link rel="stylesheet" href="styles/card.css"><article id="card">Hello</article>`,
    Assets: assets,
    Engine: t2i.Chromium,
    Options: t2i.Options{Selector: "#card", OmitBackground: true},
})

Assets maps relative slash-separated paths to file bytes. AssetsFromFS also accepts embed.FS or an fs.Sub view. It rejects symlinks and special files. Nested CSS references such as ../fonts/Roboto.ttf retain their meaning. A request-local loopback server serves the bundle until rendering finishes; JSON transports byte slices as base64.

Choose either Assets or BaseURL. BaseURL keeps its existing meaning: relative resources load from that address on the rendering host. HTTP(S) resource URLs remain available. A file:// URL reads the rendering host's files. Missing images, CSS, or fonts return the resource error to the caller.

Templates are rendered by the caller. HTML and Markdown are alternative inputs; Gonja remains excluded.

Build and use the CLI

The toolchain uses Go 1.27.3, Rust 1.91 or newer, and a C compiler. Install Chrome/Chromium on the rendering host. Linux additionally needs Fontconfig development files; install Chinese fonts for Chinese cards, for example libfontconfig1-dev and fonts-noto-cjk on Debian/Ubuntu.

asdf install
make build
./bin/t2i render demo/fixtures/bundled/card.html \
    --assets-dir demo/fixtures/bundled --selector '#card' \
    --engine blitz --transparent -o card.png
./bin/t2i render demo/fixtures/bundled/card.html \
    --assets-dir demo/fixtures/bundled --selector '#card' \
    --engine chromium --endpoint https://render.example.com -o remote.png

Set HTMLRENDER_TOKEN for an authenticated endpoint. --token can also supply it. --embedded runs the engines in the CLI process. Without --embedded or --endpoint, render starts or reuses a persistent local service.

./bin/t2i start --concurrency 2
./bin/t2i status
./bin/t2i stop
make demo

One system user and runtime directory share an instance. Its startup settings stay effective until stopped. The default directory is the system user cache directory's t2i-go/default; service.log lives there. start/status/stop use a private Unix control socket on macOS/Linux. stop waits for active tasks. make demo writes images under demo/output/, including long Markdown, transparent output, local resources, and a Chromium script page.

Other render flags include --width, --height, --dpr, --clip x,y,width,height, --full-page=false, --format jpeg, --quality, --base-url, and --resource-timeout-ms. Selectors capture the first matching element and are mutually exclusive with Clip. Without a selector, full-page output retains at least the viewport height (800×720 by default). DPR scales the output pixels. PNG supports transparency; JPEG composites onto white.

Deploy a shared service

set -x HTMLRENDER_TOKEN 'a-secret-you-manage'
./bin/t2i serve --listen 127.0.0.1:8999 \
    --runtime-dir /var/lib/htmlrender/runtime \
    --data-dir /var/lib/htmlrender/images

Place an HTTPS reverse proxy in front of the loopback listener, or expose it on a private network. Configure clients with that URL and token. An empty token enables unauthenticated operation for the existing local workflow.

Run the renderer as a dedicated user in an isolated container or VM, with only the required fonts and data mounted and with network access controlled for your deployment. Accepted HTML can run scripts in Chromium and load resources accessible to the rendering account. Give endpoint credentials to trusted callers. The AlonaBot configuration plugin shares credentials with enabled plugins.

HTTP route Behavior
POST /v1/render JSON request → image bytes plus X-Image-Width, X-Image-Height, X-Render-Engine, X-Render-Duration
POST /text2img/generate AstrBot-style input; image bytes, or a stored reference with json=true
GET /text2img/data/<id>.png Read a stored image; also supports .jpeg
GET /healthz Engine/runtime status; token omitted

With a configured token, rendering and stored-image reads require Authorization: Bearer <token>. The health endpoint remains public. AstrBot references retain {"code":0,"message":"success","data":{"id":"data/<id>.png"}}; images remain until explicitly cleaned. Errors retain their complete message. AstrBot caller example.

Queued requests respond to context cancellation. Chromium cancels the request's browser context. An in-progress Blitz native call completes before its slot is released and cancellation is reported. Closing a client releases its idle connections and leaves the service running.

Local resource sample

Measured on 2026-11-29, macOS arm64, release build, a 640×460 card at DPR 1 over loopback HTTP. Startup includes engine warmup; warm rendering is the wall-clock median of the next five requests. RSS is the idle service and all child processes after those renders.

Engine Startup (ms) First HTTP render (ms) Warm HTTP median (ms) Idle tree RSS (MiB)
blitz 1736.1 73.2 26.8 55.2
chromium 587.2 266.9 183.9 873.1

Verify the implementation

make test
make integration

make integration exercises local/HTTP × Blitz/Chromium with real resources and race detection, then runs real Core, configuration/profile plugins and the test Adapter, including an image exceeding 1 MiB. It requires Chrome. CI runs these checks on Linux amd64 and uploads the rendered PNGs. macOS arm64 is the local development platform.

Project code uses MIT. Vendored components and the sample font retain their original licenses; see third-party notices.

Documentation

Overview

Package t2i 提供共享生命周期的 HTML/Markdown 图片渲染接口。

Index

Constants

View Source
const (
	// Blitz 使用静态 HTML/CSS 的 CPU 渲染引擎。
	Blitz = "blitz"
	// Chromium 使用浏览器布局与 JavaScript。
	Chromium = "chromium"
)

Variables

View Source
var ErrClosed = errors.New("renderer is closed")

ErrClosed 标识 Renderer 已进入关闭过程。

Functions

func AssetsFromFS

func AssetsFromFS(files fs.FS) (map[string][]byte, error)

AssetsFromFS 读取可随请求传递的资源,路径相对于 files 的根目录。 可传入 embed.FS 的子目录;符号链接和特殊文件返回错误。

func MarkdownHTML

func MarkdownHTML(source string) (string, error)

MarkdownHTML 生成两种引擎共用的静态文档,允许调用方提供内嵌 HTML。

Types

type Backend

type Backend interface {
	Render(context.Context, Document) (image.Image, error)
	Close() error
}

Backend 返回整页、viewport 或 Selector 指定的图像;手动裁剪和编码由 Renderer 完成。

type Config

type Config struct {
	DefaultEngine string
	Engines       map[string]EngineConfig
}

Config 登记可用引擎;DefaultEngine 为空时使用 Blitz。

type Document

type Document struct {
	HTML    string
	BaseURL string
	Options Options
}

Document 已完成默认值和输入校验,供后端实现使用。

type EngineConfig

type EngineConfig struct {
	New         func() (Backend, error)
	Concurrency int
}

EngineConfig 配置后端构造函数及任务槽;Concurrency 为零时使用一个槽。

type EngineStatus

type EngineStatus struct {
	State   string `json:"state"`
	Workers int    `json:"workers"`
	Error   string `json:"error,omitempty"`
}

EngineStatus 提供引擎初始化状态及已创建的任务槽数。

type InputError

type InputError struct{ Message string }

InputError 表示调用方可以修正的输入错误。

func (*InputError) Error

func (e *InputError) Error() string

type Options

type Options struct {
	Width             int     `json:"viewport_width,omitempty"`
	Height            int     `json:"viewport_height,omitempty"`
	DPR               float64 `json:"device_scale_factor,omitempty"`
	FullPage          *bool   `json:"full_page,omitempty"`
	Clip              *Rect   `json:"clip,omitempty"`
	Selector          string  `json:"selector,omitempty"` // 第一个匹配元素的边界,与 Clip 互斥。
	Format            string  `json:"type,omitempty"`
	Quality           int     `json:"quality,omitempty"`
	OmitBackground    bool    `json:"omit_background,omitempty"`
	ResourceTimeoutMS int     `json:"resource_timeout_ms,omitempty"`
}

Options 的尺寸和 Clip 使用 CSS 像素;DPR 决定输出像素数。 FullPage 为 nil 时整页输出,false 时输出固定 viewport。

type Rect

type Rect struct {
	X      float64 `json:"x"`
	Y      float64 `json:"y"`
	Width  float64 `json:"width"`
	Height float64 `json:"height"`
}

Rect 以 CSS 像素指定文档中的矩形。

type Renderer

type Renderer struct {
	// contains filtered or unexported fields
}

Renderer 可被多个 goroutine 共享。Close 等待已进入的任务释放资源。

func New

func New(config Config) (*Renderer, error)

New 创建延迟初始化引擎的 Renderer,由宿主共享并在退出时关闭。

func (*Renderer) Close

func (r *Renderer) Close() error

Close 等待已进入的任务结束,关闭所有已初始化的后端。

func (*Renderer) Render

func (r *Renderer) Render(ctx context.Context, request Request) (result Result, returnErr error)

Render 排队取得任务槽,完成资源加载、渲染和编码后释放本次资源。

func (*Renderer) Status

func (r *Renderer) Status() map[string]EngineStatus

Status 返回独立的引擎状态快照。

func (*Renderer) Warmup

func (r *Renderer) Warmup(name string) error

Warmup 提前初始化指定引擎;name 为空时使用配置的默认引擎。

type Request

type Request struct {
	HTML     string            `json:"html,omitempty"`
	Markdown string            `json:"markdown,omitempty"`
	BaseURL  string            `json:"base_url,omitempty"`
	Assets   map[string][]byte `json:"assets,omitempty"` // 相对路径到文件内容;与 BaseURL 互斥。
	Engine   string            `json:"engine,omitempty"`
	Options  Options           `json:"options,omitempty"`
}

Request 选择 HTML 或 Markdown,并携带跨机可用的资源和渲染选项。

type Result

type Result struct {
	Data      []byte        `json:"-"`
	MediaType string        `json:"media_type"`
	Width     int           `json:"width"`
	Height    int           `json:"height"`
	Engine    string        `json:"engine"`
	Duration  time.Duration `json:"duration_ns"`
}

Result 持有调用方所有的图片字节、物理像素尺寸和实际使用的引擎。

Directories

Path Synopsis
alonabot module
backend
blitz
Package blitz 提供 CPU 渲染后端,使用修补过的 xo/blitz-c 桥接。
Package blitz 提供 CPU 渲染后端,使用修补过的 xo/blitz-c 桥接。
chromium
Package chromium 通过 CDP 管理共享浏览器及每次渲染的独立上下文。
Package chromium 通过 CDP 管理共享浏览器及每次渲染的独立上下文。
Package client 提供无需 CGO 的 T2I HTTP 客户端。
Package client 提供无需 CGO 的 T2I HTTP 客户端。
cmd
t2i command
demo 将同一组输入分别交给两个引擎,并输出可直接检查的图片。
demo 将同一组输入分别交给两个引擎,并输出可直接检查的图片。
fixtures/bundled
Package card 提供资料卡示例共用的 HTML、字体、样式与图片。
Package card 提供资料卡示例共用的 HTML、字体、样式与图片。
examples
embedded command
http command
Package httpapi 将共享 Renderer 暴露为通用与 AstrBot 风格的 HTTP 接口。
Package httpapi 将共享 Renderer 暴露为通用与 AstrBot 风格的 HTTP 接口。
internal
blitznative
Package blitznative 是 xo/blitz v0.5.0 C ABI 绑定的精简版本。
Package blitznative 是 xo/blitz v0.5.0 C ABI 绑定的精简版本。
Package local 管理同一用户、同一运行目录下的长期驻留服务。
Package local 管理同一用户、同一运行目录下的长期驻留服务。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL