render

package module
v0.71.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: BSD-3-Clause Imports: 31 Imported by: 8 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

render

CI Go Reference Go Report Card Coverage

Turns a page of a PDF into pixels, in pure Go with no C anywhere.

It reads with reader, takes what a document says about its fonts from pdffont, rasterises with go-gfx/gfx, and — where there is text — shapes and outlines it with go-opentype. Nothing else: this builds for GOOS=js/wasm and every architecture the fleet targets, which is what lets a PDF be shown in a browser tab with nothing on the far end.

What it draws

The graphics half of the format: the transform stack, path construction and every one of the ten painting operators, filling under both winding rules, stroking with the caps, joins, miter limit and dash pattern the graphics state carries, clipping — including clips that intersect and are let go again with Q — the device, calibrated, profile-based, indexed, separation and pattern colour spaces, constant transparency, and form XObjects with their own matrix, bounding box and resources.

Images too: XObjects and inline images, at every bit depth the format has, in every colour space, with a /Decode array, as one-bit stencils painted in the colour in force, and with either kind of transparency — a soft mask of levels or a stencil of what to leave out. A format nothing here reads is left undrawn rather than drawn wrong.

Which decoder runs is part of what this draws, so it is named:

filter decoder
/DCTDecode go-images/jpeg — Go's own image/jpeg with one change, a four-component picture's chroma upsampled the way libjpeg does rather than by repeating each sample. The standard library merges those four planes itself and hands back an *image.CMYK, so a caller cannot put it right afterwards: the planes are gone. Worth 36 levels to 2 on the cyan plate of one corpus picture.
/JPXDecode go-images/jpeg2000, a fork for the same kind of reason
/JBIG2Decode go-gfx/gfx/codec, where the fleet keeps its image decoders
/CCITTFaxDecode, /FlateDecode, /LZWDecode, /RunLengthDecode go-pdfkit/reader, which runs them to samples

This said "a JPEG is decoded by the standard library", which stopped being true when the fork was taken.

Text: the whole text state and every positioning and showing operator, with glyphs taken from an embedded TrueType or OpenType font, from a PostScript Type 1 program, from a bare CFF one, from a composite font addressed by character identifier, or — for a Type 3 font, whose glyphs are little content streams — by running them. A simple font is addressed by the name its encoding gives a code, and falls back on the program's own built-in encoding when the document says nothing. A font whose program the file does not carry at all — two pages of the corpus in five — is drawn in a stand-in: Arimo, Tinos and Cousine are metric-compatible with Helvetica, Times and Courier, so the text comes out the width it was meant to be even where the document gives no widths of its own. A bold is made by stroking the outline as well as filling it and an italic by leaning it over, since only one weight of each stand-in is carried. Symbol and the dingbats are left alone: no face here has their glyphs, and something is not better than nothing when the something is the wrong alphabet.

Gradients and patterns: the axial and radial shadings that carry nearly every gradient anyone draws, painted on their own with sh or used as a fill or a stroke; tiling patterns, coloured and uncoloured, run once per cell and clipped to the shape; and the four kinds of function the format has — a sampled grid, an exponential curve, several of them stitched end to end, and a little PostScript program — which are also what a Separation or DeviceN colour space's tint transform is written in.

And the mesh shadings, all four of them, which is how a plotting tool writes a surface: free-form and lattice-form triangles, each corner its own colour, and Coons and tensor patches, whose four sides are curves. A patch is drawn by cutting it into a grid of little quadrilaterals — the inside of a Coons patch follows from its twelve boundary points, and a tensor patch says four more — and every triangle is filled by mixing the colours at its corners across it. A patch may carry on from the one before it, sharing an edge and two of its colours, which is how a surface is written without repeating a single point.

A pattern is placed in the space of the content that names it. That is the page's own space at the top level, and inside a form it is the form's: its matrix and the transform that drew it both count. Nearly every figure a plotting tool writes is a form, so a pattern that stayed at the page's origin would miss the shape it was asked to fill by the width of a page.

