imagebdf

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: MIT Imports: 31 Imported by: 0

Documentation

Overview

Package imagebdf draws BDF documents into images without a browser: the pages of fixed and flow views, stretches of scroll views and regions of sheets, for thumbnails and other server-side previews, and objects that are in no document (Object).

It runs the same instructions as the viewer's Canvas 2D renderer (docs/spec.md §7) with a software rasterizer: anti-aliased paths with nonzero and even-odd fills, strokes with joins, caps and dashes, clips, gradients and patterns, images (PNG, JPEG, GIF, BMP, WebP), text in the embedded fonts (WOFF2, TrueType, OpenType) and in the fonts of the system for fonts referred to by name, groups with their alpha and blend mode, soft masks and shadows. The result is close to what a browser draws but not identical: text is not hinted, shaped (no kerning, ligatures or Arabic joining) or laid out by a full bidirectional algorithm; AVIF images and FILTER are not drawn. SVG images are drawn by a renderer of the SVG that previews meet, from the tree image/svg reads. Warnings list what was left out.

A document decides what it asks of a renderer, so the drawing has limits: of the objects drawn again (maxReusedInstructions), of the groups, soft masks, states and clips that are open at a time (maxLayers, maxStates, maxLive), of the outline of a stroke (strokePoints, strokeDashes), of the blur of a shadow (maxShadowBlur), of the pictures kept decoded (maxPicturePixels), of SVG images (the limits of reading of image/svg, svgBudget, svgLayers and the constants beside them) and of the gridlines of a sheet (maxGridLines). What passes a limit is left out with a warning, and the rest is drawn. A panic of a drawing is the error of Page, Region and Object.

Index

Constants

View Source
const (
	// DefaultImageCacheBytes is the completed-image cache budget per Renderer.
	DefaultImageCacheBytes = 64 << 20
	// DefaultTextCacheBytes is the text-run coverage cache budget per Renderer.
	DefaultTextCacheBytes = 32 << 20
)
View Source
const DefaultBandRows = 128

DefaultBandRows is the rows of a band of a page drawn in bands (Options.BandRows): an A4 page at 600 dpi (4960 pixels wide) takes a canvas of 10 MiB a band of 128 rows, and is drawn in 55 bands as fast as in fewer.

View Source
const DefaultCanvasCacheBytes = 64 << 20

DefaultCanvasCacheBytes bounds the memory of the canvases a renderer keeps for its next drawings (Options.CanvasCacheBytes): a page takes 16 bytes a pixel, and one made for each drawing costs the system as much again in giving the memory back and faulting it in.

View Source
const MaxBandCanvases = 192 << 20

MaxBandCanvases bounds the memory of the canvases of the bands of a page drawn at a time (Options.BandWorkers): fewer bands are drawn at a time when they are large. An A4 page at 600 dpi takes 10 MiB a band of DefaultBandRows.

View Source
const MaxPixels = 64 << 20

MaxPixels is the largest image Page and Region draw (a canvas takes 16 bytes a pixel while it is drawn).

View Source
const MaxPlacePixels = 256 << 20

MaxPlacePixels is the largest image PlaceRows draws. It is larger than MaxPixels because only a band of it is drawn at a time: an A0 sheet at 300 dpi, or A3 at 600, fits.

Variables

View Source
var ErrNeedsDocument = errors.New("imagebdf: the object refers to other parts of a document")

ErrNeedsDocument is returned by Object for an object that refers to other parts (an embedded font, an image, a path collection or another object): add it to a document with them and draw a page.

View Source
var ErrNoPage = errors.New("imagebdf: no such page")

ErrNoPage is returned for a page a view does not have.

View Source
var ErrTooLarge = errors.New("imagebdf: the image would be too large")

ErrTooLarge is returned for an image of more than MaxPixels pixels.

Functions

func Object

func Object(o *bdf.Object, scale float64, opts *Options) (img *image.RGBA, err error)

Object draws an object that needs no other part, such as a formula laid out as paths, at scale device pixels per unit. The image holds the bounding box of the object grown to whole pixels, and its bounds are in device pixels from the origin of the object: the pixel at (0, 0) is where the origin is drawn, wherever the bounding box lies around it. The background is opts.Background, and transparent without one.

func PagePixels added in v0.1.8

func PagePixels(v *bdf.View, page int, scale float64) (w, h int, err error)

PagePixels returns the size of the image Page draws of a page of a view at scale device pixels per unit, with the errors of Page: the units of the page rounded up to pixels, a pixel at least.

func SVGImage added in v0.1.7

