hcti

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2026 License: MIT Imports: 19 Imported by: 0

README

HTML/CSS to Image — Go client

A Go client for the HTML/CSS to Image API, with support for Google Fonts, PDF options, templates, and signed rendering URLs.

Installation

Requires Go 1.21 or newer.

go get github.com/htmlcsstoimage/go-client

Import github.com/htmlcsstoimage/go-client and use the hcti package name, as shown below.

Create an image

package main

import (
    "context"
    "log"

    "github.com/htmlcsstoimage/go-client"
)

func main() {
    client, err := hcti.NewClientFromEnv() // HCTI_API_ID and HCTI_API_KEY
    if err != nil { log.Fatal(err) }

    image, err := client.CreateImage(context.Background(), hcti.HTMLImageRequest{
        HTML: "<h1>Hello from Go</h1>",
        CSS: hcti.Ptr("h1 { font-family: 'Open Sans'; }"),
        GoogleFonts: hcti.GoogleFonts{"Open Sans", "Roboto"},
        ImageOptions: hcti.ImageOptions{
            Format: hcti.PNG,
            RenderOptions: hcti.RenderOptions{
                TransparentBackground: hcti.Ptr(false),
            },
        },
    })
    if err != nil { log.Fatal(err) }
    log.Println(image.URL)
}

Alternatively, use hcti.NewClient(apiID, apiKey). Keep API credentials on the server.

Optional render fields use pointers: nil preserves API defaults; hcti.Ptr(false), hcti.Ptr(0), and hcti.Ptr("") send explicit values. For typed options, use hcti.Ptr(hcti.Dark) or hcti.Ptr(hcti.Print). Font names are trimmed, deduplicated, and serialized to the API's pipe-delimited format.

URL screenshots and PDF options

image, err := client.CreateImage(ctx, hcti.URLImageRequest{
    URL: "https://example.com",
    FullScreen: hcti.Ptr(true),
    ImageOptions: hcti.ImageOptions{
        Format: hcti.PDF,
        PDFOptions: &hcti.PDFOptions{
            PrintBackground: hcti.Ptr(true),
            PageWidth: &hcti.PDFLength{Value: 8.5, Unit: hcti.Inches},
            PageHeight: &hcti.PDFLength{Value: 11, Unit: hcti.Inches},
            Margins: &hcti.PDFMargins{
                Top: hcti.PDFLength{Value: 10, Unit: hcti.Millimeters},
                Bottom: hcti.PDFLength{Value: 10, Unit: hcti.Millimeters},
            },
        },
    },
})

PDF units support pixels, inches, centimeters, and millimeters. Zero-value lengths are zero pixels. Format selects the returned URL's extension; it does not restrict the stored image to that format.

Templates

version, err := client.CreateTemplate(ctx, hcti.TemplateRequest{
    Name: "Social card",
    HTML: "<h1>{{title}}</h1>",
    GoogleFonts: hcti.GoogleFonts{"Roboto"},
})
if err != nil { return err }

image, err := client.CreateImage(ctx, hcti.TemplatedImageRequest{
    TemplateID: version.TemplateID,
    TemplateVersion: hcti.Ptr(version.TemplateVersion),
    TemplateValues: map[string]any{"title": "Hello"},
})

Use CreateTemplateVersion to add a version to a stable template ID. ListTemplates returns the latest versions; ListTemplateVersions lists versions of one template. Pass page.Pagination.NextPageStart as TemplateListOptions.MaxVersion to fetch subsequent pages; stop when nil. DeleteTemplate removes the entire template, not an individual version.

Listing returns common fields plus Template.Raw, which retains the complete JSON for template-editor block variants not yet modeled by the client.

Batches and deletion

CreateImageBatch accepts a BatchRequest containing HTML/URL Variations and optional DefaultOptions. Omitted HTML/URL fields let variations inherit defaults. Templated image batches are not supported. Empty batches return locally without making an HTTP request. Deduplication settings are excluded from defaults and every variation without modifying the input requests.

A nil CSS pointer, map, or slice inherits the batch default. Use CSS: hcti.Ptr(""), Headers: map[string]string{}, AdditionalHeaderOrigins: []string{}, or GoogleFonts: hcti.GoogleFonts{} to explicitly clear that default:

batch, err := client.CreateImageBatch(ctx, hcti.BatchRequest{
    DefaultOptions: hcti.HTMLImageRequest{
        HTML: "<h1>Hello</h1>",
        CSS: hcti.Ptr("h1 { color: red; }"),
        GoogleFonts: hcti.GoogleFonts{"Roboto"},
    },
    Variations: []hcti.ImageRequest{
        hcti.HTMLImageRequest{}, // Inherits CSS and fonts.
        hcti.HTMLImageRequest{CSS: hcti.Ptr(""), GoogleFonts: hcti.GoogleFonts{}},
    },
})

Use DeleteImage or DeleteImageBatch to delete images. Successful deletion returns a nil error, including responses with no body.

Signed URLs

GenerateTemplatedImageURL and GenerateCreateAndRenderURL produce URLs locally, without API calls. They return (string, error) and accept the same templated/URL request types used for image creation. GenerateCreateAndRenderURL excludes PDF options and dedupe duration. Signed URLs authorize rendering; do not include confidential template values or request headers in URLs you share.

Image URLs, resizing, and cropping

ImageURL builds a URL for an existing image without calling the API. RenderImageOptions controls its format, dimensions, DPI, and crop. Cropping happens before resizing.

options := hcti.RenderImageOptions{
    Format: hcti.WebP,
    Width: hcti.Ptr(600),
    Crop: &hcti.Crop{
        Horizontal: &hcti.CropSpan{
            Size: &hcti.CropValue{Value: 100, Unit: hcti.CropPercent},
        },
        AspectRatio: &hcti.AspectRatio{Width: 16, Height: 9},
        AspectRatioAxis: hcti.CropWidth,
        ComputedOrigin: hcti.CropCenter,
    },
}
imageURL, err := client.ImageURL("existing-image-id", options)

Pass the same options as the optional second argument to GenerateTemplatedImageURL(request, options) or GenerateCreateAndRenderURL(request, options). A nonempty options format overrides the request format. Template variables that share transformation parameter names are preserved using the API's __ro_ override parameters.

For rectangles, supply Horizontal and/or Vertical spans without an aspect ratio. Spans support a start position, start/end boundaries, start/size, or a size anchored with CropStart, CropCenter, or CropEnd. Positions and sizes accept pixels or percentages. URL helpers validate dimensions, units, crop combinations, and origins before returning a URL.

HTTP behavior and errors

Every network operation takes a context.Context. The default timeout is 60 seconds. WithHTTPClient accepts custom transport/timeout settings; WithBaseURL selects another API origin. Redirects are disabled. The client never automatically retries requests, since retrying an ambiguous create can create another resource.

API requests send User-Agent: HCTIGo/<version>. The version is embedded from VERSION when the client is compiled.

Non-2xx responses return *hcti.APIError, inspectable with errors.As. It contains the HTTP status, API code/message, validation errors, and response headers (including rate-limit information). Error() intentionally omits response contents. Malformed successful responses return *hcti.ResponseError, including missing image IDs/URLs, invalid template versions, malformed arrays, and unexpected empty responses. Its message excludes response contents. Transport errors preserve their causes through Go error wrapping.

Runnable examples

See examples for complete programs covering HTML images, URL screenshots, PDFs, batches, template versioning, image transformations, and signed URLs.

Development

Releases

Update the root VERSION file (for example, from 0.1.0 to 0.1.1) and push the change to main. After the Test workflow passes, the Release workflow creates the matching v-prefixed Git tag and a GitHub release with generated notes, then requests Go module indexing. It releases the exact commit that passed tests.

Existing tags and releases are left unchanged. If a release run fails after creating its tag, rerun the failed workflow to finish the release and indexing. No package registry secrets are required; the workflow uses GitHub's built-in token.

VERSION accepts stable semantic versions without a v prefix. Use a new version for every release; published tags must not be moved. Major versions starting with v2 require the matching /v2 (or later) suffix in go.mod and imports.

Checks
go test ./...
go vet ./...

Tests use fake HTTP transports and require no API credentials or live service.

Encoding tests cover emoji sequences, multilingual text, malformed UTF-8, control bytes, long values, buffer growth, and signature verification. Direct query encoding preserves arbitrary Go string bytes through percent-escaping, matching net/url. Template values preserve encoding/json semantics, including replacing each malformed UTF-8 byte in strings with U+FFFD. Ordinary scalar values are encoded directly; structured values and custom marshalers use encoding/json.