A page as SVG

err := render.PageSVG(doc, 1, w, render.SVGOptions{
	MaxBytes:    8 << 20,          // refuse (ErrSVGTooLarge), writing nothing; default 64 MiB
	RasterScale: 2,                // pixels per point of the embedded pictures; default 2
	MaxDuration: 5 * time.Second,  // as Options.MaxDuration; ErrTimedOut; default 10 s
})

On any error other than a failing writer nothing is written: the document is built in memory, bounded by MaxBytes, and handed to w in one call, so half a document never passes for a whole one.

Paths, clips, images, transparency groups and text (as outlines, so no font is needed) become SVG elements. What SVG 1.1 cannot say, which is tiling and shading patterns, shadings and soft masks, is drawn by the pixel renderer and embedded as an <image> where it falls. The document holds only numbers, generated ids and base64 data: nothing the PDF says is copied as text, href is #id or a data:image/png|jpeg;base64, URI, and there is no <script>, <foreignObject>, <style> or on* attribute. NaN and infinities are never printed. The allowlist is checked in production, not only in the tests: PageSVG reads the finished buffer once more, element by element and attribute by attribute, and refuses it (writing nothing) if anything is off it; that costs one allocation per id and none per byte. Every document the test suite draws is also held to it, and FuzzPageSVG does the same for any content stream.

A small file cannot ask for much. A picture is only as large as the clip it is drawn under, never the page; equal pictures are embedded once and used where they fall; a rectangle clip inside a rectangle clip is their intersection, one clip, and clips of any other shape may nest 64 deep (more is ErrSVGTooDeep); MaxDuration is ten seconds when left at zero. The test TestASmallFileCannotAskForMuchMemoryOrOutput states the measured bounds.