func SVGImage(data []byte, scale func(w, h float64) float64, opts *Options) (img *image.NRGBA, w, h float64, warnings []string, err error)

SVGImage draws an SVG image by itself, for the writers of formats that hold no SVG: its raster (not premultiplied by its alpha), and its natural size in units (CSS pixels). scale gives the pixels to draw a unit with for a natural size; the scale is bounded as that of the SVG images of a page is.

func SheetSize

func SheetSize(v *bdf.View) (w, h float64)

SheetSize returns the size of a sheet in units, from its rows and columns.

Types

type AntialiasMode added in v0.1.8

type AntialiasMode uint8

AntialiasMode selects how geometric edges are rasterized. It does not change source opacity, image interpolation, shadows or soft masks.

const (
	// AntialiasDefault preserves the existing antialiased rendering at any DPI.
	AntialiasDefault AntialiasMode = iota
	// AntialiasOn explicitly enables antialiased geometric edges.
	AntialiasOn
	// AntialiasOff samples geometric edges at pixel centers, without coverage
	// antialiasing. Subpixel-width strokes still use the existing width-to-alpha
	// compensation, so their pixels need not be opaque.
	AntialiasOff
)

type Barcode added in v0.2.0

type Barcode struct {
	// Mark is what the mark says: the symbol, and its box on the page.
	Mark *barcode.Mark
	// X, Y, W and H are the box of the mark on the image, in pixels: its
	// top left corner as the symbol is upright, and its size along the
	// symbol's bars (W) and up them (H), before it is turned.
	X, Y, W, H float64
	// Turns is the quarter turns clockwise of the symbol on the image:
	// 1 has the top of the symbol on the right, its box going down from
	// (X, Y) and to the left. The box's other corners are where the turns
	// take (X+W, Y) and (X, Y+H).
	Turns int
}

Barcode is a QR code or a barcode that a BARCODE mark of a page tells (docs/spec.md §7.8), where the image has it: see Options.Barcode.

type Mono added in v0.1.8

type Mono uint8

Mono selects a monochrome image in place of the RGBA one (PageMono, RegionMono, PagesMono): for printing in black, where the colours of the page are not wanted and the image is a quarter the size or less.

const (
	// Gray draws 8 bits of luminance a pixel, as an *image.Gray: the
	// luminance (with the weights of Rec. 601, as image/color converts to
	// gray) of each pixel over white, rounded to the nearest.
	Gray Mono = iota + 1
	// Bilevel draws black and white, as an *image.Paletted of those two
	// colours (black first), which image/png writes at 1 bit a pixel:
	// black where the gray value is below 128. With AntialiasOff the
	// edges are those of the drawing; with antialiasing, the coverage of
	// the edges is cut at the half, not dithered.
	Bilevel
)

type Options

type Options struct {
	// FontFS holds fonts searched before FontDirs, for the text of fonts
	// referred to by name (HTML, Markdown and EPUB documents, and others
	// converted with system fonts) and for characters an embedded font
	// lacks.
	FontFS fs.FS
	// FontDirs are searched for fonts before the system font directories.
	FontDirs []string
	// NoSystemFonts restricts font lookup to FontFS and FontDirs.
	NoSystemFonts bool
	// Background fills the page behind its content (default white). Use
	// color.Transparent for a transparent page.
	Background color.Color
	// Antialias controls path, text and geometric clip edges. The zero value
	// retains antialiasing, independent of DPI. Unknown values also retain it
	// and add a renderer warning.
	Antialias AntialiasMode
	// ImageCacheBytes bounds retained completed Page, Region and Renderer.Object
	// images. Zero uses DefaultImageCacheBytes; a negative value disables it.
	ImageCacheBytes int
	// TextCacheBytes bounds retained whole text-run coverage masks. Zero uses
	// DefaultTextCacheBytes; a negative value disables it. Neither cache changes
	// rendering quality. Call Invalidate after changing document parts or FontFS.
	TextCacheBytes int
	// CanvasCacheBytes bounds the working canvases kept from one drawing
	// for the next (16 bytes a pixel of the image drawn, and of each open
	// group), and as much again the coverage of large masks kept from one
	// fill for the next. Zero uses DefaultCanvasCacheBytes; a negative
	// value keeps none. A page at 600 dpi takes a canvas of hundreds of
	// megabytes, which pages drawn one after the other with Page reuse
	// within this budget; Pages keeps one canvas a worker for the length
	// of a batch whatever the budget.
	CanvasCacheBytes int
	// BandRows is the rows of a band of a page drawn in bands (PageRows,
	// PagesRows): the canvas of a band takes 16 bytes a pixel of it, and
	// the instructions of the page are run once a band. Zero uses
	// DefaultBandRows.
	BandRows int
	// BandWorkers is how many bands of a page are drawn at a time
	// (PageRows, PagesRows), each by a worker with a canvas of its own:
	// zero uses the threads of the machine, up to eight, within
	// MaxBandCanvases of canvases; one draws the bands one after the
	// other, with the memory of one.
	BandWorkers int
	// Barcode is called with each QR code and barcode that a BARCODE mark
	// tells (docs/spec.md §7.8) whose box the transform keeps upright or
	// turns by quarters: when it returns true, the drawing of the symbol
	// is left out (a printer of labels prints it with its own commands).
	// It is called again for each band of a page drawn in bands that the
	// symbol may show in, from the workers that draw them at once, and not
	// for an image the image cache had.
	Barcode func(Barcode) bool
	// AlignBarcodes draws those symbols again with their modules on whole
	// pixels, as many pixels wide as fit in their box (and the symbol in
	// its middle): at the few dots an inch of a label or a receipt, bars
	// a fraction of a dot wider or narrower are what a reader cannot
	// read. A symbol whose modules would be narrower than a pixel is drawn
	// as it is.
	AlignBarcodes bool
	// DitherImages draws images in black and white dots (an ordered
	// dither), for an image of black and white (Bilevel): photographs and
	// logos keep their shades, where text and lines, cut at the half, keep
	// their edges.
	DitherImages bool
}