Run the encoding and signing fuzz targets separately:

go test -run '^$' -fuzz '^FuzzAppendQueryEscaped$' -fuzztime=30s
go test -run '^$' -fuzz '^FuzzScreenshotSigning$' -fuzztime=30s
go test -run '^$' -fuzz '^FuzzTemplateSigning$' -fuzztime=30s
go test -run '^$' -fuzz '^FuzzTemplateFloatEncoding$' -fuzztime=30s

Run the URL generation benchmarks:

go test -run '^$' -bench BenchmarkGenerate -benchmem

Documentation

Overview

Package hcti provides a Go client for the HTML/CSS to Image API.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Ptr

func Ptr[T any](value T) *T

Ptr supplies an explicit optional value, including false, zero, or an empty string.

Types

type APIError

type APIError struct {
	StatusCode       int
	Code             string
	Message          string
	ValidationErrors []ValidationError
	Headers          http.Header
}

APIError is returned for non-2xx responses. Headers include rate-limit metadata. The response body is not included in Error(), to avoid accidentally logging secrets.

func (*APIError) Error

func (e *APIError) Error() string

type AspectRatio

type AspectRatio struct{ Width, Height int }

AspectRatio supplies positive width and height components, such as 16 and 9.

type BatchRequest

type BatchRequest struct {
	// Variations contains HTML or URL requests. Omitted fields inherit DefaultOptions.
	// An empty list returns an empty result without calling the API.
	Variations []ImageRequest `json:"variations"`
	// DefaultOptions supplies shared HTML or URL settings. Nil omits defaults.
	DefaultOptions ImageRequest `json:"default_options,omitempty"`
}

BatchRequest creates HTML or URL variations with optional shared defaults. Templated requests are not supported by the batch endpoint.

func (BatchRequest) MarshalJSON

func (r BatchRequest) MarshalJSON() ([]byte, error)

MarshalJSON excludes deduplication from batch defaults and variations without changing the caller's requests. The batch endpoint does not support dedupe.

type BatchResult

type BatchResult struct {
	// Images contains the created image identifiers and rendering URLs.
	Images []Image `json:"images"`
}

BatchResult contains the images created by a batch request.

type Client

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

Client is safe for concurrent use. Configure it before sharing it between goroutines. Requests are never automatically retried: a failed create may already have succeeded.

func NewClient

func NewClient(apiID, apiKey string, options ...Option) *Client

NewClient constructs a client using HTTP Basic authentication.

func NewClientFromEnv

func NewClientFromEnv(options ...Option) (*Client, error)

NewClientFromEnv reads HCTI_API_ID and HCTI_API_KEY.

func (*Client) CreateImage

func (c *Client) CreateImage(ctx context.Context, request ImageRequest) (*Image, error)

CreateImage creates an image definition and returns its render URL.

func (*Client) CreateImageBatch

func (c *Client) CreateImageBatch(ctx context.Context, request BatchRequest) (*BatchResult, error)

CreateImageBatch creates HTML or URL variations with optional shared defaults. Templated requests are rejected.

func (*Client) CreateTemplate

func (c *Client) CreateTemplate(ctx context.Context, request TemplateRequest) (*TemplateVersion, error)

CreateTemplate creates an HTML/CSS template and its initial version.

func (*Client) CreateTemplateVersion

func (c *Client) CreateTemplateVersion(ctx context.Context, id string, request TemplateRequest) (*TemplateVersion, error)

CreateTemplateVersion adds a version without replacing the template's stable ID.

func (*Client) DeleteImage

func (c *Client) DeleteImage(ctx context.Context, id string) error

DeleteImage deletes the image identified by id.

func (*Client) DeleteImageBatch

func (c *Client) DeleteImageBatch(ctx context.Context, ids []string) error

DeleteImageBatch deletes the supplied image IDs in one request. An empty list succeeds without calling the API.

func (*Client) DeleteTemplate

func (c *Client) DeleteTemplate(ctx context.Context, id string) error

DeleteTemplate removes the entire template and clears its contents. Previously rendered images may remain cached; new renders using the template fail.

func (*Client) GenerateCreateAndRenderURL

func (c *Client) GenerateCreateAndRenderURL(request URLImageRequest, options ...RenderImageOptions) (string, error)