Limits, stated rather than hidden:

  • Text render modes 4 to 7 (clip) are not honoured, as in the pixel renderer (#137); blend modes are not either (#138).
  • Knockout groups are not read.
  • Images are smoothed by an SVG viewer where the raster path is nearest-neighbour; opaque JPEG-like images are re-encoded at quality 90.
  • A transparency group under a soft mask is embedded as a picture whose alpha is recovered from the painted-coverage grid, an approximation: the worst channel difference from the pixel renderer is 1 level in the test pages.
  • The independent check, oksvg, draws only shapes and text (no <image>, no clip paths, and it never reads fill-rule): on the five vector pages it can draw, the worst mean difference from the pixel renderer is 0.23 levels per channel, with 0.17 % of pixels far.

Thumbnails, and a strip of them

A page strip wants a hundred small pictures of somebody else's file, quickly and without being able to be made to allocate. That is Page with three options and nothing else:

img, err := render.Page(doc, i, render.Options{
    Scale:       0.2,              // device pixels per point: a 612pt page → 122px
    MaxPixels:   4 << 20,          // what the file may ask to allocate
    MaxDuration: 2 * time.Second,  // what it may ask to spend
})
rgba := img.ToNRGBA()              // for a toolkit that wants image.RGBA

Scale is the thumbnail control — device pixels per point, so 0.2 is a fifth of the page's own size. MaxPixels and MaxDuration are the two bounds a caller drawing an untrusted file needs: one caps what comes out, the other caps the work of making it. ⛔ On a timeout the page comes back as far as it got, with ErrTimedOut — deliberately not a blank, because half a page is worth more than nothing to somebody scrolling, and the error says plainly that it is half.

Measured on a 68-page scanned book, at load average 25 so the figures are pessimistic:

scale per thumbnail worst page pixels in the strip
0.15 21.9 ms 54 ms 25 394
0.25 21.7 ms 93 ms 69 989
0.50 20.3 ms 31 ms 271 545

⛔ The scale barely moves it, and that is the useful part. Ten times the pixels cost the same, because on a scanned page the time goes into decoding the embedded image, not into rasterising it — so for scans, asking for a larger thumbnail is nearly free, and asking for a smaller one saves nothing. A strip of a hundred is about two seconds; a virtualised strip that draws only what is on screen is a tenth of that.

How it is checked

By writing a PDF whose geometry is known and looking at the pixels that come out: a rectangle from (10,10) to (40,40) on a hundred-point page has to be ink at (25,75) in the image and paper at (25,55), which is what says the page's coordinates — which count up from the bottom left — were mapped the right way up. Rotation, a media box that does not start at the origin, the crop box winning over the media box, every colour space, both winding rules, clipping, transparency and forms are all checked the same way.

Then on the corpus, for robustness rather than correctness: 4 108 pages drawn from 3 999 real files with no panics and no failures. 6 of them come out blank, which is the honest count of pages carrying nothing this wave understands yet — it was 373 before images, 31 before text, and 26 before Type 1 and bare CFF font programs.

And, when what is underneath changes, on the corpus again — by hashing every page's pixels before and after rather than by watching the exit status. That is how the two defects behind gfx v0.10.0 and opentype v0.7.0 were measured: a stroke assembled out of overlapping pieces came out at about half the colour it was asked for, and a CID font that carried no character map was refused outright, taking every glyph in it off the page. 3 520 of 4 057 pages changed; 1 705 of them gained ink, one of them twice over.

Testing

go test -covermode=set ./...

CI gates on exact 100% statement coverage, go vet, and a cross-compile across linux/{amd64,arm64,riscv64,loong64,ppc64le,s390x}, js/wasm, darwin/arm64 and windows/amd64.

and a cross-compile — it also RUNS the suite where it used only to build it. Eight lanes beyond linux/amd64:

lane how
riscv64, loong64, ppc64le, s390x, arm go test ./... under qemu-*-static
386 natively — qemu-i386 loses the guest's floating-point state across preemption, which failed five of eight runs and passed eight of eight with asyncpreemptoff=1; the workflow carries that measurement beside the lane
macos-latest, windows-latest go test ./... on the runner

s390x is big-endian. Cross-compiling for darwin and windows is not running there, and poppler and pdfium are tested on both — so those two are not new ground, they are ground the references hold and this repository did not: path handling, line endings and file semantics are where a Linux-only suite is quietly incomplete.

The rest of the family

reader reads and writes the format · ops is the verbs and the pdfops command · render turns a page into pixels · pdffont is what a document says about a font · extract reads a page back · coedit is a PDF several people edit at once · app is the browser workbench.

Documentation for all of it: https://go-pdfkit.github.io/docs/

License

BSD-3-Clause — see LICENSE. Copyright the go-pdfkit/render authors.

Documentation

Overview

Package render turns a page of a PDF into pixels.

It reads with github.com/go-pdfkit/reader and rasterises with github.com/go-gfx/gfx. Nothing outside those and the standard library is used, so it builds for js/wasm and for every architecture the fleet targets — which is what lets a PDF be shown in a browser tab with nothing on the far end.

Index

Constants

This section is empty.

Variables

View Source
var ErrSVGTooDeep = errors.New("render: the SVG would nest clips deeper than its limit")

ErrSVGTooDeep says the page nests clips deeper than the SVG can hold: a rectangle inside a rectangle is one clip, but sixty-five clips of any other shape, one inside the next, are refused. Nothing was written.

View Source
var ErrSVGTooLarge = errors.New("render: the SVG would be larger than its limit")

ErrSVGTooLarge says the page would have come out past SVGOptions.MaxBytes. Nothing was written.

View Source
var ErrTimedOut = errors.New("render: the page was still being drawn when its time ran out")

ErrTimedOut says a page was still being drawn when its time ran out. The image returned with it holds what had been drawn by then.

View Source
var ErrTooMuchToDecode = errors.New("render: the page names more picture than may be decoded at once")

ErrTooMuchToDecode says a page names more picture than Images will decode at once. Nothing comes back with it: half the pictures of a page would be read as the whole of them by anything counting.

Functions

func Page

func Page(d *reader.Document, i int, opt Options) (*raster.Image, error)

Page draws the i'th page of a document, counting from one.

func PageSVG added in v0.70.0

func PageSVG(d *reader.Document, i int, w io.Writer, opt SVGOptions) error

PageSVG writes the i'th page of a document, counting from one, as SVG.

Paths, text, clips, images and transparency groups become SVG elements; everything that has no equivalent in SVG 1.1 — tiling and shading patterns, shadings, soft masks — is drawn by the pixel renderer and embedded as an image where it falls. Text is written as outlines, so the output depends on no font. On any error but a failing writer nothing is written to w. The document holds only numbers, generated ids and base64 data: nothing the PDF says is copied into it as text.

Types

type GlyphFont added in v0.71.0

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

A GlyphFont is one font of a document, ready to be asked for glyphs.

func (*GlyphFont) Advance added in v0.71.0

func (g *GlyphFont) Advance(code int) float64

Advance is how far the pen moves for a code, in text space: a fraction of the font size, before the character and word spacing are added.

func (*GlyphFont) Codes added in v0.71.0

func (g *GlyphFont) Codes(s []byte) []int

Codes splits a string shown with the font into its character codes.

func (*GlyphFont) Embolden added in v0.71.0

func (g *GlyphFont) Embolden() bool

Embolden says the font stands in for a bold face the document does not carry and the renderer draws it heavier than its outline.

func (*GlyphFont) FontMatrix added in v0.71.0

func (g *GlyphFont) FontMatrix() [6]float64

FontMatrix is a Type 3 font's glyph space to text space.

func (*GlyphFont) Outline added in v0.71.0

func (g *GlyphFont) Outline(code int) ([]GlyphSeg, bool)

Outline is the shape of a code in text space, and false when the font has none (a code it does not carry, a font program that cannot be read, a Type 3 font). A stand-in for an italic is leaned here as it is drawn. The slice is shared: it must not be written to.

func (*GlyphFont) Resources added in v0.71.0

func (g *GlyphFont) Resources() reader.Dict

Resources is the /Resources of a Type 3 font, nil when it has none.

func (*GlyphFont) Simple added in v0.71.0

func (g *GlyphFont) Simple() bool

Simple says codes are single bytes, which is when the word space applies.

func (*GlyphFont) Type3 added in v0.71.0

func (g *GlyphFont) Type3() bool

Type3 says the glyphs are content streams (GlyphFont.Type3Proc) and not outlines.

func (*GlyphFont) Type3Proc added in v0.71.0

func (g *GlyphFont) Type3Proc(code int) (*reader.Stream, bool)

Type3Proc is the glyph procedure of a Type 3 font for a code: a content stream that draws the glyph in glyph space, which GlyphFont.FontMatrix maps to text space.

func (*GlyphFont) Vertical added in v0.71.0

func (g *GlyphFont) Vertical() bool

Vertical says the font is written top to bottom, which this package does not draw: a composite font with a vertical CMap (Identity-V, a name ending in -V, or a CMap stream with WMode 1). A caller that cannot reproduce what the renderer draws should refuse it.

type GlyphOp added in v0.71.0

type GlyphOp uint8

GlyphOp is one command of a glyph's outline.

const (
	GlyphMove GlyphOp = iota
	GlyphLine
	GlyphQuad
	GlyphClose
)

The commands of an outline. A quadratic takes a control point and an end point, and a move or a line an end point: P[0] is the control or the end.

type GlyphSeg added in v0.71.0

type GlyphSeg struct {
	Op GlyphOp
	P  [2][2]float64
}

A GlyphSeg is one command of an outline and its points, in text space: one unit is the font size, so the glyph is placed by scaling it by the size.

type Image added in v0.17.0

type Image struct {
	// Name is the resource name the page draws it by.
	Name string
	// Object is the number of the indirect object the picture was stored in,
	// and nought when it has none: an inline image, or a stream written
	// directly into the resource dictionary rather than referred to.
	//
	// It is here because it is the one identity a picture and another tool's
	// extraction of it can be matched on, and this is the only place that
	// knows it without guessing. A caller left with the NAME has to walk the
	// document again to recover it, and a name is not an identity: it is
	// unique within one resource dictionary and not across the several a page
	// reaches through its forms, so `Im1` can mean two different objects on
	// one page. go-pdfkit/conformance rebuilt this number that way and needed
	// three mechanisms to do it -- a walk, an ambiguity rule for names that
	// reached two objects, and a mapping from a mask to the picture that names
	// it -- and each of the three produced a defect.
	//
	// A MASK carries the object of the picture that NAMES it, not its own.
	// That is what pdfimages publishes on an smask row, and it is the number a
	// mask can actually be paired on.
	Object int
	// Filter is the image format the picture was stored in — DCTDecode,
	// JPXDecode, JBIG2Decode, CCITTFaxDecode — and is empty when the bytes
	// were samples that no image codec had to read.
	Filter string
	// Decoded says the dictionary carried a /Decode array, which maps the
	// stored samples onto the range the colour space wants and is applied
	// here. It is worth knowing about because it is the one thing that makes
	// this picture differ from the same picture as another tool EXTRACTS it:
	// pdfimages writes the samples as stored, so a /Decode of [1 0] on a
	// one-bit mask makes the two exact complements of each other, and every
	// pixel differs for a reason that is not a disagreement.
	Decoded bool
	// Stencil says the picture is a one-bit mask, which carries no colours of
	// its own: it paints whatever colour is in force through its own shape.
	// Its Pic has that shape in the alpha channel and black everywhere else,
	// because the colour is not the image's to know.
	Stencil bool
	// Pic is the decoded picture.
	Pic *raster.Image
}

Image is one picture a page draws, decoded.

func Images added in v0.17.0

func Images(d *reader.Document, i int) ([]Image, error)

Images decodes the pictures the i'th page draws, counting from one, in the order of the names it draws them by.

It exists because a page is the wrong unit for two jobs. Getting the pictures out of a document is one. Finding out whether a codec is right is the other: a page is a composition, so one image decoded wrongly can be averaged away by everything drawn over and around it, and a per-page difference of a few percent says nothing about which image was wrong. That mattered here — a release went out drawing scanned pages dark because "ink appeared" was measured instead of "the right ink".

What comes back is what each CODEC produced, not what the page draws. A picture that names a mask is returned unmasked, and the mask is returned beside it as its own entry, named for the key that named it. That is what pdfimages does, and it is the only way the two can be compared: applying a mask to one side and not the other made 21 of 22 JPEG 2000 pictures in a corpus of scanned pages look wrong, when 11 of them differed by nothing but the /SMask.

It also means a picture whose mask cannot be read still comes back. Page declines to draw that one, because how much of it shows is unknown — but the codec read it, and this is about the codec.

A picture nothing here can decode is left out rather than returned empty, which is the same answer Page gives by not drawing it. Inline images — the ones written into the content stream with BI — are not returned: they are named by no resource and are objects of nothing, so there is nothing for a tool that extracts a file's objects to hand back beside them.

It is the CONTENT STREAM that is walked, not the page's /Resources. A resource dictionary is a catalogue of what a page may draw, and PDF lets every page in a file share one; see [renderer.imagesDrawn] for what walking the catalogue instead did to a measurement.

Each picture comes back once, however many of the page's forms reach it, and a page that draws more picture than [maxImagesPixels] is refused whole with ErrTooMuchToDecode rather than decoded until the machine gives out.

type Options

type Options struct {
	// Scale is device pixels per point. Zero means one, which is seventy-two
	// to the inch; [Options.DPI] is the same thing said the other way.
	Scale float64
	// DPI sets the scale from dots per inch. It is ignored when Scale is set.
	DPI float64
	// Background is painted before anything else. The zero value is opaque
	// white, which is what paper is.
	Background *color.RGBA
	// MaxPixels refuses a page that would come out larger than this, so a
	// media box a file made up cannot be asked to fill memory. Zero means
	// forty million, which is a little over A4 at 600 dots to the inch.
	MaxPixels int
	// NoAnnotations leaves out what the page carries beside its content: the
	// notes, the highlights, the stamps, and the fields of a form. They are
	// drawn by default, because a filled-in form drawn without them is a form
	// with nothing in it.
	NoAnnotations bool
	// MaxDuration is how long the page may be drawn for. Zero means as long as
	// it takes, which is what this did before there was anywhere to say
	// otherwise.
	//
	// Some pages take a very long time. Of 59 432 corpus pages drawn at half
	// as much again as their own size, 1 131 were still going after twenty
	// seconds, and one figure took two hundred and seventy-three. A caller
	// drawing somebody else's file — a browser tab, a queue of them, a server
	// — cannot afford to wait for the worst of those and has, until now, had
	// no way to say so: MaxPixels bounds what comes out, and nothing bounded
	// the work of making it.
	//
	// When the time runs out the page stops being drawn and comes back as far
	// as it got, with ErrTimedOut. That is deliberately not a blank: half a
	// page is worth more than nothing to somebody scrolling, and the error
	// says plainly that it is half.
	MaxDuration time.Duration
	// AllLayers draws every optional-content layer, including the ones the
	// document's default configuration turns off.
	//
	// The default is to draw what the document says it shows when it is
	// opened. On the corpus that is the same picture either way: 275 of the
	// 1 633 real forms use optional content and 161 hide a group, but not one
	// mark on any page of any of the 8 300 files measured falls inside a layer
	// its own configuration hides. See optional.go for the numbers and for why
	// the mechanism is read all the same.
	//
	// A caller that wants everything — a tool showing a layer panel, an
	// archive comparing what a file holds against what it displays — sets
	// this and gets the behaviour from before optional content was read.
	AllLayers bool
}

Options say how a page is to be drawn.

type Outliner added in v0.71.0

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

An Outliner reads the fonts of a document the way the renderer does, and hands their glyphs out as shapes instead of drawing them. It is how a tool that rewrites a content stream turns text into paths without a second implementation of which glyph a code stands for: the answer is the one this package draws, so a page rewritten with it looks like the page rendered.

An Outliner is not safe for concurrent use.

func NewOutliner added in v0.71.0

func NewOutliner(d *reader.Document) *Outliner

NewOutliner reads the fonts of d.

func (*Outliner) Font added in v0.71.0

func (o *Outliner) Font(entry reader.Object) (*GlyphFont, bool)

Font reads the font a /Font resource entry stands for: an indirect reference or the dictionary itself. The same reference gives the same font, read once. ok is false when the entry is not a font dictionary.

type SVGOptions added in v0.70.0

type SVGOptions struct {
	// MaxBytes refuses a document that would come out larger than this, with
	// [ErrSVGTooLarge], and writes nothing. Zero means 64 MiB. A page a file
	// made up can be asked for any number of marks, and each is a few dozen
	// bytes of text: this is what bounds the output.
	MaxBytes int
	// RasterScale is how many pixels a point gets in the pictures embedded for
	// what SVG cannot say as a shape: a tiling or shading pattern, a soft mask,
	// a transparency group under a mask. Zero means two. The page's own
	// coordinates are unaffected; only these pictures change in sharpness (and
	// in size).
	RasterScale float64
	// MaxDuration is how long the page may be interpreted for, as for
	// [Options.MaxDuration] except that zero means ten seconds, not no limit.
	// When it runs out [ErrTimedOut] is returned and
	// nothing is written: unlike a raster, a document cut short is not a
	// smaller picture but malformed.
	MaxDuration time.Duration
}

SVGOptions say how a page is written as SVG.

Jump to

Keyboard shortcuts

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