Options configures a Renderer.

type Place added in v0.2.0

type Place struct {
	W, H             int
	Scale            float64
	Turns            int
	X, Y             float64
	MirrorX, MirrorY bool
}

Place says where a page goes on an image, to print it on paper (see PlaceRows): the image is W × H pixels; the page is drawn at Scale pixels per unit, turned clockwise by Turns quarter turns (0 to 3), and the box it then takes has its top-left corner at (X, Y) pixels; then the image is mirrored left to right (MirrorX) or top to bottom (MirrorY), as the back of a sheet is for some printers that turn the sheet over (pwg-raster-document-sheet-back). The rest of the image is the background, as the page's is.

type Renderer

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

Renderer draws the views of a document. It keeps what it decodes (objects, paths, images, fonts) for the next drawing, the images up to maxPicturePixels, past which those of the drawings before make room; it is not safe for concurrent use.

func New

func New(doc *bdf.Document, opts *Options) *Renderer

New returns a renderer of a document.

func (*Renderer) Invalidate added in v0.1.8

func (r *Renderer) Invalidate()

Invalidate releases all cached images, text masks and decoded resources, clears warnings, and retains the renderer's options. Call it after changing document part bytes or FontFS. FontDirs and system fonts retain fontdb's existing process-wide scan/load cache; use FontFS for replaceable fonts. Document/view mutation must never race with rendering. Page and view layout are also included in completed-image keys, so changes to those layouts cannot return old pixels.

func (*Renderer) Object added in v0.1.8

func (r *Renderer) Object(hash bdf.Hash, scale float64) (img *image.RGBA, err error)

Object draws a document object, including its dependencies, at scale pixels per unit. Its bounds use the object's origin as the package-level Object helper does. A nil background is transparent. Reusing a Renderer also reuses the completed-image and text-mask caches.

func (*Renderer) Page

func (r *Renderer) Page(v *bdf.View, page int, scale float64) (*image.RGBA, error)

Page draws a whole page of a fixed or flow view (or a strip of a scroll view) at scale device pixels per unit.

func (*Renderer) PageDPI

func (r *Renderer) PageDPI(v *bdf.View, page int, dpi float64) (*image.RGBA, error)

PageDPI draws a whole page at dpi pixels per inch. BDF page units are points (1/72 inch), so 72 dpi draws one pixel per page unit.

func (*Renderer) PageMono added in v0.1.8

func (r *Renderer) PageMono(v *bdf.View, page int, scale float64, mono Mono) (image.Image, error)

PageMono is Page in a monochrome image: an *image.Gray for Gray, an *image.Paletted of black and white for Bilevel. It draws the page as Page does and converts it; the renderer's antialiasing mode decides the edges. An unknown mono is an error.

func (*Renderer) PageRows added in v0.1.8

func (r *Renderer) PageRows(v *bdf.View, page int, scale float64, mono Mono, yield func(y0 int, rows image.Image) error) (err error)

PageRows draws a whole page of a fixed or flow view (or a strip of a scroll view) at scale device pixels per unit in bands of rows, from the top, and calls yield for each: with the first row of the band and the image of its rows, whose bounds are those rows of the page (Min.Y is y0). The image is an *image.RGBA for a mono of 0, and the image of the Mono otherwise (see PageMono); it is the renderer's, reused for a band after it, so yield copies what it keeps. The pixels are those of Page and PageMono.