GenerateCreateAndRenderURL signs a URL screenshot request without calling the API. PDF options and dedupe duration are not supported by this signed-URL helper. Optional render options crop or resize the result and override the request format.

func (*Client) GenerateTemplatedImageURL

func (c *Client) GenerateTemplatedImageURL(request TemplatedImageRequest, options ...RenderImageOptions) (string, error)

GenerateTemplatedImageURL signs template values without making an API request. Anyone with the resulting URL can render it. Do not put confidential values in URLs. Optional render options crop or resize the result and override the request format.

func (*Client) ImageURL

func (c *Client) ImageURL(id string, options ...RenderImageOptions) (string, error)

ImageURL builds a retrieval URL for an existing image without an API request. Supply at most one set of render options.

func (*Client) ListTemplateVersions

func (c *Client) ListTemplateVersions(ctx context.Context, id string, options TemplateListOptions) (*TemplatePage, error)

ListTemplateVersions lists versions of a single template, newest first.

func (*Client) ListTemplates

func (c *Client) ListTemplates(ctx context.Context, options TemplateListOptions) (*TemplatePage, error)

ListTemplates lists templates with their most recent versions.

type ColorScheme

type ColorScheme string

ColorScheme selects Chrome's preferred light or dark appearance.

const (
	Light ColorScheme = "light"
	Dark  ColorScheme = "dark"
)

type Crop

type Crop struct {
	Horizontal      *CropSpan
	Vertical        *CropSpan
	AspectRatio     *AspectRatio
	AspectRatioAxis CropAxis
	// ComputedOrigin anchors the calculated axis. Empty means CropStart.
	ComputedOrigin CropOrigin
}

Crop describes a rectangle or an aspect-ratio crop. A rectangle needs at least one span. An aspect crop needs exactly the span named by AspectRatioAxis; the other axis is calculated from AspectRatio and anchored by ComputedOrigin.

type CropAxis

type CropAxis string

CropAxis identifies the supplied axis in an aspect-ratio crop.

const (
	CropWidth  CropAxis = "width"
	CropHeight CropAxis = "height"
)

type CropOrigin

type CropOrigin string

CropOrigin anchors a size-only span or the calculated axis of an aspect crop. The zero value is equivalent to CropStart.

const (
	CropStart  CropOrigin = "start"
	CropCenter CropOrigin = "center"
	CropEnd    CropOrigin = "end"
)

type CropSpan

type CropSpan struct {
	Start *CropValue
	End   *CropValue
	Size  *CropValue
	// Origin applies only to Size without Start. Empty means CropStart.
	Origin CropOrigin
}

CropSpan describes one axis. Set Start alone to crop through the remaining image; Start and End for boundaries; Start and Size for a fixed size; or Size and Origin to anchor a size. End and Size cannot both be set.

type CropUnit

type CropUnit string

CropUnit measures a crop boundary or size in pixels or percent of the image.

const (
	CropPixels  CropUnit = "px"
	CropPercent CropUnit = "%"
)

type CropValue

type CropValue struct {
	Value int
	Unit  CropUnit
}

CropValue is a crop position or size. Pixel positions may be zero; pixel sizes must be positive. Percentages must be from 1 to 100. URL helpers validate values.

type GoogleFonts

type GoogleFonts []string

GoogleFonts is a list of font families, serialized in the API's pipe-delimited format.

func (GoogleFonts) MarshalJSON

func (fonts GoogleFonts) MarshalJSON() ([]byte, error)

func (*GoogleFonts) UnmarshalJSON

func (fonts *GoogleFonts) UnmarshalJSON(data []byte) error

type HTMLImageRequest

type HTMLImageRequest struct {
	ImageOptions
	// HTML is the raw HTML markup to render. Required for single-image creation;
	// an empty value is omitted so batch variations can inherit default HTML.
	HTML string `json:"html,omitempty"`
	// CSS supplies styles for the HTML or styles to inject into a URL screenshot.
	// Nil omits the field; Ptr("") sends an explicit empty value.
	CSS *string `json:"css,omitempty"`
	// GoogleFonts lists font families to load, such as GoogleFonts{"Open Sans", "Roboto"}.
	// Use font-family in your CSS to select them. Names are trimmed, deduplicated,
	// and serialized to the API's pipe-delimited string. Nil omits the field; an empty list sends an empty string.
	GoogleFonts GoogleFonts `json:"google_fonts,omitempty"`
}

