Documentation
¶
Overview ¶
Package hcti provides a Go client for the HTML/CSS to Image API.
Index ¶
- func Ptr[T any](value T) *T
- type APIError
- type AspectRatio
- type BatchRequest
- type BatchResult
- type Client
- func (c *Client) CreateImage(ctx context.Context, request ImageRequest) (*Image, error)
- func (c *Client) CreateImageBatch(ctx context.Context, request BatchRequest) (*BatchResult, error)
- func (c *Client) CreateTemplate(ctx context.Context, request TemplateRequest) (*TemplateVersion, error)
- func (c *Client) CreateTemplateVersion(ctx context.Context, id string, request TemplateRequest) (*TemplateVersion, error)
- func (c *Client) DeleteImage(ctx context.Context, id string) error
- func (c *Client) DeleteImageBatch(ctx context.Context, ids []string) error
- func (c *Client) DeleteTemplate(ctx context.Context, id string) error
- func (c *Client) GenerateCreateAndRenderURL(request URLImageRequest, options ...RenderImageOptions) (string, error)
- func (c *Client) GenerateTemplatedImageURL(request TemplatedImageRequest, options ...RenderImageOptions) (string, error)
- func (c *Client) ImageURL(id string, options ...RenderImageOptions) (string, error)
- func (c *Client) ListTemplateVersions(ctx context.Context, id string, options TemplateListOptions) (*TemplatePage, error)
- func (c *Client) ListTemplates(ctx context.Context, options TemplateListOptions) (*TemplatePage, error)
- type ColorScheme
- type Crop
- type CropAxis
- type CropOrigin
- type CropSpan
- type CropUnit
- type CropValue
- type GoogleFonts
- type HTMLImageRequest
- type Image
- type ImageFormat
- type ImageOptions
- type ImageRequest
- type MediaType
- type Option
- type PDFLength
- type PDFMargins
- type PDFOptions
- type PDFUnit
- type RenderImageOptions
- type RenderOptions
- type ResponseError
- type Template
- type TemplateListOptions
- type TemplatePage
- type TemplateRequest
- type TemplateVersion
- type TemplatedImageRequest
- type URLImageRequest
- type ValidationError
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
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.
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 NewClientFromEnv ¶
NewClientFromEnv reads HCTI_API_ID and HCTI_API_KEY.
func (*Client) CreateImage ¶
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 ¶
DeleteImage deletes the image identified by id.
func (*Client) DeleteImageBatch ¶
DeleteImageBatch deletes the supplied image IDs in one request. An empty list succeeds without calling the API.
func (*Client) DeleteTemplate ¶
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 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.
type CropValue ¶
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 Option ¶
type Option func(*Client)
Option configures a client.
func WithBaseURL ¶
WithBaseURL overrides the API origin, for example for a local test server.
func WithHTTPClient ¶
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 ¶
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 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 ¶
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 ¶
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 ¶
ValidationError identifies a rejected request field.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
batch
command
|
|
|
html-image
command
|
|
|
image-url
command
|
|
|
pdf
command
|
|
|
signed-urls
command
|
|
|
templates
command
|
|
|
url-screenshot
command
|