A band takes a canvas of its rows (Options.BandRows of them, and the rows above and below that the shadows of the page reach from) instead of the whole page, and the image of its rows: an A4 page at 600 dpi takes tens of megabytes instead of hundreds. The instructions of the page are run once a band, skipping from the second band the draws that lie outside it. The bands after the first are drawn in parallel, as many at a time as the renderer has threads (up to eight, those of the machine) and within MaxBandCanvases of canvases, each by a worker of its own with the memory of the renderer's options; yield is called in order, on the calling goroutine. An error of yield ends the drawing with that error once the bands begun are drawn. The image is not kept in the completed-image cache.

func (*Renderer) PageSize

func (r *Renderer) PageSize(v *bdf.View, page, w, h int) (img *image.RGBA, err error)

PageSize draws a whole page into exactly w × h pixels. The page is stretched if the requested size has a different aspect ratio.

func (*Renderer) Pages added in v0.1.8

func (r *Renderer) Pages(ctx stdcontext.Context, v *bdf.View, pages []int, scale float64, workers int, yield func(page int, img *image.RGBA) error) error

Pages draws selected zero-based page numbers and calls yield in selection order, on the calling goroutine. nil pages selects all pages; an empty slice draws none. The callback owns each image and may retain or modify it. Each worker uses a separate Renderer. Neither the receiver, document nor external font resources may be mutated concurrently with this call. FontFS must support concurrent reads when more than one worker is used.

workers=0 chooses up to four workers; explicit values must be 1..16. Concurrency is further bounded by a 32-million-pixel aggregate base-canvas budget (a larger individual page is drawn alone). Layer/scratch allocations are additional. Output images in flight are bounded by the worker count; images retained by yield are the caller's responsibility. Cancellation and callback errors stop between drawings/batches, not during a rasterization already in progress. All workers finish before return.

func (*Renderer) PagesDPI added in v0.1.8

func (r *Renderer) PagesDPI(ctx stdcontext.Context, v *bdf.View, pages []int, dpi float64, workers int, yield func(page int, img *image.RGBA) error) error

PagesDPI is Pages with dpi converted to device pixels per point.

func (*Renderer) PagesMono added in v0.1.8

func (r *Renderer) PagesMono(ctx stdcontext.Context, v *bdf.View, pages []int, scale float64, workers int, mono Mono, yield func(page int, img image.Image) error) error

PagesMono is Pages with monochrome images (see PageMono): an *image.Gray each for Gray, an *image.Paletted for Bilevel.

func (*Renderer) PagesRows added in v0.1.8

func (r *Renderer) PagesRows(ctx stdcontext.Context, v *bdf.View, pages []int, scale float64, mono Mono, yield func(page, y0 int, rows image.Image) error) (err error)

PagesRows is PageRows for the selected zero-based page numbers, in selection order, one after the other: yield takes the page number too. nil pages selects all pages; an empty slice draws none. The selection is checked before any page is drawn. Cancellation of ctx is seen between bands.

func (*Renderer) PlaceRows added in v0.2.0

func (r *Renderer) PlaceRows(v *bdf.View, page int, pl Place, mono Mono, yield func(y0 int, rows image.Image) error) (err error)

PlaceRows draws a page of a fixed or flow view (or a strip of a scroll view) placed on an image as pl says, in bands of rows from the top, as PageRows draws a page: for printing, where the image is the sheet of paper at the printer's resolution and the page is scaled to it, turned to its orientation, and centred or put at its margins. The shadows of the page turn with it. The pixels of a Place of the page's own size, at no turn and at the origin, are those of PageRows.

func (*Renderer) Region

func (r *Renderer) Region(v *bdf.View, page int, region bdf.Rect, w, h int) (*image.RGBA, error)

Region draws a rectangle of a view into a w × h image: of the page with index page in a fixed or flow view (in page units), of the continuous layout of a scroll view (its strips stacked, in units from the top), or of a sheet (page is ignored in the last two).

func (*Renderer) RegionMono added in v0.1.8

func (r *Renderer) RegionMono(v *bdf.View, page int, region bdf.Rect, w, h int, mono Mono) (image.Image, error)

RegionMono is Region in a monochrome image (see PageMono).

func (*Renderer) Warnings

func (r *Renderer) Warnings() []string

Warnings returns what could not be drawn as the viewer would, once each.

Jump to

Keyboard shortcuts

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