Documentation
¶
Overview ¶
Package cera renders PDF pages to raster images in pure Go.
cera joins four layers:
- parsing: internal/pdf (objects, cross-references, filters, repair, encryption, a cache of decoded streams), safe for concurrent use;
- interpretation: this package scans content streams without allocating per operand and turns their operators into calls on a Device (graphics state, paths, clips, colours, forms, text), with fonts read by internal/pdffont and github.com/go-opentype/opentype;
- a display list: what a page draws at one scale, with device-space boxes and a band index, so a page is interpreted once and only the visible part is drawn, by several cores;
- rasterization: github.com/timzifer/stilus, a sparse CPU rasterizer whose cost per path is edge length plus covered spans, with the shaders cera paints through: images, glyph masks, layers, gradients and meshes.
Use ¶
doc, err := cera.Open(data)
page, err := doc.Page(0)
dst := image.NewRGBA(page.Bounds(150.0 / 72))
err = page.Render(ctx, dst, cera.RenderOptions{Scale: 150.0 / 72})
The destination belongs to the caller and can be reused; rasterizer buffers live in pooled workers, so steady-state rendering does not allocate page-sized memory. dst may cover only part of the page (a tile or a viewport), and only that part is drawn. The page keeps its display list for the next render at the same scale until Page.Release; bands of the page are drawn by RenderOptions.Workers goroutines (all cores by default).
Text ¶
Filled text reaches a device as GlyphRuns (Device.FillGlyphs): glyph outlines in em units with their device matrices. The raster device keeps a coverage mask per glyph, size and subpixel position. Page.Run drives any Device without a display list, and a device implementing TextDevice also receives the text shown in every render mode; Page.Text extracts the characters of a page with their boxes.
Images ¶
Images reach a device as DrawImage with the matrix of their unit square. A document decodes each image once and keeps it in a bounded cache; an Image holds its samples as compactly as they come (one bit or one byte a pixel with a palette where it can) and its mask at the mask's own resolution. The raster device samples the mip level that fits the device resolution, so an image drawn small costs what its device pixels cost, not what its samples do.
Transparency ¶
Transparency groups and soft masks reach a device as BeginGroup/EndGroup and BeginMask/EndMask; an object painted with a blend mode or a soft mask arrives as a group of its own. The raster device draws a group into a layer covering only what the group can touch in the band being drawn and composites it through the clips around it. The display list drops the groups that need no layer, which are most of them.
Shadings and colour ¶
Shadings reach a device as FillShading, painting the current clip; a path, stroke or text painted with a pattern arrives as the pattern painted through a clip of its shape: FillShading for a shading pattern, FillTile for a tiling pattern (one step rasterized at device resolution and repeated with wrap-around). A document reads each shading once into what a device draws without PDF functions: a colour ramp for axial and radial shadings, a sampled texture for function-based ones and Gouraud-shaded triangles for the four mesh kinds. Colour spaces are converted to sRGB: Separation and DeviceN through their tint transforms (tabulated for one ink), CalGray, CalRGB, Lab and ICC profiles of the matrix/TRC kind through CIE XYZ; other ICC profiles fall back on the device space of as many components.
Optional content ¶
Document.Layers reads the layers of a document (optional content groups and configurations). A Visibility selects which of them a render shows, RenderOptions.Layers passes it; it is a value the caller owns, so views of one document can show different layers. The display list records hidden content too and evaluates its layer tags once per render, so switching layers draws again without interpreting the page. Page.RunWith gives other devices only the content a Visibility shows.
Annotations ¶
Page.Annotations lists the annotations of a page with their flags and link targets. Rendering draws them after the page content from their appearance streams, or from appearances cera generates for markup annotations that have none; RenderOptions.Annotations and SkipAnnotation choose which, without interpreting the page again.
Forms ¶
Document.Form reads the fields of an interactive form and their widgets. The values a user enters live in a FormState the caller owns; rendering with RenderOptions.Form draws widgets whose value changed with generated appearances, each recorded once per value and drawn over the page's display list. A FormLayer drives a FormWidgetProvider, which draws widgets natively with a UI toolkit over the page image, and tells a render (FormLayer.Skip) to leave those widgets out of the image.
Robustness ¶
Broken content is skipped, not fatal: unknown or malformed operators are ignored, unsupported features are counted in Stats, a panic is recovered and reported as a *PanicError, and RenderOptions.Deadline bounds the time spent on one page.
Index ¶
- Constants
- Variables
- type Align
- type AnnotFlags
- type AnnotMode
- type Annotation
- type Appearance
- type BlendMode
- type BorderStyle
- type Device
- type Document
- type Field
- type FieldFlags
- type FieldType
- type FillRule
- type Font
- type FontProvider
- type FontRequest
- type Form
- type FormLayer
- type FormState
- type FormWidgetProvider
- type Glyph
- type GlyphRun
- type Group
- type Image
- type ImageFilter
- type Layer
- type LayerConfig
- type LayerNode
- type LinkTarget
- type Matrix
- type Metadata
- type OpenOptions
- type Option
- type Page
- func (p *Page) Annotations() []Annotation
- func (p *Page) Bounds(scale float64) image.Rectangle
- func (p *Page) Index() int
- func (p *Page) Release()
- func (p *Page) Render(ctx context.Context, dst *image.RGBA, opt RenderOptions) (err error)
- func (p *Page) Run(ctx context.Context, dev Device, scale float64, st *Stats) error
- func (p *Page) RunWith(ctx context.Context, dev Device, opt RunOptions) (err error)
- func (p *Page) Size() (w, h float64)
- func (p *Page) Text(ctx context.Context) (*PageText, error)
- type PageText
- type Paint
- type PanicError
- type Path
- type RasterDevice
- func (d *RasterDevice) BeginGroup(r Rect, m Matrix, g *Group)
- func (d *RasterDevice) BeginMask(r Rect, m Matrix, sm *SoftMask)
- func (d *RasterDevice) ClipPath(p *Path, m Matrix, rule FillRule)
- func (d *RasterDevice) ClipRect(r Rect, m Matrix)
- func (d *RasterDevice) ClipStroke(p *Path, m Matrix, st *StrokeStyle)
- func (d *RasterDevice) DrawImage(img *Image, m Matrix, paint *Paint)
- func (d *RasterDevice) EndGroup()
- func (d *RasterDevice) EndMask()
- func (d *RasterDevice) Err() error
- func (d *RasterDevice) FillGlyphs(run *GlyphRun, paint *Paint)
- func (d *RasterDevice) FillPath(p *Path, m Matrix, rule FillRule, paint *Paint)
- func (d *RasterDevice) FillShading(sh *Shading, m Matrix, paint *Paint)
- func (d *RasterDevice) FillTile(t *Tile, m Matrix, paint *Paint)
- func (d *RasterDevice) PopClip()
- func (d *RasterDevice) Reset(dst *image.RGBA, region image.Rectangle)
- func (d *RasterDevice) StrokePath(p *Path, m Matrix, st *StrokeStyle, paint *Paint)
- type Rect
- type RenderOptions
- type RunOptions
- type Shading
- type SoftMask
- type Stats
- type StrokeStyle
- type TextChar
- type TextDevice
- type TextMode
- type Tile
- type Usage
- type Value
- type ValueKind
- type View
- type Visibility
- type Widget
- type WidgetPlacement
Constants ¶
const ( NonZero = stilus.NonZero EvenOdd = stilus.EvenOdd )
Fill rules.
const ( BlendNormal = stilus.BlendNormal BlendMultiply = stilus.BlendMultiply BlendScreen = stilus.BlendScreen BlendOverlay = stilus.BlendOverlay BlendDarken = stilus.BlendDarken BlendLighten = stilus.BlendLighten BlendColorDodge = stilus.BlendColorDodge BlendColorBurn = stilus.BlendColorBurn BlendHardLight = stilus.BlendHardLight BlendSoftLight = stilus.BlendSoftLight BlendDifference = stilus.BlendDifference BlendExclusion = stilus.BlendExclusion BlendHue = stilus.BlendHue BlendSaturation = stilus.BlendSaturation BlendColor = stilus.BlendColor BlendLuminosity = stilus.BlendLuminosity )
Blend modes.
Variables ¶
var ( ErrReadOnly = errors.New("cera: field is read-only") ErrInvalidValue = errors.New("cera: invalid field value") )
Errors of FormState.SetValue.
var ErrDeadline = errors.New("cera: render deadline exceeded")
ErrDeadline is returned when rendering stops at RenderOptions.Deadline or because the context was cancelled.
Functions ¶
This section is empty.
Types ¶
type AnnotFlags ¶
type AnnotFlags uint32
AnnotFlags are the flags of an annotation (/F).
const ( AnnotInvisible AnnotFlags = 1 << iota AnnotHidden AnnotPrint AnnotNoZoom AnnotNoRotate AnnotNoView AnnotReadOnly AnnotLocked AnnotToggleNoView AnnotLockedContents )
Annotation flags.
type Annotation ¶
type Annotation struct {
Index int // position in /Annots
Subtype string // "Text", "Link", "Widget", "Square", ...
Rect Rect // in default user space
Flags AnnotFlags
// Contents is the text of the annotation, or its alternate
// description.
Contents string
Name string // /NM
// Link is the target of a Link annotation; nil for other types and
// for links that go nowhere cera can name.
Link *LinkTarget
// contains filtered or unexported fields
}
Annotation is an annotation of a page.
type Appearance ¶
type Appearance struct {
// FontName is the /DA font's base name, "Helvetica"; FontSize its size
// in points, 0 for auto-size.
FontName string
FontSize float64
TextColor color.RGBA
// Background is /MK /BG and Border /MK /BC, nil for none.
Background *color.RGBA
Border *color.RGBA
// BorderWidth is /BS /W (or /Border), in points.
BorderWidth float64
BorderStyle BorderStyle
Align Align
// Caption is /MK /CA: the label of a push button, the ZapfDingbats
// character of a check box or radio button's mark.
Caption string
}
Appearance is what the PDF asks a widget to look like, read from /DA, /Q, /MK and /BS. Providers use it to style native widgets like the PDF.
type BlendMode ¶
BlendMode is a PDF blend mode (PDF 2.0, 11.3.5); PDF's blend modes are those of stilus.
type BorderStyle ¶
type BorderStyle uint8
BorderStyle is the style of a widget's border (/BS /S).
const ( BorderSolid BorderStyle = iota BorderDashed BorderBeveled BorderInset BorderUnderline )
Border styles.
type Device ¶
type Device interface {
FillPath(p *Path, m Matrix, rule FillRule, paint *Paint)
StrokePath(p *Path, m Matrix, st *StrokeStyle, paint *Paint)
ClipPath(p *Path, m Matrix, rule FillRule)
ClipRect(r Rect, m Matrix)
// ClipStroke intersects the clip with the area a stroke of p paints.
ClipStroke(p *Path, m Matrix, st *StrokeStyle)
PopClip()
// FillShading paints sh, whose space m maps to device space, over the
// current clip (and the shading's BBox) with the constant alpha
// paint.Color.A.
FillShading(sh *Shading, m Matrix, paint *Paint)
// FillTile paints t, repeated in both directions, over the current
// clip, with m mapping the tile's pixel space to device space. A
// stencil tile (t.Stencil) paints paint through its shape, any other
// its own colours with the constant alpha paint.Color.A.
FillTile(t *Tile, m Matrix, paint *Paint)
// FillGlyphs fills the outlines of run (nonzero) with paint.
FillGlyphs(run *GlyphRun, paint *Paint)
// DrawImage paints img, whose unit square m maps to device space. A
// stencil (img.Stencil) paints paint through its shape; any other
// image paints its own colours with the constant alpha paint.Color.A.
DrawImage(img *Image, m Matrix, paint *Paint)
// BeginGroup starts a transparency group; EndGroup composites it.
BeginGroup(r Rect, m Matrix, g *Group)
EndGroup()
// BeginMask starts drawing a soft mask; EndMask ends it. The mask
// applies to the group begun next, which has Masked set.
BeginMask(r Rect, m Matrix, sm *SoftMask)
EndMask()
}
Device receives the drawing operations of a page. The interpreter drives it; every backend (raster, text extraction, hit testing, GPU) implements it without touching the parser or the interpreter.
Paths are in user space and m maps them to device space, so strokes are exact under anisotropic transforms. Clips nest: every ClipPath or ClipRect is undone by exactly one PopClip.
Filled text arrives as FillGlyphs, so that a device can cache what it draws per glyph. Stroked text and text clips (render modes 1, 2 and 4–7) arrive as paths, Type 3 glyphs as the drawing operations of their content streams. A device that wants the text itself, in every render mode including invisible text, implements TextDevice as well.
Images arrive as DrawImage with m mapping the image's unit square to device space.
Transparency arrives as groups: what is drawn between BeginGroup and EndGroup is composited as one, with the group's blend mode, opacity and, for a masked group, the soft mask drawn between the BeginMask and EndMask just before it. Objects painted with a blend mode or a soft mask in the graphics state come as groups of their own. Clips, groups and masks nest: a clip pushed inside a group or mask is popped inside it. The rectangle r under m bounds what a group or mask covers.
Shadings arrive as FillShading, painting the current clip. A path, stroke or text painted with a pattern arrives as the pattern painted through a clip of the shape: ClipPath, ClipStroke for strokes, then FillShading (a shading pattern) or FillTile (a tiling pattern) and PopClip. A tiling pattern of a few large cells arrives as the drawing operations of its cells instead.
type Document ¶
type Document struct {
// contains filtered or unexported fields
}
Document is an open PDF file. It is safe for concurrent use: pages of one Document may be rendered from many goroutines at once, and what they read from the file (objects, decoded streams, fonts, images, colour spaces) is loaded once and shared. Once a page has been rendered at a scale, further renders of it at that scale only draw its display list.
func Open ¶
Open parses a PDF file. Damaged cross-reference tables, wrong stream lengths and missing objects are repaired by the reader where possible.
func OpenReaderAt ¶ added in v0.4.0
OpenReaderAt is OpenWith for a file of size bytes read through r as it is needed, rather than held in memory: a large file, or one in a browser read through the File API. r must not change while the Document is used, and must be safe for concurrent use if pages are rendered concurrently, as an *os.File is. A file with damaged cross-reference tables is read in full once to rebuild them.
func OpenWith ¶
func OpenWith(data []byte, opt OpenOptions) (doc *Document, err error)
OpenWith parses a PDF file with options: a password, a provider of fonts the document does not embed, and how CMYK is converted. It fails on a CMYKProfile it cannot read.
func OpenWithPassword ¶
OpenWithPassword parses an encrypted PDF file. It is OpenWith with a password.
func (*Document) Form ¶
Form returns the interactive form of the document, read once; nil if the document has none or its form has no fields.
func (*Document) LayerConfigs ¶
func (d *Document) LayerConfigs() []*LayerConfig
LayerConfigs returns the alternate configurations (/OCProperties /Configs).
func (*Document) Layers ¶
func (d *Document) Layers() *LayerConfig
Layers returns the default configuration of the document's optional content (/OCProperties /D), nil if the document has none.
type Field ¶
type Field struct {
// Name is the fully qualified name, "address.street".
Name string
// Alt is /TU, the tooltip and accessible name.
Alt string
Type FieldType
Flags FieldFlags
// Saved is the value the document holds (/V), Default the value a
// reset restores (/DV).
Saved Value
Default Value
// Options are the entries of a choice field (/Opt), or the export
// values of the widgets of a check box or radio button that has /Opt.
Options []Option
// MaxLen is the maximum length of a text field, 0 if unlimited.
MaxLen int
// TopIndex is the first option a list box shows (/TI).
TopIndex int
// HasActions reports JavaScript or other additional actions (/AA)
// on the field or its widgets (format, keystroke, validate,
// calculate). cera does not run them: computed fields do not update.
HasActions bool
Widgets []*Widget
// contains filtered or unexported fields
}
Field is a terminal field of a form.
type FieldFlags ¶
type FieldFlags uint32
FieldFlags are the flags of a field (/Ff). Bits not named here are kept.
const ( FfReadOnly FieldFlags = 1 << 0 FfRequired FieldFlags = 1 << 1 FfNoExport FieldFlags = 1 << 2 FfMultiline FieldFlags = 1 << 12 FfPassword FieldFlags = 1 << 13 FfNoToggleToOff FieldFlags = 1 << 14 FfRadio FieldFlags = 1 << 15 FfCombo FieldFlags = 1 << 17 FfEdit FieldFlags = 1 << 18 FfSort FieldFlags = 1 << 19 FfFileSelect FieldFlags = 1 << 20 FfMultiSelect FieldFlags = 1 << 21 FfDoNotSpellCheck FieldFlags = 1 << 22 FfDoNotScroll FieldFlags = 1 << 23 FfComb FieldFlags = 1 << 24 FfRichText FieldFlags = 1 << 25 FfRadiosInUnison FieldFlags = 1 << 25 FfCommitOnSelChange FieldFlags = 1 << 26 )
Field flags, at their bit positions in /Ff (PDF 2.0, tables 227, 229, 231 and 233). FfRichText and FfRadiosInUnison share a bit: the first applies to text fields, the second to radio buttons.
type FieldType ¶
type FieldType uint8
FieldType is the kind of a form field.
type Font ¶
type Font struct {
// contains filtered or unexported fields
}
Font is a font of a document, as the interpreter uses it. Devices get it with every GlyphRun: for the text a code stands for (Text) and for what the font is called (Name).
func (*Font) Text ¶
Text returns the characters a code stands for: the font's ToUnicode map, what its encoding calls the glyph, or for fonts of the Adobe CJK character collections what the code's CID stands for. ok is false when none says.
type FontProvider ¶
type FontProvider interface {
// Font returns a font program — TrueType, OpenType (CFF), a bare CFF
// or a Type 1 font — for the font req describes, ok false for none.
// For a composite font (req.Ordering set) it is either a CID-keyed
// program of that character collection, whose glyphs are found by
// CID, or any other program with a Unicode character map, whose
// glyphs are found by the character each CID stands for.
Font(req FontRequest) (program []byte, ok bool)
}
FontProvider supplies programs for fonts a document names but does not embed: CJK fonts (see the module github.com/timzifer/cera/fonts/cjk) or the fonts of the system the document is shown on. Font is called once per font and document, possibly from several goroutines at a time.
type FontRequest ¶
type FontRequest struct {
// Name is the font's BaseFont without a subset prefix, as the document
// spells it ("Arial,Bold", "MS-Mincho").
Name string
// Registry, Ordering and Supplement are the character collection of a
// composite font ("Adobe", "Japan1", 6), empty for a simple font.
Registry, Ordering string
Supplement int
// Vertical is a composite font written top to bottom.
Vertical bool
// The style, from the name and the font descriptor.
Serif, FixedPitch, Symbolic, Bold, Italic bool
// Weight is the descriptor's /FontWeight (400 regular, 700 bold), 0 if
// it gives none.
Weight int
}
FontRequest describes a font a document does not embed.
type Form ¶
type Form struct {
// Fields are the terminal fields, in tree order.
Fields []*Field
// NeedAppearances is /NeedAppearances: widget appearances must be
// generated rather than taken from /AP.
NeedAppearances bool
// XFA reports an /XFA entry: the document carries an XFA form, of
// which cera uses only the AcroForm fallback.
XFA bool
// contains filtered or unexported fields
}
Form is the interactive form of a document (/AcroForm).
func (*Form) PageWidgets ¶
PageWidgets returns the widgets on page i (0-based) in the order of its /Annots. The slice is shared; do not modify it.
type FormLayer ¶
type FormLayer struct {
// contains filtered or unexported fields
}
FormLayer joins a page, a form state and a provider: it translates changes of the view into Show and Hide calls, and tells a render which widgets the provider draws.
func NewFormLayer ¶
func NewFormLayer(p *Page, s *FormState, prov FormWidgetProvider) *FormLayer
NewFormLayer returns the form layer of page p showing the values of s through prov. It asks prov which widgets of the page it supports; Update shows them.
func (*FormLayer) Close ¶
func (l *FormLayer) Close()
Close hides every widget shown and stops following the state.
func (*FormLayer) Focus ¶
Focus gives w the keyboard focus (nil: none); the widget that had it and w are shown again with WidgetPlacement.Focus set accordingly.
func (*FormLayer) Next ¶
Next returns the widget after w in tab order (nil w: the first), for keyboard navigation: the page's widgets in the order of its /Tabs (row, column, or /Annots order for structure order and none), then those of the following pages. Hidden widgets and read-only fields are passed over. It returns nil after the last widget of the document.
type FormState ¶
type FormState struct {
// contains filtered or unexported fields
}
FormState holds the values of a form's fields as a user edits them. It belongs to the caller, like a Visibility: the document and the display lists of its pages are not changed, so one document can be shown with several states. Fields with several widgets, and radio groups, share one value. A FormState is safe for concurrent use; callbacks run on the goroutine that changed the value.
func (*FormState) Changed ¶
Changed returns the fields whose value differs from the one the document saved, in form order.
func (*FormState) Reset ¶
func (s *FormState) Reset()
Reset sets every field to its default value (/DV), or to empty if it has none, and calls subscribers for those that change.
func (*FormState) SetValue ¶
SetValue sets the value of f, checking it against the field: its type, MaxLen, options, ReadOnly and NoToggleToOff. A text value of a choice field selects the option of that export value or text; an editable combo box also keeps other text. Subscribers are called when the value changes.
type FormWidgetProvider ¶
type FormWidgetProvider interface {
// Supports reports whether the provider draws w natively. Widgets it
// does not support are drawn by cera from their appearance and are
// not interactive. Asked once per widget and remembered.
Supports(w *Widget) bool
// Show places the widget, creating it on first call and moving or
// restyling it on later ones. p is in view coordinates (see
// WidgetPlacement); the provider reads the current value from
// p.State and writes user input back with p.State.SetValue.
Show(w *Widget, p WidgetPlacement)
// Hide removes a widget that left the view (scrolled out, page
// released, layer switched off, field hidden).
Hide(w *Widget)
}
A FormWidgetProvider draws form widgets with a UI toolkit, over the rendered page. cera tells it which widget to show where; the provider owns everything about the widget's look and input. Its methods are called on the goroutine that calls FormLayer.Update, and, for a field whose value changes, on the goroutine that changed it.
type Glyph ¶
type Glyph struct {
// Code is the character code shown; run.Font.Text(Code) is its text.
Code int
// GID is the glyph index in the font program (the code for Type 3).
GID int
// Outline is the glyph in em units (y up, origin at the pen position),
// nil for an empty or missing glyph and for Type 3 glyphs. It is shared
// and must not be modified.
Outline *Path
// M maps the em square of the glyph to device space: font size,
// horizontal scaling, rise, text matrix and CTM.
M Matrix
// Advance is the pen movement in em, before character and word
// spacing: to the right, or down for vertical text.
Advance float64
// Origin is the pen position in the glyph's em square: (0, 0) for
// horizontal text; for vertical text the position vector, about half
// the width right of and 0.88 em above the glyph's own origin.
Origin [2]float64
}
Glyph is one glyph of a GlyphRun.
type GlyphRun ¶
type GlyphRun struct {
Font *Font
Glyphs []Glyph
// Vertical is text written top to bottom (a font with WMode 1).
Vertical bool
}
GlyphRun is the glyphs of one text-showing operator in one font. The run and its slice are reused: devices must not keep them.
type Group ¶
type Group struct {
// Isolated groups start from a transparent backdrop; non-isolated ones
// see what is below them.
Isolated bool
// Knockout groups composite each object against the group's initial
// backdrop instead of the objects before it.
Knockout bool
// Blend composites the group onto its backdrop.
Blend BlendMode
// Alpha is the group's constant opacity (255 is opaque).
Alpha uint8
// Masked composites the group through the soft mask drawn just before.
Masked bool
// contains filtered or unexported fields
}
Group describes a transparency group (PDF 2.0, 11.4).
type Image ¶
type Image struct {
// W and H are the size of the image in samples.
W, H int
// Stencil reports an image mask (/ImageMask true): the image has no
// colours and paints the fill paint through its shape.
Stencil bool
// Interpolate reports the image's /Interpolate flag: it asks for
// smoothing when the image is magnified.
Interpolate bool
// contains filtered or unexported fields
}
Image is a decoded image XObject or inline image, as a Device receives it. It is immutable and shared: by the renders of a page, by the pages of a document (through the document's image cache), and by the workers drawing it. Devices must not modify it.
An image occupies the unit square of the user space it is drawn in: its first sample row is at the top (y = 1), its first column at x = 0.
type ImageFilter ¶
type ImageFilter uint8
ImageFilter sets how a raster device samples a magnified image that does not ask for /Interpolate.
const ( // ImageNearest samples the nearest pixel, the literal reading of the // spec (and what Ghostscript does): pixel art, QR codes and scans stay // crisp. ImageNearest ImageFilter = iota // ImageSmooth samples bilinearly while the image is magnified less // than smoothLimit times, as PDFium, MuPDF and Poppler all do; images // magnified further stay crisp, as in all three. ImageSmooth )
type Layer ¶
type Layer struct {
Name string
// Visible and Locked are the state in the configuration, before the
// usage of a render applies (see LayerConfig.VisibilityFor).
Visible bool
Locked bool
// contains filtered or unexported fields
}
Layer is an optional content group as one configuration sees it.
type LayerConfig ¶
type LayerConfig struct {
Name string
// Layers are the document's groups in the order of /OCGs; Layers[i]
// of every configuration is the same group.
Layers []*Layer
// Order is the tree of /Order, for a layer panel; it may leave
// layers out.
Order []LayerNode
// RBGroups are radio-button groups: at most one layer of a group is
// meant to be visible. Visibility.With does not enforce them.
RBGroups [][]*Layer
// contains filtered or unexported fields
}
LayerConfig is a configuration of optional content (/D or an entry of /Configs).
func (*LayerConfig) Visibility ¶
func (c *LayerConfig) Visibility() Visibility
Visibility returns the visibility the configuration gives on screen.
func (*LayerConfig) VisibilityFor ¶
func (c *LayerConfig) VisibilityFor(u Usage) Visibility
VisibilityFor returns the visibility the configuration gives for usage u: its states with its automatic states (/AS) for u applied.
type LayerNode ¶
LayerNode is an entry of the layer tree a viewer shows (/Order): a layer with the layers nested under it, or a label grouping layers.
type LinkTarget ¶
type LinkTarget struct {
URI string
// Page is the 0-based target page, -1 if none.
Page int
// Fit is the kind of view of an explicit destination ("XYZ", "Fit",
// "FitH", "FitV", "FitR", "FitB", "FitBH", "FitBV") and Params its
// numbers in default user space of the target page; NaN stands for
// null (unchanged).
Fit string
Params []float64
// Named is the name of a named destination, which Page, Fit and
// Params resolve when the document defines it.
Named string
}
LinkTarget is where a link goes: a URI, or a place in the document.
type Metadata ¶ added in v0.5.0
type Metadata struct {
Title, Author, Subject, Keywords, Creator, Producer string
// Created and Modified are zero when absent or not a date. A date
// without a time zone is taken as UTC.
Created, Modified time.Time
// Trapped is "True", "False", "Unknown" or "".
Trapped string
// Custom holds the other entries of /Info that are strings, by key.
Custom map[string]string
// XMP is the catalog's /Metadata stream, decoded but not parsed; nil if
// there is none. PDF 2.0 deprecates /Info, but for its dates, in favour
// of XMP.
XMP []byte
}
Metadata is what a document says about itself: its document information dictionary (/Info), decoded, and its XMP metadata stream.
type OpenOptions ¶
type OpenOptions struct {
// Password opens an encrypted document.
Password string
// Fonts supplies programs for fonts the document does not embed; nil
// for the built-in stand-ins only.
Fonts FontProvider
// NaiveCMYK converts DeviceCMYK, and ICCBased spaces of four
// components, with R = (1-C)(1-K) and its like instead of through a
// press profile, for callers who want the device values: fills,
// strokes, shadings and images. It takes precedence over CMYKProfile.
NaiveCMYK bool
// CMYKProfile, if set, is an ICC profile (CMYK; lut8, lut16 or
// lutAtoB tables; Lab or XYZ connection space) that DeviceCMYK, and
// ICCBased spaces of four components whose own profile cera cannot
// read, are converted through instead of the bundled one (CGATS TR
// 005, SWOP), relative colorimetric with black point compensation.
// Documents opened with the same profile share its tables.
CMYKProfile []byte
}
OpenOptions are the options of OpenWith.
type Option ¶
Option is an entry of a choice field: the value exported and the text shown, which are the same unless /Opt gives both.
type Page ¶
type Page struct {
// Box is the visible area in default user space: CropBox clipped to
// MediaBox, scaled by UserUnit.
Box Rect
// Rotate is the clockwise display rotation: 0, 90, 180 or 270.
Rotate int
// contains filtered or unexported fields
}
Page is one page of a Document. It caches the display list of its last render; Release frees it.
func (*Page) Annotations ¶
func (p *Page) Annotations() []Annotation
Annotations returns the annotations of the page in the order of /Annots, read once. Unreadable entries are left out. The slice is shared; do not modify it.
func (*Page) Bounds ¶
Bounds returns the device-pixel size of the page at scale (pixels per point), rounded up.
func (*Page) Release ¶
func (p *Page) Release()
Release frees the display list cached by Render. The page stays usable.
func (*Page) Render ¶
Render draws the page into dst, whose pixel coordinates are device pixels of the whole page at opt.Scale (see Bounds). dst belongs to the caller and can be reused across calls, so rendering does not allocate a page image.
The page is interpreted into a display list once per scale; later renders at the same scale (other tiles, a scrolled viewport) only draw. Release frees the list. Bands of the page are drawn by opt.Workers goroutines.
Broken content does not stop rendering. A non-nil error means the page was drawn partially: ErrDeadline, a rasterizer budget, or a *PanicError.
func (*Page) Run ¶
Run interprets the page into dev, without a display list: device space is the page at scale pixels per point, as for Render. It is how devices other than the raster one (text extraction, hit testing) see a page. The page's box is the outermost clip. Optional content is drawn as the document's default configuration shows it on screen. st, when non-nil, receives the statistics. The error is ErrDeadline when ctx ends first, or a *PanicError.
type PageText ¶
type PageText struct {
Chars []TextChar
}
PageText is the text of a page in content order.
type PanicError ¶
PanicError reports a panic recovered while opening or rendering. It always indicates a bug in cera or one of its dependencies.
func (*PanicError) Error ¶
func (e *PanicError) Error() string
type RasterDevice ¶
type RasterDevice struct {
C *stilus.Canvas
// ImageFilter sets how magnified images that do not ask for
// /Interpolate are sampled (see RenderOptions.ImageFilter).
ImageFilter ImageFilter
// contains filtered or unexported fields
}
RasterDevice draws onto an *image.RGBA through a stilus.Canvas. Glyphs small enough are rasterized once per size and subpixel position into a cache of coverage masks kept by the device. Images are sampled from the mip level that fits the device resolution. Groups and soft masks are drawn into layers of their own (see Reset).
func (*RasterDevice) BeginGroup ¶
func (d *RasterDevice) BeginGroup(r Rect, m Matrix, g *Group)
func (*RasterDevice) ClipRect ¶
func (d *RasterDevice) ClipRect(r Rect, m Matrix)
func (*RasterDevice) ClipStroke ¶
func (d *RasterDevice) ClipStroke(p *Path, m Matrix, st *StrokeStyle)
func (*RasterDevice) DrawImage ¶
func (d *RasterDevice) DrawImage(img *Image, m Matrix, paint *Paint)
DrawImage paints img, whose unit square m maps to device space: a stencil in paint, any other image in its own colours with the constant alpha paint.Color.A.
func (*RasterDevice) EndGroup ¶
func (d *RasterDevice) EndGroup()
func (*RasterDevice) EndMask ¶
func (d *RasterDevice) EndMask()
func (*RasterDevice) Err ¶
func (d *RasterDevice) Err() error
Err returns the first error of the canvas since Reset.
func (*RasterDevice) FillGlyphs ¶
func (d *RasterDevice) FillGlyphs(run *GlyphRun, paint *Paint)
FillGlyphs draws the glyphs of run through the glyph cache, or as paths when they are large or the paint is not a solid colour.
func (*RasterDevice) FillPath ¶
func (d *RasterDevice) FillPath(p *Path, m Matrix, rule FillRule, paint *Paint)
func (*RasterDevice) FillShading ¶
func (d *RasterDevice) FillShading(sh *Shading, m Matrix, paint *Paint)
FillShading paints sh over the clip with the alpha of paint.
func (*RasterDevice) PopClip ¶
func (d *RasterDevice) PopClip()
func (*RasterDevice) Reset ¶
func (d *RasterDevice) Reset(dst *image.RGBA, region image.Rectangle)
Reset targets the device, and its canvas, at region of dst. Groups need it: a device whose canvas was targeted directly draws their content without compositing it and does not draw soft masks.
func (*RasterDevice) StrokePath ¶
func (d *RasterDevice) StrokePath(p *Path, m Matrix, st *StrokeStyle, paint *Paint)
type RenderOptions ¶
type RenderOptions struct {
// Scale is pixels per point; 0 means 1 (72 dpi). 150 dpi is 150/72.
Scale float64
// Region restricts drawing to part of the page, in device pixels of the
// whole page at Scale (a tile or viewport). Empty means dst.Bounds().
Region image.Rectangle
// Background fills the region before drawing. The zero value leaves it
// transparent; use color.RGBA{255, 255, 255, 255} for paper.
Background color.RGBA
// Deadline stops interpretation; the image then holds what was drawn
// and Render returns ErrDeadline. The zero value means no deadline.
Deadline time.Time
// Stats, when non-nil, receives what rendering did.
Stats *Stats
// Workers is the most goroutines drawing the page, each taking
// horizontal bands of it: 0 means GOMAXPROCS, 1 draws on the calling
// goroutine in one pass. A page or region estimated to draw quickly
// is drawn by fewer, or in one pass, since starting and joining
// goroutines would cost more than it saves. Antialiasing may round
// differently by one level where bands meet.
Workers int
// Layers selects the optional content to draw; nil is the document's
// default configuration for Usage (see Document.Layers). Switching
// layers does not interpret the page again.
Layers *Visibility
// Usage is UsageView (the default), UsagePrint or UsageExport. It
// selects the automatic states (/AS) of the default configuration and
// applies only when Layers is nil.
Usage Usage
// Annotations selects the annotations drawn over the page content:
// AnnotsView (the default), AnnotsPrint, or AnnotsNone.
Annotations AnnotMode
// SkipAnnotation, when set, is asked once per render for each
// annotation the mode shows, by its index in /Annots; those it
// returns true for are not drawn (a form overlay drawing its own
// widgets). Changing it does not interpret the page again.
SkipAnnotation func(index int) bool
// SimulateOverprint composites objects painted with overprint (OP,
// op) in DeviceCMYK under OPM 1, Separation or DeviceN as Multiply
// with what is below them, approximating the mixed result of print;
// off, they are painted over it, as most viewers do for files that
// are not PDF/X. The page is interpreted once per setting.
SimulateOverprint bool
// Form, when set, supplies the values of form fields: widgets whose
// value differs from the one the document saved are drawn with a
// generated appearance (or, for buttons, the appearance of their
// state). Each is recorded once per value and scale and drawn over
// the page; the page is not interpreted again. Without it the saved
// values are shown.
Form *FormState
// ImageFilter sets how magnified images that do not ask for
// /Interpolate are sampled: ImageNearest (the default) samples the
// nearest pixel, ImageSmooth samples bilinearly while an image is
// magnified less than 2×, as PDFium, MuPDF and Poppler do (beyond it
// they draw it crisp, and so does cera). Images with /Interpolate true
// are always smoothed;
// minified images are read from their mip levels either way. Switching
// it does not interpret the page again. Images inside the cells of a
// tiling pattern are drawn into the pattern's tile when the page is
// interpreted, at the nearest pixel unless they ask for /Interpolate.
ImageFilter ImageFilter
// Band, when set, is called with each part of the region once its
// pixels are final, so that an encoder can start on the first rows
// while others are drawn. The parts are horizontal strips spanning
// the region's width; they do not overlap and together cover the
// region. They come in no particular order, possibly from several
// goroutines at once, and all of them before Render returns, also
// after a deadline or a panic. With Form values to draw over the
// page, the region is one part.
Band func(r image.Rectangle)
}
RenderOptions control Page.Render.
type RunOptions ¶
type RunOptions struct {
// Scale is pixels per point, as for RenderOptions.
Scale float64
// Stats, when non-nil, receives what interpreting did.
Stats *Stats
// Layers and Usage select the optional content dev sees, as for
// RenderOptions; hidden content reaches dev only as its clips, and
// a TextDevice does not see its text.
Layers *Visibility
Usage Usage
// Annotations and SkipAnnotation select the annotations, as for
// RenderOptions. A TextDevice sees the text of their appearances.
Annotations AnnotMode
SkipAnnotation func(index int) bool
// SimulateOverprint is as for RenderOptions.
SimulateOverprint bool
// Form supplies field values, as for RenderOptions; a TextDevice
// sees the text of the generated appearances.
Form *FormState
}
RunOptions control Page.RunWith.
type Shading ¶
type Shading struct {
// Type is the ShadingType, 1 to 7.
Type int
// Coords are those of an axial (x0 y0 x1 y1) or radial
// (x0 y0 r0 x1 y1 r1) shading.
Coords [6]float64
// Extend continues an axial or radial shading beyond its ends.
Extend [2]bool
// Ramp is the colour of an axial or radial shading over its
// parameter, or of a parametric mesh over the parameter of its
// vertices (premultiplied, opaque).
Ramp stilus.Ramp
// Knots, if not empty, are the parameters of the entries of an axial
// or radial Ramp: the bounds of stitching functions appear twice,
// with the colours on either side, so that colour breaks stay exact.
Knots []float32
// BBox clips the shading in its own space if HasBBox is set.
BBox Rect
HasBBox bool
// Background is painted where the shading is not defined, when the
// shading is the paint of a pattern; transparent if there is none.
Background color.RGBA
// Texture is the colour of a function-based shading over Domain,
// which Matrix maps to shading space; its first row is at the
// bottom of the domain.
Texture *stilus.Texture
Domain Rect
Matrix Matrix
// Mesh is the triangles of a mesh shading in shading space, and
// Bounds the box of their vertices.
Mesh []stilus.MeshTriangle
Bounds Rect
// contains filtered or unexported fields
}
Shading is a smooth shading prepared for drawing. It is immutable and shared by the pages of a document and the workers drawing them.
type SoftMask ¶
type SoftMask struct {
// Luminosity takes the mask from the luminosity of the group drawn on
// Backdrop; otherwise it is the group's alpha.
Luminosity bool
// Backdrop is the opaque colour a luminosity mask group is drawn on,
// and the mask's value outside the group.
Backdrop color.RGBA
// Transfer maps mask values; nil is the identity.
Transfer *[256]uint8
}
SoftMask describes a soft mask (PDF 2.0, 11.6.5.2). Its values come from the group drawn between BeginMask and EndMask.
type Stats ¶
type Stats struct {
Ops int // content-stream operators executed, including forms
Fills int
Strokes int
Clips int
Glyphs int // glyphs filled, and Type 3 glyphs run
Images int // images drawn, inline images and stencil masks included
Groups int // transparency groups and soft masks, of forms and objects
// Shadings counts shadings painted, by sh and as the paint of a
// pattern.
Shadings int
// Unsupported counts features that were skipped or approximated, keyed
// by feature ("shading", "font-missing", "image-filter", ...).
Unsupported map[string]int
// Errors counts recoverable problems: malformed operators, missing
// resources, content that did not decode.
Errors int
// Reused reports that the page was not interpreted again: its display
// list from an earlier render at the same scale was drawn. The other
// fields are those of the render that recorded it.
Reused bool
}
Stats describes what rendering a page did.
func (*Stats) UnsupportedKeys ¶
UnsupportedKeys returns the keys of s.Unsupported in sorted order.
type StrokeStyle ¶
type StrokeStyle = stilus.StrokeStyle
StrokeStyle is a stroke in user space (width, caps, joins, dashes).
type TextChar ¶
type TextChar struct {
// Text is what the glyph stands for, usually one character; empty when
// the font does not say.
Text string
// Origin is the pen position of the glyph and Box the box of its em
// square (ascent to descent, origin to advance), in points of the
// displayed page: y down, origin at the top-left corner, after
// /Rotate.
Origin [2]float64
Box Rect
// Size is the em size in points.
Size float64
Font string
Mode TextMode
// contains filtered or unexported fields
}
TextChar is one glyph of the text of a page.
type TextDevice ¶
TextDevice is implemented by devices that want to know the text a page shows: text extraction, search, hit testing. The interpreter calls ShowText for every string shown, whatever its render mode, before it draws it.
type Tile ¶
type Tile struct {
W, H int
// Stencil reports an uncoloured pattern: the tile is a shape painted
// in the colour given with the pattern.
Stencil bool
// contains filtered or unexported fields
}
Tile is one step of a tiling pattern, XStep × YStep in pattern space, rasterized at device resolution into W × H pixels. It is immutable and shared by the renders and workers that draw it.
type Usage ¶
type Usage uint8
Usage is what a render is for; it selects the automatic states of a configuration's /AS entry and the /Usage of its groups.
type Value ¶
type Value struct {
// contains filtered or unexported fields
}
Value is the value of a field: a text, a button state or a set of selected options. The zero value is no value (push buttons and signatures). Values are immutable.
func ChoiceValue ¶
ChoiceValue returns the selection of the options at the given indices of Field.Options.
func StateValue ¶
StateValue returns the state of a check box or radio button: a widget's OnState, or "Off".
func (Value) Selected ¶
Selected returns the indices of the selected options, ascending. The slice is shared; do not modify it.
type ValueKind ¶
type ValueKind uint8
ValueKind tells the kinds of Value apart.
const ( // ValueText is the text of a text field, or of an editable combo box // whose text is none of its options. ValueText ValueKind // ValueState is the state of a check box or radio button: the name of // the "on" appearance of the widget that is on, or "Off". ValueState // ValueChoice is the set of selected options of a choice field. ValueChoice )
type View ¶
type View struct {
// Scale is pixels per point, as for RenderOptions.
Scale float64
// Viewport is the visible part of the page in device pixels of the
// whole page at Scale; empty means the whole page.
Viewport image.Rectangle
// Origin is where the page's (0, 0) pixel is in the overlay.
Origin image.Point
// Layers and Usage select optional content as for RenderOptions;
// widgets in hidden layers are hidden.
Layers *Visibility
Usage Usage
}
View is what a viewer shows of a page.
type Visibility ¶
type Visibility struct {
// contains filtered or unexported fields
}
Visibility selects the optional content a render draws: a set of the document's layers that are off, and the layers whose state depends on the zoom. The zero value shows every layer. A Visibility is a value; With returns a modified copy and leaves the original unchanged, so one document can be shown with different layers in several views.
func (Visibility) Visible ¶
func (v Visibility) Visible(l *Layer) bool
Visible reports whether l is on, at any zoom.
func (Visibility) With ¶
func (v Visibility) With(l *Layer, on bool) Visibility
With returns v with l switched on or off, for every zoom.
type Widget ¶
type Widget struct {
Field *Field
// Page is the 0-based page and Annotation the index of the widget in
// the page's /Annots (Annotation.Index).
Page int
Annotation int
// Rect is the widget's rectangle in default user space of the page.
Rect Rect
// Rotation is /MK /R: the counterclockwise rotation of the widget's
// content on the page in degrees, 0, 90, 180 or 270.
Rotation int
// Flags are the annotation flags.
Flags AnnotFlags
// OnState is the name of the "on" appearance of a check box or radio
// button, its export value; empty for other fields.
OnState string
Appearance Appearance
// contains filtered or unexported fields
}
Widget is a widget annotation of a field: where and how the field is shown on a page.
type WidgetPlacement ¶
type WidgetPlacement struct {
// Rect is the widget's rectangle in device pixels of the whole page at
// Scale — the same space as RenderOptions.Region — offset by the
// view's Origin, i.e. directly the position in the overlay. It covers
// every pixel the widget's appearance can touch.
Rect image.Rectangle
// Rotation is the clockwise rotation of the widget's content in the
// view, in degrees: the page's /Rotate less the counterclockwise /MK
// /R, 0, 90, 180 or 270.
Rotation int
// Scale is pixels per point, for font sizes and border widths: a
// provider sets the font to Appearance.FontSize * Scale.
Scale float64
State *FormState
// Focus is true when the widget should take keyboard focus (see
// FormLayer.Focus and FormLayer.Next).
Focus bool
}
WidgetPlacement is where and how large a widget is in the view.
Source Files
¶
- annot.go
- annotgen.go
- budget.go
- cffcid.go
- color.go
- colormath.go
- device.go
- displaylist.go
- doc.go
- document.go
- extgstate.go
- fill_amd64.go
- font.go
- fontcid.go
- fontmatrix.go
- fontrepair.go
- fontsubst.go
- form.go
- formgen.go
- formlayer.go
- formstate.go
- function.go
- glyphcache.go
- group.go
- image.go
- imagedecode.go
- imagedraw.go
- interp.go
- layers.go
- macglyphs.go
- metadata.go
- pattern.go
- render.go
- shading.go
- shadingdraw.go
- text.go
- textpage.go
- tiledraw.go
- transparency.go
- type3clip.go
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
corpus
command
Command corpus fetches the test corpus and renders it with cera: speed, allocations, unsupported features and robustness per page.
|
Command corpus fetches the test corpus and renders it with cera: speed, allocations, unsupported features and robustness per page. |
|
fonts
|
|
|
system
module
|
|
|
internal
|
|
|
cmap
Package cmap reads the codes of composite fonts: which bytes of a string make up one code, and which character identifier (CID) each code selects (PDF 2.0 9.7.5).
|
Package cmap reads the codes of composite fonts: which bytes of a string make up one code, and which character identifier (CID) each code selects (PDF 2.0 9.7.5). |
|
cmap/gen
command
Command gen compiles the predefined CMaps of PDF 2.0 Table 116, and the CID-to-Unicode tables of the Adobe CJK character collections, from a checkout of https://github.com/adobe-type-tools/cmap-resources into internal/cmap/data.bin.
|
Command gen compiles the predefined CMaps of PDF 2.0 Table 116, and the CID-to-Unicode tables of the Adobe CJK character collections, from a checkout of https://github.com/adobe-type-tools/cmap-resources into internal/cmap/data.bin. |
|
cmyk
Package cmyk converts DeviceCMYK to sRGB as a press would print it, through a SWOP press profile, as PDFium, MuPDF, Poppler and Ghostscript convert through profiles of their own, instead of the naive formula R = (1-C)(1-K).
|
Package cmyk converts DeviceCMYK to sRGB as a press would print it, through a SWOP press profile, as PDFium, MuPDF, Poppler and Ghostscript convert through profiles of their own, instead of the naive formula R = (1-C)(1-K). |
|
cmyk/gen
command
Command gen writes internal/cmyk/swop.bin, the profile cera converts DeviceCMYK with: the colorimetric table (A2B1) of a CMYK press profile and its black point.
|
Command gen writes internal/cmyk/swop.bin, the profile cera converts DeviceCMYK with: the colorimetric table (A2B1) of a CMYK press profile and its black point. |
|
content
Package content scans PDF content streams without allocating per operand.
|
Package content scans PDF content streams without allocating per operand. |
|
corpus
Package corpus fetches the public test corpus and writes synthetic technical-drawing pages.
|
Package corpus fetches the public test corpus and writes synthetic technical-drawing pages. |
|
pdffont
Package pdffont is the PDF side of a font: not its outlines, which are the font program's business, but what the document says about reading a string of bytes with it — which codes the string holds, how wide each is, what each glyph is called and what text it stands for (ADR 0012).
|
Package pdffont is the PDF side of a font: not its outlines, which are the font program's business, but what the document says about reading a string of bytes with it — which codes the string holds, how wide each is, what each glyph is called and what text it stands for (ADR 0012). |
|
pdfsyntax
Package pdfsyntax holds the lexical rules of the PDF object syntax that both the file reader (internal/pdf) and the content stream scanner (internal/content) need: character classes, numbers and the escapes of names and strings.
|
Package pdfsyntax holds the lexical rules of the PDF object syntax that both the file reader (internal/pdf) and the content stream scanner (internal/content) need: character classes, numbers and the escapes of names and strings. |
|
stdfont
Package stdfont holds the stand-ins for the standard fonts Symbol and ZapfDingbats, which have alphabets of their own: subsets of DejaVu Sans (Bitstream Vera licence, see LICENSE-DejaVu) with their character sets, and Adobe's metrics and built-in encodings for them.
|
Package stdfont holds the stand-ins for the standard fonts Symbol and ZapfDingbats, which have alphabets of their own: subsets of DejaVu Sans (Bitstream Vera licence, see LICENSE-DejaVu) with their character sets, and Adobe's metrics and built-in encodings for them. |
|
stdfont/gen
command
Command gen builds the stand-ins for the standard fonts Symbol and ZapfDingbats: subsets of DejaVu Sans holding the glyphs of their character sets, and tables of their built-in encodings, AFM widths and what each glyph stands for in Unicode.
|
Command gen builds the stand-ins for the standard fonts Symbol and ZapfDingbats: subsets of DejaVu Sans holding the glyphs of their character sets, and tables of their built-in encodings, AFM widths and what each glyph stands for in Unicode. |
|
Package pdfedit builds new PDF files from the pages of existing ones.
|
Package pdfedit builds new PDF files from the pages of existing ones. |