HTMLImageRequest creates an image from HTML markup and optional CSS.

func (HTMLImageRequest) MarshalJSON

func (r HTMLImageRequest) MarshalJSON() ([]byte, error)

MarshalJSON preserves empty collections, which clear inherited batch defaults.

type Image

type Image struct {
	// ID is the image identifier used for deletion and rendering.
	ID string `json:"id"`
	// URL is the render URL returned by the API.
	URL string `json:"url"`
}

Image identifies a created image and its rendering URL.

type ImageFormat

type ImageFormat string

ImageFormat selects PNG, JPG, WebP, or PDF rendering URLs.

const (
	PNG  ImageFormat = "png"
	JPG  ImageFormat = "jpg"
	WebP ImageFormat = "webp"
	PDF  ImageFormat = "pdf"
)

type ImageOptions

type ImageOptions struct {
	RenderOptions
	// Format selects the extension of the initially returned image URL.
	// It does not restrict the stored image to that format.
	// An empty value uses the API's default image URL.
	Format ImageFormat `json:"format,omitempty"`
	// Selector is a CSS selector identifying the element to capture.
	// The image is cropped to the selected element's dimensions.
	// Nil omits the selector; Ptr("") clears an inherited batch selector.
	Selector *string `json:"selector,omitempty"`
	// MaxRenderOnce requests that the image be rendered and saved only once.
	// Nil uses the API default.
	MaxRenderOnce *bool `json:"max_render_once,omitempty"`
	// DedupeDurationSeconds reuses an identical recently created image without
	// consuming another image credit. Ptr(0) disables deduplication.
	// HTML/CSS defaults vary by plan; URL requests default to 0.
	// Applies only to standard single-image POST creation, not batches or signed URLs.
	// See https://docs.htmlcsstoimage.com/parameters/dedupe_duration_s/.
	DedupeDurationSeconds *int `json:"dedupe_duration_s,omitempty"`
	// PDFOptions configures PDF output, including page dimensions and margins.
	// Nil omits PDF options. Select PDF as the Format to receive a PDF URL.
	PDFOptions *PDFOptions `json:"pdf_options,omitempty"`
}

ImageOptions configures HTML/CSS and URL image creation.

type ImageRequest

type ImageRequest interface {
	// contains filtered or unexported methods
}

ImageRequest accepts one of HTMLImageRequest, URLImageRequest, or TemplatedImageRequest.

type MediaType

type MediaType string

MediaType selects which CSS media rules Chrome uses.

const (
	Screen MediaType = "screen"
	Print  MediaType = "print"
)

type Option

type Option func(*Client)

Option configures a client.

func WithBaseURL

func WithBaseURL(baseURL string) Option

WithBaseURL overrides the API origin, for example for a local test server.

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient supplies transport and timeout configuration. The client is copied; redirects are disabled to avoid replaying credentials or writes at another endpoint.

type PDFLength

type PDFLength struct {
	// Value is the dimension magnitude. It must be finite and nonnegative.
	Value float64
	// Unit selects Pixels, Inches, Centimeters, or Millimeters.
	// An empty unit means Pixels.
	Unit PDFUnit
}

PDFLength expresses a PDF dimension. The zero value means zero pixels.

func (PDFLength) MarshalJSON

func (length PDFLength) MarshalJSON() ([]byte, error)

type PDFMargins

type PDFMargins struct {
	// Top sets the top margin. The zero value is zero pixels.
	Top PDFLength
	// Right sets the right margin. The zero value is zero pixels.
	Right PDFLength
	// Bottom sets the bottom margin. The zero value is zero pixels.
	Bottom PDFLength
	// Left sets the left margin. The zero value is zero pixels.
	Left PDFLength
}

PDFMargins serializes in CSS order: top, right, bottom, left.

func (PDFMargins) MarshalJSON

func (m PDFMargins) MarshalJSON() ([]byte, error)

type PDFOptions

