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, one implementing MarkedContentDevice the marked-content sequences around it. Page.Text extracts the characters of a page with their quads, in points of the displayed page (Page.DisplayMatrix), and the structure element and artifact each belongs to, and lays them out in lines and blocks in reading order: by the structure tree of a tagged PDF, else by columns and rows.
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 Destination
- type Device
- type DocMatch
- type DocPos
- type Document
- func (d *Document) Destination(t *LinkTarget) (Destination, bool)
- func (d *Document) Edit() *Editor
- func (d *Document) Form() *Form
- func (d *Document) LayerConfigs() []*LayerConfig
- func (d *Document) Layers() *LayerConfig
- func (d *Document) Metadata() Metadata
- func (d *Document) NumPages() int
- func (d *Document) Page(i int) (p *Page, err error)
- type EditPage
- type Editor
- func (e *Editor) AddHighlight(i int, h Highlight) error
- func (e *Editor) DeletePages(indices ...int) error
- func (e *Editor) Flatten() error
- func (e *Editor) ImportPages(at int, src *Document, pages ...EditPage) error
- func (e *Editor) MovePage(from, to int) error
- func (e *Editor) NumPages() int
- func (e *Editor) RotatePage(i, degrees int) error
- func (e *Editor) Save(w io.Writer) (err error)
- func (e *Editor) SetFields(state *FormState) error
- func (e *Editor) Update(w io.Writer) (err error)
- 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 Granularity
- type Group
- type Highlight
- type Hit
- type HitKind
- type Image
- type ImageFilter
- type Layer
- type LayerConfig
- type LayerNode
- type Link
- type LinkTarget
- type MarkedContent
- type MarkedContentDevice
- 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) DisplayMatrix() Matrix
- func (p *Page) Index() int
- func (p *Page) Links() []Link
- 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)
- func (p *Page) TextWith(ctx context.Context, opt TextOptions) (*PageText, error)
- type PageText
- func (t *PageText) All() TextRange
- func (t *PageText) CharAt(x, y float64) (int, bool)
- func (t *PageText) Find(query string, opt SearchOptions) []TextMatch
- func (t *PageText) FindQuote(q Quote, opt SearchOptions) (TextMatch, bool)
- func (t *PageText) InRect(r Rect) []TextRange
- func (t *PageText) LineAt(p TextPos) TextRange
- func (t *PageText) Offset(p TextPos) int
- func (t *PageText) PosAt(x, y float64) TextPos
- func (t *PageText) PosAtOffset(n int) TextPos
- func (t *PageText) Quads(r TextRange) []Quad
- func (t *PageText) QuoteOf(r TextRange, context int) Quote
- func (t *PageText) RangeOfOffsets(lo, hi int) TextRange
- func (t *PageText) Select(a, b TextPos, g Granularity) TextRange
- func (t *PageText) String() string
- func (t *PageText) TextOf(r TextRange, format TextFormat) string
- func (t *PageText) URLs() []Link
- func (t *PageText) WordAt(p TextPos) TextRange
- type Paint
- type PanicError
- type Path
- type Quad
- type Quote
- 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 SearchOptions
- type Shading
- type SoftMask
- type Stats
- type StrokeStyle
- type TextBlock
- type TextChar
- type TextDevice
- type TextFormat
- type TextIndex
- func (x *TextIndex) Document() *Document
- func (x *TextIndex) Find(ctx context.Context, query string, opt SearchOptions, from DocPos, ...) iter.Seq2[DocMatch, error]
- func (x *TextIndex) FindQuote(ctx context.Context, q Quote, opt SearchOptions, near int) (DocMatch, bool, error)
- func (x *TextIndex) Hit(ctx context.Context, i int, px, py float64) (Hit, error)
- func (x *TextIndex) Page(ctx context.Context, i int) (*PageText, error)
- func (x *TextIndex) TextOf(ctx context.Context, a, b DocPos, format TextFormat) (string, error)
- type TextLine
- type TextMatch
- type TextMode
- type TextOptions
- type TextPos
- type TextRange
- type Tile
- type Usage
- type Value
- type ValueKind
- type View
- type Visibility
- type Widget
- type WidgetPlacement
Examples ¶
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 ( ErrCertified = errors.New("cera: the document's certification does not allow the change") ErrLocked = errors.New("cera: the field is locked by a signature") ErrSigned = errors.New("cera: the document is signed: a new file would invalidate its signatures, an update keeps them") )
Errors of editing a signed or certified document.
var ErrDeadline = errors.New("cera: render deadline exceeded")
ErrDeadline is returned when rendering stops at RenderOptions.Deadline or because the context was cancelled.
var ErrNoAssembly = errors.New("cera: the document's permissions do not allow reassembling it")
ErrNoAssembly is returned for an encrypted document whose permissions do not allow reassembling it (bit 11 of /P): it may not be saved as a new file, and its pages may not be imported.
var ErrNoUpdate = errors.New("cera: the document cannot be updated incrementally")
ErrNoUpdate is returned by Editor.Update for a document that cannot be updated incrementally: a new one, and one whose structure needed a repair.
var ErrNotPermitted = errors.New("cera: the document's permissions do not allow the change")
ErrNotPermitted is returned by Editor.Update for a change the permissions of an encrypted document do not allow: changing the pages needs the permission to modify it or to assemble it, writing form values the permission to fill in forms, to annotate or to modify, adding annotations the permission to annotate or to modify.
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 Destination ¶ added in v0.8.0
type Destination struct {
// Page is the 0-based target page.
Page int
// Fit is "XYZ", "Fit", "FitH", "FitV", "FitR", "FitB", "FitBH" or
// "FitBV".
Fit string
// X and Y are the point to show at the top-left corner of the window
// (XYZ), the top edge (FitH, FitBH: Y) or the left edge (FitV, FitBV:
// X); NaN keeps the current one.
X, Y float64
// Zoom is the magnification of XYZ, 0 to keep the current one.
Zoom float64
// Rect is the area to fit into the window for FitR.
Rect Rect
}
Destination is the view a link leads to, in points of the displayed target page. Fit is the kind of view, turned with the page: a /FitH on a page rotated by 90° fits the height of the displayed page and is a FitV.
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) Destination ¶ added in v0.8.0
func (d *Document) Destination(t *LinkTarget) (Destination, bool)
Destination resolves t to a view of a page of d. It reports false for a target that is not in d: a URI, an external link, a named destination the document does not define or a page out of range.
func (*Document) Edit ¶ added in v0.7.0
Edit returns an editor of d with all its pages.
Example ¶
A report with a cover page from another file, its last page deleted; its outline, form and the rest kept.
package main
import (
"log"
"os"
"github.com/timzifer/cera"
)
func main() {
report, err := os.ReadFile("report.pdf")
if err != nil {
log.Fatal(err)
}
cover, err := os.ReadFile("cover.pdf")
if err != nil {
log.Fatal(err)
}
doc, err := cera.Open(report)
if err != nil {
log.Fatal(err)
}
src, err := cera.Open(cover)
if err != nil {
log.Fatal(err)
}
e := doc.Edit()
if err := e.DeletePages(e.NumPages() - 1); err != nil {
log.Fatal(err)
}
if err := e.ImportPages(0, src, cera.EditPage{Index: 0}); err != nil {
log.Fatal(err)
}
f, err := os.Create("out.pdf")
if err != nil {
log.Fatal(err)
}
defer f.Close()
if err := e.Save(f); err != nil {
log.Fatal(err)
}
}
Output:
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 EditPage ¶ added in v0.7.0
type EditPage struct {
Index int // 0-based page index in the source document
Rotate int // extra clockwise rotation in degrees, a multiple of 90 (added to the page's /Rotate)
// Fields brings the page's form fields with it: the part of its
// document's field tree that leads to the page's widgets, a root
// renamed name_2 and so on when the result has its name. They come
// with the first copy of the page; signature fields stay plain
// annotations. Without it, widgets stay as plain annotations.
Fields bool
}
EditPage selects a page to import.
type Editor ¶ added in v0.7.0
type Editor struct {
// contains filtered or unexported fields
}
Editor records the pages of a document being edited or put together. It is not safe for concurrent use, but the documents it uses may be rendered while it is. Its methods change nothing when they fail.
func NewEditor ¶ added in v0.7.0
func NewEditor() *Editor
NewEditor returns an editor of a new, empty document.
Example ¶
Pages 3 to 5 and page 1 of a file in a new one, the last turned to landscape.
package main
import (
"log"
"os"
"github.com/timzifer/cera"
)
func main() {
data, err := os.ReadFile("in.pdf")
if err != nil {
log.Fatal(err)
}
doc, err := cera.Open(data)
if err != nil {
log.Fatal(err)
}
e := cera.NewEditor()
err = e.ImportPages(0, doc,
cera.EditPage{Index: 2}, cera.EditPage{Index: 3}, cera.EditPage{Index: 4},
cera.EditPage{Index: 0, Rotate: 90})
if err != nil {
log.Fatal(err)
}
f, err := os.Create("out.pdf")
if err != nil {
log.Fatal(err)
}
defer f.Close()
if err := e.Save(f); err != nil {
log.Fatal(err)
}
}
Output:
func (*Editor) AddHighlight ¶ added in v0.8.0
AddHighlight adds h to page i of the result, a page of the edited document, on top of its annotations; Save and Update write it with an appearance stream. The page keeps the highlight when it moves.
func (*Editor) DeletePages ¶ added in v0.7.0
DeletePages removes the pages at the given indices of the result.
func (*Editor) Flatten ¶ added in v0.7.0
Flatten records that the form of the edited document is flattened when the editor writes it. It returns ErrSigned for a signed document, whose signatures are fields too.
func (*Editor) ImportPages ¶ added in v0.7.0
ImportPages inserts the given pages of src before page at (NumPages to append), in that order; a page may repeat.
func (*Editor) MovePage ¶ added in v0.7.0
MovePage moves the page at index from so that it is at index to.
func (*Editor) RotatePage ¶ added in v0.7.0
RotatePage turns the page at index i clockwise by degrees, a multiple of 90.
func (*Editor) Save ¶ added in v0.7.0
Save writes the result to w as a new file, which is never encrypted: an encrypted document is written decrypted when its permissions allow reassembling it. A signed document is refused with ErrSigned: a new file invalidates its signatures, and Editor.Update keeps them. The editor may be saved again. Nothing is written when Save fails, but for an error of w itself.
func (*Editor) SetFields ¶ added in v0.7.0
SetFields records the values of the fields of state that differ from what the document holds, to be written by Editor.Save and Editor.Update. state must be of the form of the edited document. A later call replaces what an earlier one recorded.
It returns ErrCertified for a document whose certification allows no change, and ErrLocked for a field a signature locks. Writing values removes an XFA form (/XFA), which would show the old ones. Calculated and formatted fields (Field.HasActions) are not computed again: cera runs no JavaScript.
func (*Editor) Update ¶ added in v0.7.0
Update writes the edited document's file to w as it was read, followed by an incremental update that makes it the result (PDF 2.0, 7.5.6). The original bytes stay as they are, so signatures over them stay valid, and the update holds only what changed: the pages of the document keep their objects, deleted pages and what hung on them alone are freed, and imported pages are copied in. An unchanged document is written as it is. An encrypted document stays encrypted: what the update writes is encrypted with its key. It returns ErrNoUpdate for an editor made with NewEditor and for a document that needed a repair, ErrNotPermitted for a change an encrypted document's permissions do not allow, and ErrCertified for changes a certification signature does not allow: any with DocMDP permissions 1, changes of the pages with 2 and 3, added annotations with 1 and 2. The editor may be updated again. Nothing is written when Update fails, but for an error of w itself.
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 Granularity ¶ added in v0.8.0
type Granularity uint8
Granularity is the unit a selection grows by.
const ( SelectChars Granularity = iota // single characters: a drag SelectWords // whole words: a double click and drag SelectLines // whole lines: a triple click and drag SelectBlocks // whole blocks )
Granularities.
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 Highlight ¶ added in v0.8.0
type Highlight struct {
// Kind is "Highlight" (the default), "Underline", "StrikeOut" or
// "Squiggly".
Kind string
// Quads are the areas marked, in points of the displayed page, as
// PageText.Quads returns them for a range: corners in QuadPoints
// order, the first two along the top edge of the text. Quads that
// enclose no area are left out.
Quads []Quad
// Color is the colour, gray, RGB or CMYK components from 0 to 1;
// yellow for a highlight and black for the others when empty.
Color []float64
// Opacity is the constant opacity from 0 to 1 (/CA); 0 means opaque.
// A highlight multiplies with what is below it either way.
Opacity float64
// Note is the text of the annotation (/Contents); a note adds a popup
// that viewers show it in.
Note string
// Author (/T), Name (/NM, unique on the page) and Date (/M and
// /CreationDate, left out when zero) describe the annotation.
Author string
Name string
Date time.Time
}
Highlight is a text markup annotation to add to a page: a highlight, or a line under or through text.
type Hit ¶ added in v0.8.0
type Hit struct {
Kind HitKind
// Link is the link under the point (HitLink).
Link *Link
// Widget is the form field widget under the point (HitWidget); cera
// only reports it, editing is the form layer's.
Widget *Widget
// Pos is the text position nearest to the point (HitText), and Char
// the character under it, -1 between characters.
Pos TextPos
Char int
}
Hit is what lies at a point of a page.
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 Link ¶ added in v0.8.0
type Link struct {
// Index is the link annotation's index in /Annots (Annotation.Index),
// -1 for an address found in the text (PageText.URLs).
Index int
// Quads are the areas that react, in points of the displayed page: the
// /QuadPoints of the annotation, else its rectangle.
Quads []Quad
// Target is where the link leads.
Target LinkTarget
}
Link is a place on a page that leads somewhere.
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
// External reports a link out of the document: to another PDF file
// (/GoToR), where Page, Fit, Params and Named are in that file, or to
// a file or application (/Launch). File names it. cera follows
// neither, and a viewer should ask before it does.
External bool
File string
}
LinkTarget is where a link goes: a URI, or a place in the document.
type MarkedContent ¶ added in v0.8.0
type MarkedContent struct {
// Tag is the sequence's tag, such as P, Span or Artifact.
Tag string
// MCID identifies the sequence in the structure tree of the page; -1
// when it has none.
MCID int
// ActualText replaces the text of the content inside, when
// HasActualText; it may be empty, to drop that text.
ActualText string
HasActualText bool
// Alt is an alternate description and Lang the language, empty when
// the sequence has none.
Alt, Lang string
}
MarkedContent is a marked-content sequence. It is reused: devices must not keep it.
type MarkedContentDevice ¶ added in v0.8.0
type MarkedContentDevice interface {
Device
BeginMarkedContent(mc *MarkedContent)
EndMarkedContent()
}
MarkedContentDevice is implemented by devices that want to know the marked-content sequences of a page (PDF 2.0, 14.6): the structure of a tagged PDF, replacement text, artifacts. The interpreter calls BeginMarkedContent at BMC and BDC and EndMarkedContent at the matching EMC; sequences still open at the end of a content stream are ended there. Content hidden by optional content is inside its sequences too.
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. Its units are /UserUnit points; Size and DisplayMatrix
// apply it.
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) DisplayMatrix ¶ added in v0.8.0
DisplayMatrix maps default user space to points of the displayed page: y down, origin at the top-left corner of Box, rotated clockwise by /Rotate and scaled by /UserUnit. Text, links and the boxes of the text API are in these points; a viewer scales them by its zoom. Its inverse maps them back to user space.
func (*Page) Links ¶ added in v0.8.0
Links returns the link annotations of the page that lead somewhere, in the order of /Annots, leaving out hidden ones.
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 are the characters in reading order: the characters of a line
// follow each other, and the lines of a block.
Chars []TextChar
// Lines are the lines of text, in reading order.
Lines []TextLine
// Blocks are the blocks of lines, such as paragraphs or table cells,
// in reading order.
Blocks []TextBlock
// contains filtered or unexported fields
}
PageText is the text of a page laid out in lines and blocks, in reading order. It is not changed after Page.Text returns it and may be used from several goroutines.
func (*PageText) CharAt ¶ added in v0.8.0
CharAt returns the index of the character whose quad contains (x, y), in points of the displayed page.
func (*PageText) Find ¶ added in v0.8.0
func (t *PageText) Find(query string, opt SearchOptions) []TextMatch
Find returns the places of query in the text, in reading order and not overlapping. The text is searched as String has it, with runs of white space as one space, soft hyphens left out and words broken across lines (TextLine.Hyphenated) joined; so is the query.
func (*PageText) FindQuote ¶ added in v0.8.0
func (t *PageText) FindQuote(q Quote, opt SearchOptions) (TextMatch, bool)
FindQuote returns the place of q.Exact in the text whose text before and after it agrees most with q.Prefix and q.Suffix; the first such place on a tie. opt.WholeWord is ignored.
func (*PageText) InRect ¶ added in v0.8.0
InRect returns the ranges of the characters whose centres are inside r, in points of the displayed page: a rectangular selection, such as a column of a table.
func (*PageText) LineAt ¶ added in v0.8.0
LineAt returns the line at p, or before it at the end of a line.
func (*PageText) Offset ¶ added in v0.8.0
Offset returns the byte offset of p in String: where the text of Chars[p] starts, or the length of the text for the end.
func (*PageText) PosAt ¶ added in v0.8.0
PosAt returns the position nearest to (x, y), in points of the displayed page: on the nearest line, before the character under the point when the point is in its first half, else after it. A drag from PosAt of one point to PosAt of another selects the text between them, also when the points are beside or between lines.
func (*PageText) PosAtOffset ¶ added in v0.8.0
PosAtOffset returns the position of the byte offset n of String: before the character whose text holds it, or after the text before n when n is in the space or line breaks between characters.
func (*PageText) Quads ¶ added in v0.8.0
Quads returns the boxes that highlight r: one per line it touches, from the first to the last character of r on the line, as high as the line.
func (*PageText) QuoteOf ¶ added in v0.8.0
QuoteOf returns the text of r with context characters of the text before and after it (0 means 32): the anchor FindQuote finds r by again.
func (*PageText) RangeOfOffsets ¶ added in v0.8.0
RangeOfOffsets returns the characters whose text is in the bytes String()[lo:hi], with those it covers only in part: the way back from an anchor kept as a byte range of the text of a page.
func (*PageText) Select ¶ added in v0.8.0
func (t *PageText) Select(a, b TextPos, g Granularity) TextRange
Select returns the range between the positions a and b, in either order, grown to whole units of g and to whole /ActualText sequences.
func (*PageText) String ¶
String returns the text: lines are separated by a line break, blocks by an empty line, and a space stands where characters on a line are further apart than a word space. A character the font gives no text for is U+FFFD. White space starting a line is left out, and so are lines without text, such as the rest of a word whose /ActualText is on an earlier line.
func (*PageText) TextOf ¶ added in v0.8.0
func (t *PageText) TextOf(r TextRange, format TextFormat) string
TextOf returns the text of r, as String does for the whole page: a space for a word space, a line break between lines and an empty line between blocks.
func (*PageText) URLs ¶ added in v0.8.0
URLs returns the web and mail addresses written in the text (http://, https://, www. and mailto:), as links with Index -1; an address that starts with www. leads to http://. An address ends at white space, so one broken across lines is found up to the break.
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 Quad ¶ added in v0.8.0
type Quad struct {
P [4][2]float64
}
Quad is a quadrilateral, such as the box of a glyph on a rotated or skewed baseline. P[0] to P[1] runs along the text, P[0] to P[2] across it towards the next line, and P[3] is the corner opposite P[0]: for upright horizontal text, upper left, upper right, lower left and lower right, the order of the QuadPoints of a text markup annotation.
func QuadOf ¶ added in v0.8.0
QuadOf returns the quad of r: upper left, upper right, lower left, lower right, with y down.
type Quote ¶ added in v0.8.0
type Quote struct {
Prefix, Exact, Suffix string
}
Quote is a passage of text with some of the text before and after it, as a W3C TextQuoteSelector: an anchor that finds the passage again after the text was extracted anew, or in another text layer of the same document. White space in it is one space.
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 SearchOptions ¶ added in v0.8.0
type SearchOptions struct {
// MatchCase tells upper and lower case apart.
MatchCase bool
// WholeWord finds the query only where it does not continue a word
// before or after it.
WholeWord bool
// IgnoreDiacritics finds "resume" in "résumé"; it also reads
// compatibility characters as what they stand for, such as "2" for
// "²".
IgnoreDiacritics bool
// Context is how many characters of the text before and after a match
// its Quote holds: 0 means 32, a negative number none.
Context int
}
SearchOptions control Find.
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 TextBlock ¶ added in v0.8.0
type TextBlock struct {
// Lines[Start:End] of the PageText are the lines of the block.
Start, End int
// Bounds is the box around the block.
Bounds Rect
}
TextBlock is a block of lines with the same direction, one below the other.
type TextChar ¶
type TextChar struct {
// Text is what the glyph stands for, usually one character; empty when
// the font does not say. A glyph standing for several characters, such
// as a ligature, is split into one TextChar per character. Inside a
// sequence with /ActualText, the first glyph has that text and the
// others none.
Text string
// Code is the character code shown.
Code int
// Origin is the pen position of the glyph, Quad the box of its em
// square (ascent to descent, origin to advance) and Box the bounds of
// Quad, in points of the displayed page: y down, origin at the top-left
// corner, after /Rotate and /UserUnit (see Page.DisplayMatrix).
Origin [2]float64
Quad Quad
Box Rect
// Dir is the unit vector the pen moves along, and Advance how far it
// moves for this glyph, in points, before character and word spacing.
Dir [2]float64
Advance float64
// Size is the em size in points.
Size float64
Font string
Mode TextMode
// MCID is the marked-content identifier of the innermost sequence
// around the glyph that has one, which ties it to the structure tree
// of a tagged PDF; -1 when there is none.
MCID int
// Artifact reports that the glyph is inside an Artifact sequence:
// page furniture such as running heads, page numbers or watermarks.
Artifact bool
// 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 TextFormat ¶ added in v0.8.0
type TextFormat struct {
// JoinHyphenated drops the hyphen of a word broken across lines
// (TextLine.Hyphenated) and the line break after it.
JoinHyphenated bool
}
TextFormat controls TextOf.
type TextIndex ¶ added in v0.8.0
type TextIndex struct {
// contains filtered or unexported fields
}
TextIndex holds the text of the pages of a document, laid out once and kept for the most recently used pages. It is safe for concurrent use.
func NewTextIndex ¶ added in v0.8.0
func NewTextIndex(d *Document, opt TextOptions, maxPages int) *TextIndex
NewTextIndex returns an index of the text of d, laid out with opt, that keeps the text of at most maxPages pages; 0 or less means 64.
func (*TextIndex) Find ¶ added in v0.8.0
func (x *TextIndex) Find(ctx context.Context, query string, opt SearchOptions, from DocPos, backward bool) iter.Seq2[DocMatch, error]
Find returns the places of query in the document, page by page, as PageText.Find finds them: forward from the matches that start at or after from, to the end of the document and on from its start; or, when backward is set, back from the matches that end at or before from. Each match comes once. A page whose text cannot be laid out yields its error with a DocMatch for that page and no Range, and the search goes on as long as the caller wants; when ctx ends, Find yields its error and stops.
func (*TextIndex) FindQuote ¶ added in v0.8.0
func (x *TextIndex) FindQuote(ctx context.Context, q Quote, opt SearchOptions, near int) (DocMatch, bool, error)
FindQuote returns the place of q as PageText.FindQuote finds it, on page near or else on the page nearest to it that has q.Exact; the pages after near come before those as far before it.
func (*TextIndex) Hit ¶ added in v0.8.0
Hit returns what lies at (x, y) on page i, in points of the displayed page: a link annotation, else an address in the text, else a visible widget, else a line of text, else nothing.
type TextLine ¶ added in v0.8.0
type TextLine struct {
// Chars[Start:End] of the PageText are the characters of the line.
Start, End int
// Quad is the box of the line, from the start of its first character
// to the end of its last, and from the highest ascent to the lowest
// descent; Dir is the direction of the text.
Quad Quad
Dir [2]float64
// Block is the index of the line's block.
Block int
// Hyphenated reports that the line ends in a hyphen that breaks a word
// continued on the next line of the block.
Hyphenated bool
}
TextLine is a line of text: characters on one baseline, close enough to read as one line.
type TextMatch ¶ added in v0.8.0
type TextMatch struct {
// Range is the characters of the passage; Quads draws them.
Range TextRange
// Quote is its text, with the text around it.
Quote Quote
}
TextMatch is a passage found in the text of a page.
type TextOptions ¶ added in v0.8.0
type TextOptions struct {
// Layers and Usage select the optional content whose text is
// extracted, as for RenderOptions.
Layers *Visibility
Usage Usage
// Annotations selects the annotations whose appearances add text, as
// for RenderOptions.
Annotations AnnotMode
// Form supplies field values, whose generated appearances add text.
Form *FormState
// IgnoreStructure orders the text by its layout alone. Otherwise the
// structure tree of a tagged PDF orders the blocks it covers.
IgnoreStructure bool
}
TextOptions control Page.TextWith.
type TextPos ¶ added in v0.8.0
type TextPos int
TextPos is a position in the text of a page: the boundary before Chars[p], from 0 to len(Chars).
type TextRange ¶ added in v0.8.0
type TextRange struct{ Start, End TextPos }
TextRange is the characters Chars[Start:End] of a page.
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
- annotwrite.go
- budget.go
- cffcid.go
- color.go
- colormath.go
- device.go
- displaylist.go
- doc.go
- document.go
- editor.go
- extgstate.go
- fill_amd64.go
- font.go
- fontcid.go
- fontmatrix.go
- fontrepair.go
- fontsubst.go
- form.go
- formflatten.go
- formgen.go
- formlayer.go
- formstate.go
- formwrite.go
- function.go
- glyphcache.go
- group.go
- image.go
- imagedecode.go
- imagedraw.go
- interp.go
- layers.go
- links.go
- macglyphs.go
- markedcontent.go
- metadata.go
- pattern.go
- quad.go
- render.go
- shading.go
- shadingdraw.go
- signing.go
- structtree.go
- text.go
- textindex.go
- textlayout.go
- textpage.go
- textsearch.go
- textselect.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. |
|
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. |
|
pdfedit
Package pdfedit puts edited documents together: the page tree, the catalogue, pages of the edited document with everything around them and pages imported from others alone (ADR 0013).
|
Package pdfedit puts edited documents together: the page tree, the catalogue, pages of the edited document with everything around them and pages imported from others alone (ADR 0013). |
|
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. |
|
pdfwrite
Package pdfwrite writes PDF files made of objects built in memory and of objects copied from source documents.
|
Package pdfwrite writes PDF files made of objects built in memory and of objects copied from source documents. |
|
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. |
|
testpdf
Package testpdf builds small PDF files for tests: a sample with the structures editing must keep or drop, and an encrypted one.
|
Package testpdf builds small PDF files for tests: a sample with the structures editing must keep or drop, and an encrypted one. |
|
Package pdfedit builds new PDF files from the pages of existing ones.
|
Package pdfedit builds new PDF files from the pages of existing ones. |