type PDFOptions struct {
	// PrintBackground includes background graphics in PDF output.
	// Nil uses the API default; Ptr(false) explicitly excludes them.
	PrintBackground *bool `json:"print_background,omitempty"`
	// Scale sets the PDF output scale factor. Nil uses the API default.
	Scale *float64 `json:"scale,omitempty"`
	// Margins sets the top, right, bottom, and left PDF margins.
	// Nil uses the API defaults; a non-nil zero value sends four zero-pixel margins.
	Margins *PDFMargins `json:"margins,omitempty"`
	// PageHeight sets the PDF page height with explicit units.
	// Nil uses the API default.
	PageHeight *PDFLength `json:"page_height,omitempty"`
	// PageWidth sets the PDF page width with explicit units.
	// Nil uses the API default.
	PageWidth *PDFLength `json:"page_width,omitempty"`
}

PDFOptions controls PDF page layout and printing.

type PDFUnit

type PDFUnit string

PDFUnit is a unit accepted for PDF dimensions and margins.

const (
	Pixels      PDFUnit = "px"
	Inches      PDFUnit = "in"
	Centimeters PDFUnit = "cm"
	Millimeters PDFUnit = "mm"
)

type RenderImageOptions

type RenderImageOptions struct {
	// Format selects PNG, JPG, WebP, or PDF. Empty preserves the request's format.
	Format ImageFormat
	// DPI sets output density, strictly greater than 30 and less than 600.
	DPI *int
	// Height resizes the result to 1–5000 pixels. Nil preserves its height or aspect ratio.
	Height *int
	// Width resizes the result to 1–5000 pixels. Nil preserves its width or aspect ratio.
	Width *int
	// Crop selects a rectangle or an aspect-ratio crop before resizing.
	Crop *Crop
}

RenderImageOptions transforms an image when its URL is fetched. Cropping is applied before resizing. These settings do not change the stored image.

type RenderOptions

type RenderOptions struct {
	// DeviceScale controls the screenshot pixel ratio, from 0.1 to 3.
	// HTML and template renders default to 2; URL renders default to 1.
	// Nil uses the API default.
	DeviceScale *float64 `json:"device_scale,omitempty"`
	// ViewportHeight sets Chrome's viewport height in pixels, from 1 to 6000.
	// Supply ViewportWidth as well. Setting viewport dimensions disables automatic cropping.
	ViewportHeight *int `json:"viewport_height,omitempty"`
	// ViewportWidth sets Chrome's viewport width in pixels, from 1 to 6000.
	// Supply ViewportHeight as well. Nil leaves the API default unchanged.
	ViewportWidth *int `json:"viewport_width,omitempty"`
	// MaxWaitMS limits how long to wait before taking the screenshot when
	// the page continues loading irrelevant content. Values are milliseconds,
	// from 500 to 10000, and are also subject to the account plan limit.
	MaxWaitMS *int `json:"max_wait_ms,omitempty"`
	// MSDelay adds a delay before taking the screenshot so JavaScript can execute.
	// Values are milliseconds, from 0 to 10000. The API default is 0.
	MSDelay *int `json:"ms_delay,omitempty"`
	// RenderWhenReady waits for JavaScript to call ScreenshotReady().
	// The image fails if the readiness signal is never sent. Nil uses the API default.
	RenderWhenReady *bool `json:"render_when_ready,omitempty"`
	// DisableTwemoji disables the Twemoji fallback and renders emoji with native fonts.
	// Nil uses the API default; Ptr(false) explicitly enables the fallback.
	DisableTwemoji *bool `json:"disable_twemoji,omitempty"`
	// ColorScheme sets Chrome's preferred color scheme to Light or Dark.
	// Nil leaves the API default unchanged; use Ptr(Dark) or Ptr(Light).
	ColorScheme *ColorScheme `json:"color_scheme,omitempty"`
	// Timezone sets Chrome's timezone using an IANA name, such as America/New_York.
	// Nil leaves the API default unchanged; Ptr("") sends an explicit empty value.
	Timezone *string `json:"timezone,omitempty"`
	// ViewportMobile enables mobile viewport behavior, including the page's
	// viewport meta tag. Nil uses the API default.
	ViewportMobile *bool `json:"viewport_mobile,omitempty"`
	// ViewportTouch enables touch interactions in the emulated viewport.
	// Nil uses the API default.
	ViewportTouch *bool `json:"viewport_touch,omitempty"`
	// ViewportLandscape sets the emulated viewport to landscape orientation.
	// Nil uses the API default.
	ViewportLandscape *bool `json:"viewport_landscape,omitempty"`
	// MediaType selects Screen or Print CSS media rules.
	// Nil leaves the API default unchanged; use Ptr(Screen) or Ptr(Print).
	MediaType *MediaType `json:"media_type,omitempty"`
	// ProxyID selects an organization proxy for rendering.
	// Nil omits the proxy selection; Ptr("") sends an explicit empty value.
	// See https://docs.htmlcsstoimage.com/parameters/proxy_id/.
	ProxyID *string `json:"proxy_id,omitempty"`
	// StorageDestinationID selects an organization storage destination for rendered files.
	// Nil omits the destination selection; Ptr("") sends an explicit empty value.
	// See https://docs.htmlcsstoimage.com/parameters/storage_destination_id/.
	StorageDestinationID *string `json:"storage_destination_id,omitempty"`
	// JumboMaxWidth sets the maximum width in pixels for jumbo rendering.
	// Supply JumboMaxHeight as well. Both must be positive and at most 80000;
	// at least one must exceed 8000, and their product must not exceed 400000000.
	// Jumbo rendering consumes additional renders.
	JumboMaxWidth *int `json:"jumbo_max_width,omitempty"`
	// JumboMaxHeight sets the maximum height in pixels for jumbo rendering.
	// Supply JumboMaxWidth as well; its documentation describes the size limits.
	// Jumbo rendering consumes additional renders.
	JumboMaxHeight *int `json:"jumbo_max_height,omitempty"`
	// TransparentBackground requests a transparent image background.
	// Nil uses the API default; Ptr(false) explicitly disables transparency.
	TransparentBackground *bool `json:"transparent_background,omitempty"`
}

RenderOptions are shared by HTML, URL, and HTML template requests. Nil pointers leave the API default intact; Ptr(false) and Ptr(0) send explicit values.

type ResponseError

type ResponseError struct {
	StatusCode int
	Problem    string
}

ResponseError indicates an invalid successful API response. The response body is deliberately excluded from the error so it is safe to log.

func (*ResponseError) Error

func (e *ResponseError) Error() string

type Template

type Template struct {
	RenderOptions
	// ID is the stable template identifier.
	ID string `json:"id"`
	// Version identifies this particular version of the template.
	Version int64 `json:"version"`
	// TemplateType identifies the template variant, such as html_css or blocks.
	TemplateType string `json:"template_type"`
	// Name is the template's display name.
	Name string `json:"name"`
	// Description explains the template's purpose.
	Description string `json:"description"`
	// HTML contains the markup for an HTML/CSS template.
	HTML string `json:"html"`
	// CSS contains the styles for an HTML/CSS template.
	CSS string `json:"css"`
	// GoogleFonts contains decoded font family names.
	GoogleFonts GoogleFonts `json:"google_fonts"`
	// CreatedAt is the creation timestamp returned by the API.
	CreatedAt time.Time `json:"created_at"`
	// UpdatedAt is the last-update timestamp returned by the API.
	UpdatedAt time.Time `json:"updated_at"`
	// RenderCount is the render count returned by the API.
	RenderCount int64 `json:"render_count"`
	// Raw preserves the complete JSON response, including fields specific to
	// template-editor block variants that are not yet represented by this type.
	Raw json.RawMessage `json:"-"`
}

Template contains common template metadata and HTML/CSS settings. Raw retains the complete response, including editor block fields not yet modeled.

func (*Template) UnmarshalJSON

func (t *Template) UnmarshalJSON(data []byte) error

type TemplateListOptions

type TemplateListOptions struct {
	// Count limits the number of results, from 1 to 100.
	// Zero omits the parameter and uses the API default of 10.
	Count int
	// MaxVersion supplies the version cursor from the previous page's
	// Pagination.NextPageStart. Nil starts from the newest results.
	MaxVersion *int64
}

TemplateListOptions uses the template API's numeric version cursor.

type TemplatePage

type TemplatePage struct {
	// Data contains the templates or template versions on this page.
	Data []Template `json:"data"`
	// Pagination contains the cursor for the next page.
	Pagination struct {
		// NextPageStart is passed as TemplateListOptions.MaxVersion.
		// Nil indicates that no further page is available.
		NextPageStart *int64 `json:"next_page_start"`
	} `json:"pagination"`
}

TemplatePage is one page of templates or template versions.

type TemplateRequest

type TemplateRequest struct {
	RenderOptions
	// HTML contains Handlebars markup. It must be non-empty, include at least
	// one placeholder, and compile as valid Handlebars.
	HTML string `json:"html"`
	// CSS styles the rendered template. Handlebars expressions are not supported
	// here; put dynamic CSS inside HTML instead.
	CSS *string `json:"css,omitempty"`
	// GoogleFonts lists font families to load. Use font-family in CSS to select them.
	// The SDK serializes the list to the API's pipe-delimited format.
	GoogleFonts GoogleFonts `json:"google_fonts,omitempty"`
	// Name identifies the template in your account. Maximum length: 64 characters.
	Name string `json:"name,omitempty"`
	// Description explains the template's purpose. Maximum length: 1024 characters.
	Description string `json:"description,omitempty"`
}

TemplateRequest creates an HTML/CSS template or a new version of one.

type TemplateVersion

type TemplateVersion struct {
	// TemplateID is the stable identifier shared by versions of this template.
	TemplateID string `json:"template_id"`
	// TemplateVersion is the newly created version number. Use it to pin rendering.
	TemplateVersion int64 `json:"template_version"`
}

TemplateVersion is the result of creating a template or adding a version.

type TemplatedImageRequest

type TemplatedImageRequest struct {
	// TemplateID identifies the template used to render the image. Required.
	TemplateID string `json:"template_id"`
	// TemplateVersion pins a specific template version.
	// Nil uses the template's latest version.
	TemplateVersion *int64 `json:"template_version,omitempty"`
	// TemplateValues maps template variable names to JSON-serializable values.
	// Values can include strings, numbers, booleans, arrays, and objects.
	TemplateValues map[string]any `json:"template_values"`
	// Format selects the extension of the initially returned image URL.
	// It does not restrict the stored image to that format.
	// An empty value uses the API's default image URL.
	Format ImageFormat `json:"format,omitempty"`
}

TemplatedImageRequest renders a saved template using variable values.

type URLImageRequest

type URLImageRequest struct {
	ImageOptions
	// URL is the webpage to capture. Required for single-image creation;
	// an empty value is omitted so batch variations can inherit the default URL.
	URL string `json:"url,omitempty"`
	// CSS supplies styles for the HTML or styles to inject into a URL screenshot.
	// Nil omits the field; Ptr("") sends an explicit empty value.
	CSS *string `json:"css,omitempty"`
	// Headers supplies custom HTTP headers for top-level requests to the URL's
	// origin and AdditionalHeaderOrigins. Subrequests require IncludeHeadersOnSubrequests.
	// Nil inherits batch defaults; an empty map clears inherited headers.
	// See https://docs.htmlcsstoimage.com/parameters/headers/.
	Headers map[string]string `json:"headers,omitempty"`
	// AdditionalHeaderOrigins lists extra exact HTTP or HTTPS origins allowed
	// to receive Headers. Each origin includes its scheme, host, and optional port.
	// Nil inherits batch defaults; an empty slice clears inherited origins.
	AdditionalHeaderOrigins []string `json:"additional_header_origins,omitempty"`
	// IncludeHeadersOnSubrequests also sends Headers on subrequests to allowed origins.
	// Nil uses the API default.
	IncludeHeadersOnSubrequests *bool `json:"include_headers_on_subrequests,omitempty"`
	// IdentifyAsHCTI adds X-HCTI-SCREENSHOT: 1 to the top-level page request.
	// Nil uses the API default.
	IdentifyAsHCTI *bool `json:"identify_as_hcti,omitempty"`
	// FullScreen captures the webpage's full height instead of only its viewport.
	// Nil uses the API default.
	FullScreen *bool `json:"full_screen,omitempty"`
	// BlockConsentBanners attempts to block cookie and consent banners.
	// Nil uses the API default.
	BlockConsentBanners *bool `json:"block_consent_banners,omitempty"`
}

URLImageRequest creates a screenshot of a webpage.

func (URLImageRequest) MarshalJSON

func (r URLImageRequest) MarshalJSON() ([]byte, error)

MarshalJSON preserves empty collections, which clear inherited batch defaults.

type ValidationError

type ValidationError struct {
	Path    string `json:"path"`
	Message string `json:"message"`
}

ValidationError identifies a rejected request field.

Directories

Path Synopsis
examples
batch command
html-image command
image-url command
pdf command
signed-urls command
templates command
url-screenshot command

Jump to

Keyboard shortcuts

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