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
- func SetPoolLimits(l PoolLimits)
- type Align
- type AnnotFlags
- type AnnotMode
- type Annotation
- type Appearance
- type Attachment
- type BlendMode
- type BorderStyle
- type Cache
- type Canvas
- func (c *Canvas) Clip(p *Path, rule FillRule)
- func (c *Canvas) DrawImage(img *CanvasImage, r Rect)
- func (c *Canvas) DrawPage(src *Document, index int, r Rect) error
- func (c *Canvas) DrawText(s string, x, y float64, f *CanvasFont, size float64, col color.Color) float64
- func (c *Canvas) Fill(p *Path, rule FillRule, col color.Color)
- func (c *Canvas) FillRect(r Rect, col color.Color)
- func (c *Canvas) Restore()
- func (c *Canvas) Save()
- func (c *Canvas) SetBlendMode(b BlendMode)
- func (c *Canvas) SetOpacity(alpha float64)
- func (c *Canvas) Size() (w, h float64)
- func (c *Canvas) Stroke(p *Path, st StrokeStyle, col color.Color)
- func (c *Canvas) Transform(m Matrix)
- type CanvasFont
- type CanvasImage
- type Changes
- type Destination
- type Device
- type DocMatch
- type DocPos
- type Document
- func (d *Document) Attachments() []*Attachment
- func (d *Document) Destination(t *LinkTarget) (Destination, bool)
- func (d *Document) Edit() *Editor
- func (d *Document) Encrypted() bool
- 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) Outline() []OutlineItem
- func (d *Document) Page(i int) (p *Page, err error)
- func (d *Document) PageByLabel(label string) (int, bool)
- func (d *Document) PageLabel(i int) string
- func (d *Document) PageLabels() []LabelRange
- func (d *Document) Permissions() Permissions
- func (d *Document) Signatures() []Signature
- func (d *Document) Structure() *StructTree
- func (d *Document) Trim()
- func (d *Document) ViewSettings() (v ViewSettings)
- type Drop
- type EditPage
- type Editor
- func (e *Editor) AddAnnotation(i int, a NewAnnotation) (int, error)
- func (e *Editor) AddField(i int, rect Rect, f NewField) error
- func (e *Editor) AddHighlight(i int, h Highlight) error
- func (e *Editor) AddPage(at int, width, height float64) error
- func (e *Editor) AddSheets(at int, src *Document, s Sheet, pages ...int) error
- func (e *Editor) ApplyRedactions() (int, error)
- func (e *Editor) DeletePages(indices ...int) error
- func (e *Editor) Draw(i int, over bool, draw func(c *Canvas)) error
- func (e *Editor) Flatten() error
- func (e *Editor) FlattenAnnotations() error
- func (e *Editor) ImportPages(at int, src *Document, pages ...EditPage) error
- func (e *Editor) ImportPagesWith(at int, src *Document, opt ImportOptions, pages ...EditPage) error
- func (e *Editor) MissingGlyphs() []*Field
- func (e *Editor) MovePage(from, to int) error
- func (e *Editor) NumPages() int
- func (e *Editor) Outline() []OutlineItem
- func (e *Editor) PruneOutline()
- func (e *Editor) Redact(i int, areas []Quad, fill color.Color) error
- func (e *Editor) RemoveAnnotation(i, index int) error
- func (e *Editor) RemoveField(name string) error
- func (e *Editor) ResizePage(i int, width, height float64, fit Fit) error
- func (e *Editor) RotatePage(i, degrees int) error
- func (e *Editor) Save(w io.Writer) error
- func (e *Editor) SaveWith(w io.Writer, opt SaveOptions) (err error)
- func (e *Editor) SetAnnotation(i, index int, a NewAnnotation) error
- func (e *Editor) SetFields(state *FormState) error
- func (e *Editor) SetMetadata(m Metadata) error
- func (e *Editor) SetOutline(items []OutlineItem) error
- func (e *Editor) SetPageBox(i int, box PageBox, r Rect) error
- func (e *Editor) SetPageLabels(ranges []LabelRange) error
- func (e *Editor) Sign(w io.Writer, opt SignOptions) (err error)
- func (e *Editor) Update(w io.Writer) (err error)
- type Encryption
- type Field
- type FieldFlags
- type FieldLock
- type FieldType
- type FillRule
- type Fit
- type Font
- type FontProvider
- type FontProviders
- type FontRequest
- type Form
- type FormDataError
- type FormLayer
- type FormState
- func (s *FormState) Changed() []*Field
- func (s *FormState) Do(a WidgetAction) bool
- func (s *FormState) ExportFDF(w io.Writer) error
- func (s *FormState) ExportXFDF(w io.Writer) error
- func (s *FormState) Form() *Form
- func (s *FormState) Hidden(w *Widget) bool
- func (s *FormState) ImportFDF(r io.Reader) error
- func (s *FormState) ImportXFDF(r io.Reader) error
- func (s *FormState) Reset()
- func (s *FormState) ResetFields(fields ...*Field)
- func (s *FormState) SetHidden(w *Widget, hidden bool)
- func (s *FormState) SetValue(f *Field, v Value) error
- func (s *FormState) Submission(a WidgetAction) (body []byte, contentType string, err error)
- func (s *FormState) Subscribe(fn func(*Field)) (cancel func())
- func (s *FormState) Value(f *Field) Value
- type FormWidgetProvider
- type Glyph
- type GlyphRun
- type Granularity
- type Group
- type Highlight
- type Hit
- type HitKind
- type Image
- type ImageFilter
- type ImportOptions
- type LabelRange
- type LabelStyle
- type Layer
- type LayerConfig
- type LayerNode
- type Link
- type LinkTarget
- type MarkedContent
- type MarkedContentDevice
- type Markup
- type Matrix
- type Metadata
- type NewAnnotation
- type NewField
- type ObjectStreamMode
- type OpenOptions
- type Option
- type OutlineItem
- type Page
- func (p *Page) Annotations() []Annotation
- func (p *Page) Bounds(scale float64) image.Rectangle
- func (p *Page) Boxes() PageBoxes
- func (p *Page) Destination(t *LinkTarget) (Destination, bool)
- func (p *Page) DisplayMatrix() Matrix
- func (p *Page) EditAnnotation(index int) (NewAnnotation, bool)
- func (p *Page) InBox(box PageBox) *Page
- 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) RenderGray(ctx context.Context, dst *image.Gray, opt RenderOptions) (err error)
- func (p *Page) Rotated(degrees int) *Page
- 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 PageBox
- type PageBoxes
- 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 Permissions
- type PoolLimits
- type Popup
- type PrintSettings
- 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 Reply
- type RunOptions
- type SaveOptions
- type SearchOptions
- type Shading
- type Sheet
- type SignOptions
- type Signature
- type SignatureStatus
- type SoftMask
- type Stats
- type StrokeStyle
- type StructAttr
- type StructElem
- type StructKid
- type StructTree
- 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) SetBox(b PageBox)
- func (x *TextIndex) SetRotation(degrees int)
- 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 VerifyOptions
- type View
- type ViewSettings
- type Visibility
- type Widget
- type WidgetAction
- 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 ErrAttachmentTooLarge = errors.New("cera: the attachment is too large")
ErrAttachmentTooLarge is returned by Attachment.Open for a file that decodes to more than cera reads into memory (256 Mi bytes).
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), opened with the user password: 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.SaveWith for removing or changing the protection of a document opened with its user password, and 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, and flattening, which changes the content of pages, drawing on pages and setting metadata the permission to modify.
var ErrPassword = errors.New("cera: the document needs a password, or the password is wrong")
ErrPassword is returned by the Open functions for an encrypted document that the password of OpenOptions does not open: a missing one (the empty password was tried) and a wrong one alike. A viewer asks for a password and opens the file again.
var ErrRedaction = errors.New("cera: the page cannot be redacted")
ErrRedaction is returned when a file with a redaction is written and the content of a page cannot be rewritten: nothing is written then.
var ErrSignatureRoom = errors.New("cera: the signature does not fit the room left for it")
ErrSignatureRoom is returned by Editor.Sign when the signature is larger than the room cera left for it, as with a certificate chain a signing service adds to.
var ErrSignatureUnsupported = errors.New("cera: the signature cannot be checked")
ErrSignatureUnsupported is returned by Signature.Verify for a signature cera cannot check: a subfilter or an algorithm it does not know, or signature data it cannot read.
var ErrSubmitDocument = errors.New("cera: the action submits the document, not the values of its fields")
ErrSubmitDocument is returned by FormState.Submission for an action that sends the document itself, which is the viewer's to write.
var ErrUnsupportedEncryption = errors.New("cera: unsupported security handler")
ErrUnsupportedEncryption is returned by the Open functions for a document encrypted in a way cera cannot read: a security handler other than the standard one, or a crypt filter it does not know. No password opens it.
Functions ¶
func SetPoolLimits ¶ added in v0.10.0
func SetPoolLimits(l PoolLimits)
SetPoolLimits sets the bounds of the pools of the process. Glyph caches past the new bound are dropped at once, layer buffers as the devices that hold them are next used or collected. It is safe to call while pages are rendered.
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 is the rectangle in default user space, which
// Page.DisplayMatrix maps to points of the displayed page;
// Markup.Bounds is the result for a markup annotation.
Rect Rect
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 with neither a destination nor an action.
Link *LinkTarget
// File is the file a FileAttachment annotation embeds; nil for other
// types, and for one that names a file outside the document.
File *Attachment
// Markup is what a markup annotation says about itself — author,
// dates, colours, geometry, popup, replies; nil for the other types:
// Link, Popup, Widget and those that hold media or printing marks.
Markup *Markup
// 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 Attachment ¶ added in v0.10.0
type Attachment struct {
// Name is the file name (/UF, else /F, else the name the document
// lists it under), Description what the document says about it
// (/Desc).
Name string
Description string
// MIME is the media type of the file (/Subtype of the embedded file
// stream), such as "application/xml"; empty when the file gives none.
MIME string
// Size is the size of the file in bytes as the document states it
// (/Params /Size), -1 if it says none. Open tells the size there is.
Size int64
// Created and Modified are zero when the document does not say.
Created time.Time
Modified time.Time
// Relationship is what the file is to the document or to the part of
// it that names it (/AFRelationship): "Source", "Data", "Alternative",
// "Supplement", "EncryptedPayload", "FormData", "Schema" or
// "Unspecified"; empty when it says none. The XML of an e-invoice is
// "Alternative" or "Data".
Relationship string
// contains filtered or unexported fields
}
Attachment is a file embedded in a document.
func (*Attachment) Open ¶ added in v0.10.0
func (a *Attachment) Open() (io.ReadCloser, error)
Open returns the content of the file, decoded and, in an encrypted document, decrypted. It is read into memory: ErrAttachmentTooLarge for more than 256 Mi bytes. A document may encrypt its attachments alone; it then opens without the password, and Open returns ErrPassword until the document is opened with it.
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 Cache ¶ added in v0.10.0
type Cache struct {
// contains filtered or unexported fields
}
Cache holds the decoded images and streams of the documents opened with it (OpenOptions.Cache), least recently used dropped first: one bound for a server with many documents open, where a bound per document is none. It is safe for concurrent use.
What a document has in it leaves with Document.Trim or when the document is collected, and otherwise as other entries come in.
type Canvas ¶ added in v0.10.0
type Canvas struct {
// contains filtered or unexported fields
}
Canvas draws on a page, in points of the displayed page: the origin at the top left corner, x to the right and y down. It is valid during the call of Editor.Draw it was made for.
func (*Canvas) Clip ¶ added in v0.10.0
Clip keeps what is drawn from here on inside p, until the state saved before is restored.
func (*Canvas) DrawImage ¶ added in v0.10.0
func (c *Canvas) DrawImage(img *CanvasImage, r Rect)
DrawImage draws img into r.
func (*Canvas) DrawPage ¶ added in v0.10.0
DrawPage draws page index of src into r, as it is displayed: its content without its annotations. The page is stretched to r; Page.Size gives its proportions. It is how several pages are put on a sheet, and how a page of a file becomes a stamp or a letterhead.
func (*Canvas) DrawText ¶ added in v0.10.0
func (c *Canvas) DrawText(s string, x, y float64, f *CanvasFont, size float64, col color.Color) float64
DrawText draws s in font f at size, in col, from (x, y) on: the start of its baseline. It returns the width of what it drew. The text is one line, drawn character by character, left to right: there is no shaping, no kerning and no reordering. A character f lacks is drawn in a fallback font (Latin, Greek, Cyrillic), and as a question mark, or the glyph of an embedded font for what it lacks, when that has none either.
func (*Canvas) Restore ¶ added in v0.10.0
func (c *Canvas) Restore()
Restore brings back the state kept by the last Save.
func (*Canvas) Save ¶ added in v0.10.0
func (c *Canvas) Save()
Save keeps the state of the canvas — the transform, the clip, the opacity and the blend mode — until the Restore that belongs to it. What is still saved when the drawing ends is restored.
func (*Canvas) SetBlendMode ¶ added in v0.10.0
SetBlendMode sets how what is drawn from here on blends with what lies under it.
func (*Canvas) SetOpacity ¶ added in v0.10.0
SetOpacity sets the opacity of what is drawn from here on, from 0 to 1. The alpha of a colour is multiplied with it.
type CanvasFont ¶ added in v0.10.0
type CanvasFont struct {
// contains filtered or unexported fields
}
CanvasFont is a font to draw text with: one of the standard 14 fonts, which a file names and a viewer has, or a font program, which is embedded with the glyphs drawn. It may be used by several editors, also at once.
func NewCanvasFont ¶ added in v0.10.0
func NewCanvasFont(data []byte) (*CanvasFont, error)
NewCanvasFont returns the font of a TrueType or OpenType program, which must have a Unicode character map. The file gets a subset of it with the glyphs drawn. data is kept, and must not change. A variable font is drawn as its default instance. OpenType fonts whose CFF outlines are CID-keyed or variable (CFF2) cannot be used.
func StandardFont ¶ added in v0.10.0
func StandardFont(name string) (*CanvasFont, error)
StandardFont returns one of the standard 14 fonts: Helvetica, Times-Roman and Courier with their -Bold, -Oblique (-Italic for Times) and -BoldOblique (-BoldItalic) styles, Symbol and ZapfDingbats. They are not embedded: a viewer draws them with a font of its own. The text fonts show the characters of Windows-1252.
func (*CanvasFont) Metrics ¶ added in v0.10.0
func (f *CanvasFont) Metrics() (ascent, descent float64)
Metrics returns the ascent and the descent (negative) of the font as fractions of its size.
func (*CanvasFont) Width ¶ added in v0.10.0
func (f *CanvasFont) Width(s string, size float64) float64
Width returns the width of s at size, as Canvas.DrawText draws it.
type CanvasImage ¶ added in v0.10.0
type CanvasImage struct {
// contains filtered or unexported fields
}
CanvasImage is an image to draw, encoded for a file once: drawn on many pages, and by several editors, it is one object in each file.
func NewCanvasImage ¶ added in v0.10.0
func NewCanvasImage(img image.Image) *CanvasImage
NewCanvasImage returns img for drawing: its pixels compressed without loss, eight bits a component, grey for an image.Gray and RGB otherwise, with its alpha as a soft mask when it is not opaque.
func NewCanvasJPEG ¶ added in v0.10.0
func NewCanvasJPEG(data []byte) (*CanvasImage, error)
NewCanvasJPEG returns a JPEG image for drawing, written into the file as it is: baseline or progressive, grey, colour or CMYK. data is kept, and must not change.
func (*CanvasImage) Size ¶ added in v0.10.0
func (im *CanvasImage) Size() (w, h int)
Size returns the size of the image in pixels.
type Changes ¶ added in v0.10.0
type Changes struct {
// FormFilled: values of form fields changed. Fields names them.
FormFilled bool
Fields []string
// Signed: further signatures were added.
Signed bool
// Annotated: annotations were added, changed or removed.
Annotated bool
// Other: something else changed — pages, their content, fields added
// or removed —, or cera could not tell what did.
Other bool
}
Changes say what was appended to a file after a signature.
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. It returns ErrPassword for an encrypted file the empty password does not open, and ErrUnsupportedEncryption for one cera cannot decrypt.
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, how CMYK is converted, and how much the document keeps decoded. It fails on a CMYKProfile it cannot read.
func OpenWithPassword ¶
OpenWithPassword parses an encrypted PDF file. It is OpenWith with a password.
func (*Document) Attachments ¶ added in v0.10.0
func (d *Document) Attachments() []*Attachment
Attachments returns the files embedded in the document: those of the /EmbeddedFiles name tree, in its order, the order of their names, and then the associated files of the catalogue (/AF) that are not among them. The files of FileAttachment annotations are on their pages (Annotation.File). Read once and shared; nil for a document without.
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. The coordinates are those of the page as the file turns it; a viewer that turns its view asks the page it shows, Page.Destination.
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.
func (*Document) Metadata ¶ added in v0.5.0
Metadata returns the document's metadata. A missing or damaged /Info gives empty fields, never an error.
func (*Document) Outline ¶ added in v0.9.0
func (d *Document) Outline() []OutlineItem
Outline returns the entries at the top of the document outline, nil for a document without one. It is read once and shared; do not modify it.
func (*Document) Page ¶
Page returns page i (0-based). Pages are lightweight; nothing is interpreted until the page is rendered.
func (*Document) PageByLabel ¶ added in v0.10.0
PageByLabel returns the first page with the given label, for a "go to page" that takes what is printed on the pages. It reports false when no page has the label, as in a document without page labels; a viewer then takes the input as a page number.
func (*Document) PageLabel ¶ added in v0.10.0
PageLabel returns the label of page i (0-based): the number the document gives the page, as "iv", "12" or "A-3". It is empty for a document without page labels, for a page before the first that has one, and for a page labelled with nothing.
func (*Document) PageLabels ¶ added in v0.10.0
func (d *Document) PageLabels() []LabelRange
PageLabels returns the ranges that label the pages of the document, in the order of the pages; nil for a document without page labels, whose pages are 1, 2, 3. Document.PageLabel gives the label of one page.
func (*Document) Permissions ¶ added in v0.9.0
func (d *Document) Permissions() Permissions
Permissions returns what the document allows: AllPermissions for a document that is not encrypted and for one opened with the owner password, else what its author granted.
The editor refuses what the permissions do not allow (ErrNoAssembly, ErrNotPermitted). Reading does not: Page.Render and Page.Text work whatever PermPrint and PermCopy say, and whether to print or to copy is the decision of the application.
func (*Document) Signatures ¶ added in v0.10.0
Signatures returns the signatures of the document, in the order they were made. Read once and shared; nil for a document without.
func (*Document) Structure ¶ added in v0.10.0
func (d *Document) Structure() *StructTree
Structure returns the structure tree of a tagged document, nil for a document without one. It is read once and shared; do not modify it.
The text of an element is that of its marked content: the characters of the page's PageText with the identifier of a kid, in the order of the kids, unless the element or one above it has an ActualText.
func (*Document) Trim ¶ added in v0.10.0
func (d *Document) Trim()
Trim drops the decoded images and streams the document keeps, in its own caches or in the Cache it was opened with. The document and its pages stay usable: what they show is decoded again when it is next drawn. The display list of a page is freed by Page.Release.
func (*Document) ViewSettings ¶ added in v0.10.0
func (d *Document) ViewSettings() (v ViewSettings)
ViewSettings returns how the document asks to be opened and printed.
type Drop ¶ added in v0.10.0
type Drop uint
Drop names parts of a document a viewer does not need to show it, for SaveOptions.Drop to leave out.
const ( // DropThumbnails leaves out the thumbnail images of the pages: // viewers make their own. DropThumbnails Drop = 1 << iota // DropPieceInfo leaves out the private data that the programs which // made the document keep in it, with the document, its pages and its // form XObjects (/PieceInfo): what an illustration program needs to // edit its file again, often larger than the page it belongs to. DropPieceInfo // DropObjectMetadata leaves out the metadata streams of the pages, // images, fonts and other objects. The metadata of the document // itself stays. DropObjectMetadata )
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) AddAnnotation ¶ added in v0.9.0
func (e *Editor) AddAnnotation(i int, a NewAnnotation) (int, error)
AddAnnotation adds a to page i of the result, a page of the edited document, on top of its annotations, and returns the Index it has there: the number of annotations the page has, counted with those added before. With it a later annotation replies to this one (Markup.Reply), and Editor.SetAnnotation and Editor.RemoveAnnotation take it back. Save and Update write the annotation with an appearance stream and, for a note or a comment, a popup; the page keeps it when it moves.
Annotations the editor adds are not flattened by the same editor, and a flatten draws the document's annotations as they were, not as SetAnnotation changes them: write the changes first.
func (*Editor) AddField ¶ added in v0.10.0
AddField adds a form field to page i of the result, a page of the edited document: rect is where its widget shows, in points of the displayed page. A name that is a field's already adds a widget to that field. The field is written with an appearance for its value; a signature field is empty, for Editor.Sign to sign once the document is written.
It returns ErrCertified for a document whose certification allows no such change; an encrypted document needs the permission to modify. Editor.Flatten in the same editor flattens the form as the document has it: write the fields first.
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: Editor.AddAnnotation for text markup.
func (*Editor) AddPage ¶ added in v0.10.0
AddPage inserts a blank page of width by height points before page at (NumPages to append). Editor.Draw draws on it.
func (*Editor) AddSheets ¶ added in v0.10.0
AddSheets inserts, before page at (NumPages to append), sheets with pages of src on them: Columns by Rows on each, row by row from the top left, each page scaled to fit its place and set in the middle of it. pages are their indices in that order, -1 for a place left empty, which is how the pages of a booklet are imposed; without any, all pages of src are taken in their order. The last sheet may have places left over.
A page is drawn as it is displayed, without its annotations — it is Canvas.DrawPage on new pages, and more can be drawn on the sheets with Editor.Draw. The pages themselves are not in the result unless they are in the editor for another reason.
func (*Editor) ApplyRedactions ¶ added in v0.10.0
ApplyRedactions carries out the redaction annotations of the edited document's pages that the result still has (/Subtype /Redact): the areas they mark are redacted as Editor.Redact does, with boxes in their interior colour, and the annotations go with them. It returns the number of annotations applied. The text an annotation asks to be written over its area (/OverlayText) is not written.
func (*Editor) DeletePages ¶ added in v0.7.0
DeletePages removes the pages at the given indices of the result.
func (*Editor) Draw ¶ added in v0.10.0
Draw draws on page i of the result: draw is called once, with a canvas in points of the displayed page — the origin at its top left corner, y down, as everywhere in the editor. What it draws lies over the content of the page, or under it; drawings of several calls lie in their order. A drawing belongs to its page: it moves with it, turns with it when the page is rotated afterwards, and goes when the page is deleted. Annotations stay above everything drawn.
The content of the page is kept as it is. Content that leaves the graphics state unbalanced — more q than Q — moves what is drawn over it.
Example ¶
A page number at the foot of every page, and a cover sheet in front.
package main
import (
"fmt"
"image/color"
"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)
}
font, err := cera.StandardFont("Helvetica")
if err != nil {
log.Fatal(err)
}
e := doc.Edit()
for i := range e.NumPages() {
err := e.Draw(i, true, func(c *cera.Canvas) {
w, h := c.Size()
label := fmt.Sprintf("%d / %d", i+1, e.NumPages())
c.DrawText(label, (w-font.Width(label, 9))/2, h-24, font, 9, color.Gray{Y: 90})
})
if err != nil {
log.Fatal(err)
}
}
if err := e.AddPage(0, 595, 842); err != nil {
log.Fatal(err)
}
err = e.Draw(0, true, func(c *cera.Canvas) {
c.DrawText("Annual report", 72, 200, font, 32, color.Black)
})
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) 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) FlattenAnnotations ¶ added in v0.9.0
FlattenAnnotations records that the annotations of the edited document are flattened when the editor writes it, for print or the archive: every annotation the document shows on screen is drawn into the content of its page and leaves the page, with its popup. Links stay, and so do annotations that show nothing (hidden ones, those without an appearance cera can draw) and the widgets of the form, which Editor.Flatten draws; an annotation that lies on a widget stays with it, so that it does not end up under the widget. Annotations the editor adds itself are not flattened.
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. They bring what is on them; Editor.ImportPagesWith brings more.
func (*Editor) ImportPagesWith ¶ added in v0.10.0
ImportPagesWith is ImportPages with options: the pages bring the outline entries and named destinations that lead to them, and their page labels. What a document brings is one thing for all its pages: the options of several imports from one document add up, and its outline entries are put under the title given last. An entry or a name whose page is not in the result when it is written is left out. Pages of the edited document imported into itself bring nothing more: it has all that already.
The structure tree is not brought: imported pages are untagged.
func (*Editor) MissingGlyphs ¶ added in v0.9.0
MissingGlyphs returns the fields, among those whose values SetFields recorded, with characters in the value that cera has no font for: neither the field's font nor Helvetica, the fallback fonts (Latin, Greek and Cyrillic) or the fonts the document's FontProvider has for Chinese, Japanese and Korean. The value is written whole, but its appearance, in the file and on a flattened page, shows '?' in place of such a character. Written as a field, the form gets /NeedAppearances, so that a viewer with a font for it draws the value itself.
func (*Editor) MovePage ¶ added in v0.7.0
MovePage moves the page at index from so that it is at index to.
func (*Editor) Outline ¶ added in v0.10.0
func (e *Editor) Outline() []OutlineItem
Outline returns the outline of the result as it stands: the one Editor.SetOutline set, or that of the edited document. The targets name pages of the result; an entry whose page is no longer there has none. Changed and given back to SetOutline, it is the outline with those changes and nothing else lost.
func (*Editor) PruneOutline ¶ added in v0.10.0
func (e *Editor) PruneOutline()
PruneOutline leaves the entries out of the outline that led to a page which is not in the result — after Editor.DeletePages, or in a result made of some pages of a document. An entry with entries below it that still lead somewhere stays, as their heading. It holds for the outline as it is written, whatever is deleted afterwards.
func (*Editor) Redact ¶ added in v0.10.0
Redact removes what page i of the result, a page of the edited document, has in the areas, which are in points of the displayed page: the glyphs, paths and images drawn there, also by form XObjects and in layers that are hidden, and the annotations, links and form fields that reach into them. With a fill, boxes of that colour are drawn over the areas.
The content is taken out when the file is written, and it is written anew: Editor.Save writes what is left and nothing of what was there, while Editor.Update, which keeps the bytes of the file, returns ErrNoUpdate. Save returns ErrRedaction when the content of the page cannot be rewritten.
What a redaction takes out besides: /ActualText, /Alt and /E of the marked content and of the structure elements the removed content belongs to, and the thumbnail of the page. What it leaves, for the caller to look at: the outline, whose titles may quote a heading; the metadata; attachments; other pages. A path that reaches into an area is clipped, not cut: its numbers stay in the file. Of a tiling pattern or a soft mask the cells are not rewritten; what they paint in an area is clipped away with the path they fill.
Fields that reach into an area are removed as Editor.RemoveField removes them, and Redact returns what that returns: ErrCertified, ErrLocked. Drawings on the same page (Editor.Draw) are made after the file is written.
func (*Editor) RemoveAnnotation ¶ added in v0.9.0
RemoveAnnotation removes the annotation with the given Index from page i of the result, with its popup and with the annotations that reply to it. A widget of the form is not removed this way.
func (*Editor) RemoveField ¶ added in v0.10.0
RemoveField removes the field with the fully qualified name, with its widgets: one of the edited document, or one added with AddField. It returns ErrLocked for a field a signature locks and ErrCertified for a document whose certification allows no such change. The nodes above the field stay, also when it was their last.
func (*Editor) ResizePage ¶ added in v0.10.0
ResizePage makes page i a page of width by height points, as it is displayed: what it shows — its CropBox — is put on the new page as fit says, and nothing else of it. Its annotations move with the content, and so do its BleedBox, TrimBox and ArtBox where it has them; the MediaBox and the CropBox are the new page. A Letter page becomes an A4 page with ResizePage(i, 595.28, 841.89, FitInside).
The content is not rewritten: it becomes a form XObject that the page draws through a matrix, so that patterns, which a matrix in front of the content would leave where they were, move with what they fill. The content of a tagged page stays the page's, behind a matrix, so that the structure tree still finds what it names — unless the page paints with patterns: then it is a form like the others, and its structure elements no longer lead to their content. What lay outside the CropBox is still in the file and no longer shown. Destinations that name a place on the page by coordinates — of links, of the outline — are not moved; they are off by what the page was scaled. The text of form fields keeps its size in a rectangle that changed, and borders their width.
It changes the page as it is written; see Editor.SetPageBox. Calls follow each other: a page resized twice is fitted twice.
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. An encrypted document stays encrypted, with its passwords and permissions: use Editor.SaveWith to change that. A signed document is refused with ErrSigned: a new file invalidates its signatures, and Editor.Update keeps them. A document whose embedded files alone are encrypted is refused with ErrPassword unless it was opened with the password. The editor may be saved again. Nothing is written when Save fails, but for an error of w itself.
func (*Editor) SaveWith ¶ added in v0.10.0
func (e *Editor) SaveWith(w io.Writer, opt SaveOptions) (err error)
SaveWith is Save with options: to protect the file with passwords and permissions, or to write an encrypted document plain. Either changes the protection of an encrypted document, which needs the owner password: ErrNotPermitted for a document opened with the user password. Pages imported from other documents are encrypted, or not, as the result is.
func (*Editor) SetAnnotation ¶ added in v0.9.0
func (e *Editor) SetAnnotation(i, index int, a NewAnnotation) error
SetAnnotation makes the annotation with the given Index on page i of the result what a describes: its text, colours, geometry, state. The type stays what it is. What a does not describe — entries cera does not read — stays in the annotation; its appearance is made anew. Take a from Page.EditAnnotation to change one thing and keep the rest.
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. Fields calculated and formatted by scripts cera recognises (Field.Computed) are written as the state calculated them, shown in their format; those with other scripts (Field.HasActions) are not computed again: cera runs no JavaScript. See Editor.MissingGlyphs for values with characters that cannot be drawn.
func (*Editor) SetMetadata ¶ added in v0.10.0
SetMetadata records the metadata of the result, written by Save and Update into /Info and into the XMP stream, so that both say the same: title, author, subject, keywords, creator, producer, the dates and /Trapped; empty fields and zero dates are left out, and removed where the document had them. Custom are the other entries of /Info, as strings.
The XMP packet is m.XMP, or the one the edited document has when m.XMP is nil — as it is in what Document.Metadata returns for a document without one —, with the properties that mirror /Info changed and what else it holds kept; a new packet is made when there is none.
It returns ErrCertified for a document certified for no changes.
func (*Editor) SetOutline ¶ added in v0.10.0
func (e *Editor) SetOutline(items []OutlineItem) error
SetOutline makes items the outline of the result, in place of the one the edited document has; none makes a result without an outline. A Target names a page of the result as it is now and stays with that page when pages are moved afterwards; when the page is deleted the entry leads nowhere, or goes with Editor.PruneOutline. Besides pages, an entry may lead to an address (URI), a named destination, another file, or do one of the named actions; an action cera only reports cannot be made anew.
Entries taken from Editor.Outline or from the outline of the edited document, with the target they had, are written as the document has them. The outlines that Editor.ImportPagesWith brings are not added to an outline that is set: it is the whole outline.
func (*Editor) SetPageBox ¶ added in v0.10.0
SetPageBox sets a box of page i to r, in default user space, as Page.Boxes has them: the CropBox to show and print less of a page, or more; the MediaBox to change the medium; the boxes of a page for print. The content of the page stays where it is. A box other than the MediaBox has to have an area within it — a reader clips it to that.
Like Editor.ResizePage, it changes the page as it is written: the other calls of this editor — Draw, the annotations, a redaction — go on speaking of the page as its document shows it.
func (*Editor) SetPageLabels ¶ added in v0.10.0
func (e *Editor) SetPageLabels(ranges []LabelRange) error
SetPageLabels labels the pages of the result: each range the pages from its Start to the next one. Pages before the first range are numbered 1, 2, 3; no ranges make a result without page labels. The ranges are of the pages as they are when the result is written, by their place: set them when the pages are in order. Without it the result keeps the labels its pages have, with the pages.
func (*Editor) Sign ¶ added in v0.10.0
func (e *Editor) Sign(w io.Writer, opt SignOptions) (err error)
Sign writes the edited document's file to w with an update that holds the changes of the editor, as Editor.Update writes them, and a signature over all of it: an approval signature, or with SignOptions.Certify a certification. Signatures the document has stay valid. The signature is a PAdES baseline signature (B-B, ETSI.CAdES.detached) without a timestamp: its time is the signer's word.
The pages cannot change with a signature: an editor that deleted, moved, turned, imported or drew on pages, or flattens the form, is written with Update first, and the result signed. Sign returns the errors of Update, ErrCertified for a document whose certification allows no changes, ErrLocked for a field a signature locks, and ErrSignatureRoom. The file is held in memory while it is signed, and nothing is written when Sign fails, but for an error of w itself.
To go on after signing, open what was written: the editor still edits the document as it was.
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, of their boxes and size, of the outline and the page labels, drawings on the pages and flattened annotations 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 Encryption ¶ added in v0.10.0
type Encryption struct {
// UserPassword opens the file with the permissions below; it may be
// empty, for a file anyone opens and no one may change.
UserPassword string
// OwnerPassword opens it with all permissions, and is needed to
// remove or change the protection. When empty the file gets a random
// one that nobody knows.
OwnerPassword string
// Permissions are what a reader with the user password may do.
Permissions Permissions
}
Encryption protects a file the editor writes: with AES-256 (PDF 2.0), under a file key of its own.
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) that cera does not run: what they compute does not
// update. It is false for a Computed field.
HasActions bool
// Computed reports a field whose scripts cera does without running
// them, because each is a call of one of the functions Acrobat's form
// editor writes: the field is formatted ([Field.Format]), validated
// and calculated by [FormState.SetValue] as they say.
Computed bool
Widgets []*Widget
// contains filtered or unexported fields
}
Field is a terminal field of a form.
func (*Field) Format ¶ added in v0.10.0
Format returns the text the field shows for v: a text formatted as the format of the field says — a number with separators and a currency, a date, a phone number — where the field has a format cera does (Field.Computed) and the text is of its kind; else the text of v. The value stays what it is: the format is how it is shown, in the appearances cera generates and writes, and in a toolkit's widget while it is not being edited.
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 FieldLock ¶ added in v0.10.0
type FieldLock struct {
// Action is "All" for every field, "Include" for those of Fields and
// "Exclude" for all but those.
Action string
// Fields are fully qualified field names.
Fields []string
}
FieldLock names the fields a signature locks (PDF 2.0, 12.7.5.5).
type FieldType ¶
type FieldType uint8
FieldType is the kind of a form field.
type Fit ¶ added in v0.10.0
type Fit int
Fit says how Editor.ResizePage puts what a page shows on the page of another size.
const ( // FitInside scales it, its proportions kept, to lie within the new // page, in its middle: a Letter page on A4 keeps margins left and // right. FitInside Fit = iota // FitFill scales it, its proportions kept, to cover the new page, in // its middle: what hangs over two of the edges is cut off. FitFill // FitStretch scales it to the new page in each direction. FitStretch // FitNone does not scale it: it lies in the middle of the new page, // with a margin around it or cut off by the edges. FitNone )
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 FontProviders ¶ added in v0.10.0
type FontProviders []FontProvider
FontProviders asks several providers in their order: the first that has a font for a request supplies it. The fonts of the machine before the fonts a program brings along:
cera.FontProviders{system.New(), cjk.Provider{japan1.Collection}}
func (FontProviders) Font ¶ added in v0.10.0
func (p FontProviders) Font(req FontRequest) ([]byte, bool)
Font implements FontProvider.
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 FormDataError ¶ added in v0.10.0
type FormDataError struct {
// Unknown are the names of fields the data has values for and the
// form does not have.
Unknown []string
// Refused says, a field each, why the form does not take its value:
// errors that wrap [ErrReadOnly] or [ErrInvalidValue] and name the
// field.
Refused []error
}
FormDataError reports what an import of form data could not do. The rest of the data is set.
func (*FormDataError) Error ¶ added in v0.10.0
func (e *FormDataError) Error() string
func (*FormDataError) Unwrap ¶ added in v0.10.0
func (e *FormDataError) Unwrap() []error
Unwrap returns the errors of the values refused.
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) Do ¶ added in v0.10.0
func (s *FormState) Do(a WidgetAction) bool
Do carries out an action that changes the state: ResetForm sets the fields it names to their default values, and Hide shows or hides widgets, which renders with the state and a FormLayer obey. It reports whether the action was one of them; the others are the viewer's: where to go (Target), what to send (FormState.Submission), a script it may know.
func (*FormState) ExportFDF ¶ added in v0.10.0
ExportFDF writes the values of the state as FDF: of every field that has one, by its name, but for password fields. The state of a check box or radio button is written as a name, text as a string, the options selected in a choice field by their export values.
func (*FormState) ExportXFDF ¶ added in v0.10.0
ExportXFDF writes the values of the state as XFDF, as ExportFDF writes them as FDF.
func (*FormState) Hidden ¶ added in v0.10.0
Hidden reports whether the widget is hidden: as the state says where a Hide action or SetHidden said so, else as the document does (AnnotHidden).
func (*FormState) ImportFDF ¶ added in v0.10.0
ImportFDF sets the fields of the state to the values FDF data has for them, by their names; fields the data does not name stay as they are. A value is set as FormState.SetValue sets it, so the form checks it, calculated fields follow and subscribers are told. Rich text (/RV) is dropped for the plain value beside it; what else FDF may hold — annotations, pages, scripts — is not read.
It returns a *FormDataError when the data names fields the form does not have, or has values the form does not take, after setting the others; and another error, with nothing set, for data that is not FDF or is larger than cera reads (docs/budgets.md).
func (*FormState) ImportXFDF ¶ added in v0.10.0
ImportXFDF is ImportFDF for XFDF data; rich text (value-richtext) is dropped.
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) ResetFields ¶ added in v0.10.0
ResetFields sets the fields to their default values (/DV), or to empty if they have none, as Reset does for all, and calls subscribers for those that change.
func (*FormState) SetHidden ¶ added in v0.10.0
SetHidden hides the widget or shows it, in renders with the state and in a FormLayer, and calls subscribers with its field when that changes what is shown. The document is not changed, and Editor.SetFields does not write it.
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.
func (*FormState) Submission ¶ added in v0.10.0
func (s *FormState) Submission(a WidgetAction) (body []byte, contentType string, err error)
Submission returns what a SubmitForm action sends, for the viewer to send to a.URL if it will: the values of the fields the action names as FDF, as XFDF, or as an HTML form sends them (contentType "application/x-www-form-urlencoded"; with a.Get they belong into the query of the address). Fields flagged FfNoExport are left out, and fields without a value unless the action asks for them. cera sends nothing. It returns ErrSubmitDocument for the format "PDF".
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
// View is the rotation and Box the box of the view the quads are
// given in, as for [NewAnnotation].
View int
Box PageBox
}
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 ImportOptions ¶ added in v0.10.0
type ImportOptions struct {
// Outline brings the entries of the source's outline that lead to an
// imported page, with the entries above them. They follow the entries
// the result has, under an entry titled OutlineTitle, or at the top
// level when that is empty.
Outline bool
OutlineTitle string
// Destinations brings the source's named destinations on imported
// pages, so that links into the file by name still arrive; a name
// the result has is renamed name_2, name_3 and so on, as field names
// are. (Links between imported pages are kept either way.)
Destinations bool
// Labels keeps the page labels of the imported pages: the numbers
// printed on them.
Labels bool
}
ImportOptions say what imported pages bring from their document besides what is on them, so that merging documents does not make them worse.
type LabelRange ¶ added in v0.10.0
type LabelRange struct {
// Start is the index of the first page of the range.
Start int
Style LabelStyle
Prefix string
// First is the number of the page at Start: 1 or more, and 1 for 0.
First int
}
LabelRange labels the pages from Start on, up to the next range: with Prefix and then a number in Style that counts on from First.
type LabelStyle ¶ added in v0.10.0
type LabelStyle byte
LabelStyle is how the pages of a LabelRange are numbered.
const ( LabelNone LabelStyle = 0 // no number: the prefix alone LabelDecimal LabelStyle = 'D' // 1, 2, 3 LabelRomanUpper LabelStyle = 'R' // I, II, III LabelRomanLower LabelStyle = 'r' // i, ii, iii LabelLetterUpper LabelStyle = 'A' // A to Z, then AA to ZZ LabelLetterLower LabelStyle = 'a' // a to z, then aa to zz )
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 is the address of a URI action, resolved against the base the
// document names for its relative addresses (/URI /Base).
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, to a
// file embedded in this or another one (/GoToE, see Embedded), or to
// a file or application (/Launch). File names it. cera follows none
// of them, and a viewer should ask before it does.
External bool
File string
// Embedded is the way to the target of a /GoToE action, from File,
// or from this document when File is empty: the names of embedded
// files, each inside the one before, ".." for the file a file is
// embedded in.
Embedded []string
// Action is the type of the action the target was read from: "GoTo",
// "GoToR", "GoToE", "Launch", "URI", "Named", or one cera only
// reports, so that a viewer can say that the link does something it
// will not run: "JavaScript", "SubmitForm", "ResetForm", "Hide", ...
// It is empty for a destination (/Dest). Of chained actions (/Next)
// the target is the first that leads somewhere.
Action string
// NamedAction is the name of a Named action: "NextPage", "PrevPage",
// "FirstPage" and "LastPage", which [LinkTarget.NamedPage] resolves,
// or one a viewer may know ("Print", "GoBack", "Find", ...).
NamedAction string
// IsMap reports a URI the viewer is to add the place of the click to,
// as "?x,y" (/IsMap).
IsMap bool
}
LinkTarget is where a link goes: a URI, a place in the document or in another file, or what else it does.
func (*LinkTarget) NamedPage ¶ added in v0.10.0
func (t *LinkTarget) NamedPage(current, n int) (int, bool)
NamedPage returns the page a Named action leads to from page current of a document of n pages. It reports false for other targets, for names other than NextPage, PrevPage, FirstPage and LastPage, and where there is no such page.
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 Markup ¶ added in v0.9.0
type Markup struct {
// Author is the text of the title bar of the popup, by convention
// who made the annotation (/T), Subject what it is about (/Subj).
Author string
Subject string
// Created and Modified are zero when the annotation does not say.
Created time.Time
Modified time.Time
// RichText is the text of the annotation as XHTML (/RC), raw as the
// file holds it; Annotation.Contents is its plain form.
RichText string
// Intent is what the annotation is meant as when its type leaves
// that open (/IT): "FreeTextCallout", "LineArrow", "PolygonCloud", ...
Intent string
// Color is the colour (/C) and Interior that of the inside of a shape
// and of line endings (/IC): gray, RGB or CMYK components from 0 to
// 1, nil when the annotation gives none (for Interior: not filled).
Color []float64
Interior []float64
// Opacity is the constant opacity from 0 to 1 (/CA), 1 by default.
Opacity float64
// BorderWidth is the width of the lines in points, 1 by default,
// BorderStyle their style and Dash the dash pattern of a dashed one.
BorderWidth float64
BorderStyle BorderStyle
Dash []float64
// Bounds is the rectangle of the annotation (Annotation.Rect).
Bounds Rect
// Quads are the areas of text a Highlight, Underline, Squiggly,
// StrikeOut or Redact annotation marks, corners in /QuadPoints order;
// the rectangle when the annotation has none that hold.
Quads []Quad
// Ink are the strokes of an Ink annotation, each a path of points.
Ink [][][2]float64
// Vertices are the corners of a Polygon or PolyLine annotation.
Vertices [][2]float64
// Line is the start and end of a Line annotation, nil for others.
Line [][2]float64
// LineEndings are the styles of the ends of a Line or PolyLine and
// of the callout of a FreeText annotation, which has only the first
// (/LE): "None", "OpenArrow", "ClosedArrow", "Circle", ...
LineEndings [2]string
// Callout is the callout line of a FreeText annotation (/CL), two or
// three points from the end at the place it points to.
Callout [][2]float64
// Popup is the window that shows the text, nil for none.
Popup *Popup
// Reply names the annotation this one replies to (/IRT), nil for
// none.
Reply *Reply
// State and StateModel are the review state a reply sets on the
// annotation it replies to: "Accepted" of "Review", "Marked" of
// "Marked", ...
State string
StateModel string
// Icon names the icon of a Text, Stamp, FileAttachment or Sound
// annotation (/Name): "Note", "Comment", "Approved", "PushPin", ...
Icon string
// DefaultAppearance is the font, size and colour of the text of a
// FreeText annotation as content operators (/DA), and Align how its
// text is aligned (/Q).
DefaultAppearance string
Align Align
}
Markup describes a markup annotation beyond its type, rectangle and text. Geometry is in points of the displayed page, as the quads of Link and of PageText are, with y down.
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 NewAnnotation ¶ added in v0.9.0
type NewAnnotation struct {
Subtype string
// Contents is the text of the annotation: of a note, of a free text,
// or a comment on what another type marks. A note, and any other
// annotation with a comment but a free text, gets a popup window.
Contents string
// Name identifies the annotation on its page (/NM).
Name string
// Flags are the flags of the annotation; zero stands for AnnotPrint,
// and for a note also AnnotNoZoom and AnnotNoRotate, which keep its
// icon the same size and upright.
Flags AnnotFlags
// Link is where a "Link" leads: a URI, a page of the edited document
// with a view, a named destination, another file (/GoToR, /Launch) or
// a Named action. A link of the document keeps its action as it is
// while Link is what it was read as, and whenever cera cannot write
// the action: JavaScript, /GoToE, ...
Link *LinkTarget
// View is the rotation of the view the geometry is given in, in
// degrees: what [Page.Rotated] was called with for the page the user
// sees, 0 for the page as the file turns it. EditAnnotation sets it.
View int
// Box is the box of the view the geometry is given in, as
// [Page.InBox] shows it: BoxCrop for the page as the document shows
// it. EditAnnotation sets it.
Box PageBox
Markup
}
NewAnnotation describes an annotation to add to a page, or what an annotation of the page becomes. Its Markup holds what Annotation.Markup reads back, with geometry in points of the displayed page; which of its fields a type uses is said there.
The types that can be written, with the geometry they need:
- "Text", a sticky note, "FreeText", "Square", "Circle", "Caret" and "Stamp" (Icon, a standard stamp name, "Draft" by default): Bounds;
- "Highlight", "Underline", "Squiggly", "StrikeOut": Quads;
- "Ink": Ink; "Polygon", "PolyLine": Vertices; "Line": Line;
- "Link": Bounds or Quads, and Link, where it leads.
A shape needs a border or an interior colour to show. A zero Opacity means opaque.
type NewField ¶ added in v0.10.0
type NewField struct {
// Name is the fully qualified name: "street", or "address.street" for
// a field below a node "address", which is made if the form has none.
// The name of a field the document has, or of one added before, adds a
// widget to that field: another button of a radio group, or the same
// field shown in another place. What describes the field — all but
// OnState and Look — is then that field's and is ignored here.
Name string
// Type is FieldText (the zero value), FieldCheckBox, FieldRadio,
// FieldComboBox, FieldListBox, FieldPushButton or FieldSignature.
Type FieldType
// Flags are the flags of the field: FfReadOnly, FfRequired,
// FfMultiline, FfPassword, FfComb, FfEdit, FfMultiSelect and the
// others. Those that say the type (FfRadio, FfPushbutton, FfCombo)
// follow Type.
Flags FieldFlags
// Alt is the description of the field for a user who does not see it,
// and the tooltip (/TU).
Alt string
// Value is the value the field starts with: a TextValue, a
// ChoiceValue of Options, or for a check box or a radio group the
// StateValue of the OnState of the widget that is on.
Value Value
// Options are the entries of a choice field.
Options []Option
// MaxLen is the most characters of a text field, 0 for any number.
MaxLen int
// OnState is the state of this widget of a check box or radio button
// when it is on, the value the field then has: "Yes" where empty, and
// for the buttons of a radio group, which need one each, "1", "2" and
// on.
OnState string
// Look is how the widget is drawn. The zero Appearance is black text
// in Helvetica of a size that fits, with no border and no background;
// FontName is not used.
Look Appearance
}
NewField describes a form field for Editor.AddField, or one more widget of a field.
type ObjectStreamMode ¶ added in v0.10.0
type ObjectStreamMode int
ObjectStreamMode says whether a file is written with object streams; see SaveOptions.ObjectStreams.
const ( // ObjectStreamsAsSource packs the objects of a document that was // packed, and of no other. ObjectStreamsAsSource ObjectStreamMode = iota // ObjectStreamsAlways packs them: the smallest file, which readers // from before PDF 1.5 (2003) do not read. ObjectStreamsAlways // ObjectStreamsNever writes every object on its own, with a // cross-reference table. ObjectStreamsNever )
type OpenOptions ¶
type OpenOptions struct {
// Password opens an encrypted document: its user password, or the
// owner password, which lifts the restrictions of
// [Document.Permissions]. The empty password is tried when none is
// given; [ErrPassword] says that the document needs another.
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
// and over the document's output intent.
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. It takes
// precedence over the document's output intent.
CMYKProfile []byte
// IgnoreOutputIntent converts DeviceCMYK through the bundled profile
// also in a document that names the printing condition its device
// colours are meant for. Without it, DeviceCMYK is converted through
// the CMYK profile of the document's output intent (/OutputIntents of
// the catalogue: PDF/X, PDF/A, PDF/E), as Acrobat and MuPDF do: a file
// made for uncoated paper or for newsprint is shown with those
// colours. PDFium does not use output intents.
IgnoreOutputIntent bool
// ImageCacheBytes bounds the decoded images the document keeps for
// the next page that shows them: 0 means 256 MB, a negative number
// none, for a thumbnailer that draws each page once. An image larger
// than the bound is decoded for each page that is recorded with it.
ImageCacheBytes int64
// StreamCacheBytes bounds the decoded streams the document keeps —
// the content of pages, forms, Type 3 glyphs, functions: 0 means
// 64 MB, a negative number none.
StreamCacheBytes int64
// Cache, if set, keeps the decoded images and streams of the document
// with those of the other documents opened with it, under its one
// bound; ImageCacheBytes and StreamCacheBytes are ignored. See
// [NewCache].
Cache *Cache
}
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 OutlineItem ¶ added in v0.9.0
type OutlineItem struct {
Title string
// Target is where the entry leads, as for a link: resolve it with
// [Document.Destination]. An entry that names a structure element
// and no destination leads to the page of the element. Target is nil
// for an entry without destination and action, a heading of its
// children; an action cera does not follow is reported by its type
// ([LinkTarget.Action]).
Target *LinkTarget
// Open says that the children are shown when the outline is first
// displayed.
Open bool
// Bold and Italic are the style of the title, Color its colour,
// black by default.
Bold, Italic bool
Color color.RGBA
Children []OutlineItem
// contains filtered or unexported fields
}
OutlineItem is an entry of the document outline.
type Page ¶
type Page struct {
// Box is the visible area in default user space: CropBox clipped to
// MediaBox, or for a page made by InBox the box it shows. Its units
// are /UserUnit points; Size and DisplayMatrix apply it.
Box Rect
// Rotate is the clockwise display rotation: 0, 90, 180 or 270, the
// /Rotate of the page and what Rotated added to it. It is for
// reading: a page is rendered, measured and cached as it was made, so
// setting Rotate after its first use draws one rotation in the size
// of another. Use Rotated for another rotation.
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.
A viewer that turns its view uses Page.Rotated: the page as it is shown is then a Page of its own, and everything given in points of the displayed page — Bounds, Render, the text, links, annotations — is in its coordinates.
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) Boxes ¶ added in v0.10.0
Boxes returns the boxes of the page. They are in default user space whatever the page shows; Page.DisplayMatrix maps them to points of the displayed page, where a viewer of print files outlines them.
func (*Page) Destination ¶ added in v0.10.0
func (p *Page) Destination(t *LinkTarget) (Destination, bool)
Destination resolves t, a target on this page, to a view of it in the points of the page as it is displayed — turned, for a page made by Page.Rotated. It reports false for a target that is not on the page.
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) EditAnnotation ¶ added in v0.9.0
func (p *Page) EditAnnotation(index int) (NewAnnotation, bool)
EditAnnotation returns the annotation of the page with the given Index as Editor.SetAnnotation takes it, to change what should change. It reports false for an annotation the editor cannot write: a widget, a popup, which is changed through its annotation, and types beyond those of NewAnnotation.
func (*Page) InBox ¶ added in v0.10.0
InBox returns the page showing another of its boxes than the CropBox: the MediaBox with the marks around a page for print, or the TrimBox for a thumbnail of the finished page. It is a view of the page as Page.Rotated makes one, with Box, Size, Bounds and DisplayMatrix of that box; the two combine, in either order. Render draws what is inside the box, and "points of the displayed page" have their origin at its corner. InBox(BoxCrop) is the page as the document shows it.
APIs that take a page number ask for the box as they do for the rotation: TextIndex.SetBox, NewAnnotation.Box, Highlight.Box.
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, and those of the views Rotated and InBox made of the page. 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) RenderGray ¶ added in v0.10.0
RenderGray draws the page into dst as Page.Render does, in grey: for a monochrome printer, a fax, text recognition. dst has the pixel coordinates Render's has, and opt means what it means there; where the background is not opaque the page is drawn on white.
The page is drawn in colour, a band of it at a time, and each band is converted as PDF converts DeviceRGB to DeviceGray (PDF 2.0, 10.4.2.2: 0.3 R + 0.59 G + 0.11 B, here with the weights of color.GrayModel) — the pixels Render draws into tiles of that size, converted, without holding the page in colour: a page of 100 megapixels takes 100 MB and not 500.
func (*Page) Rotated ¶ added in v0.10.0
Rotated returns the page viewed turned by degrees more, clockwise: a multiple of 90, others are rounded to one. It is the page itself for a multiple of 360, and else a view of it — a Page with Rotate turned, its own bounds, display list and text, and the same content. Asked for again, the same view is returned, so what it cached is still there; Release on the page frees the views' lists too.
"Points of the displayed page" are those of the view everywhere: of what Render draws, of PageText, of links, Annotation.Markup and Page.EditAnnotation, whose result Editor.SetAnnotation takes back with its view. APIs that take a page number ask for the view where it matters: Page.Destination, TextIndex.SetRotation, NewAnnotation.View, Highlight.View.
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 PageBox ¶ added in v0.10.0
type PageBox int
PageBox names one of the boxes of a page.
const ( BoxCrop PageBox = iota // what a viewer shows and a printer prints; the default BoxMedia // the medium the page is printed on, with all its marks BoxBleed // what is printed and then cut off around the trimmed page BoxTrim // the finished page, after trimming BoxArt // the content its author means, as for placing the page in another )
type PageBoxes ¶ added in v0.10.0
type PageBoxes struct{ Media, Crop, Bleed, Trim, Art Rect }
PageBoxes are the boxes of a page in default user space, as Box is, each clipped to the MediaBox, with the defaults of the specification for one the page does not have or has no area of within the MediaBox: Crop is then Media, and Bleed, Trim and Art are Crop.
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. Right-to-left text is
// in logical order too, the order it is read and typed in, with the
// letters its presentation forms stand for; on the page the character
// after one of its characters stands left of it.
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. Places that share characters, as two in the text of one /ActualText do, are one place, the first.
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. Where the direction of the text changes within the range a new box starts, since what follows in the range need not stand beside what came before: a line with right-to-left and left-to-right text has one box for each stretch.
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 Permissions ¶ added in v0.9.0
type Permissions uint32
Permissions are what the author of an encrypted document allows a reader that opened it with the user password (PDF 2.0, table 22).
const ( // PermPrint allows printing; without PermPrintFaithful only in a // quality that does not serve as a copy of the document. PermPrint Permissions = 1 << 2 // PermModify allows changing the content of the document. PermModify Permissions = 1 << 3 // PermCopy allows copying text and graphics out of the document. PermCopy Permissions = 1 << 4 // PermAnnotate allows adding and changing annotations, and filling // in form fields. PermAnnotate Permissions = 1 << 5 // PermFillForms allows filling in form fields, also without // PermAnnotate. PermFillForms Permissions = 1 << 8 // PermExtract allowed extracting text and graphics for accessibility; // PDF 2.0 deprecates it and always allows that. PermExtract Permissions = 1 << 9 // PermAssemble allows inserting, deleting and rotating pages, also // without PermModify. PermAssemble Permissions = 1 << 10 // PermPrintFaithful allows printing in full quality. PermPrintFaithful Permissions = 1 << 11 // AllPermissions is every permission. AllPermissions = PermPrint | PermModify | PermCopy | PermAnnotate | PermFillForms | PermExtract | PermAssemble | PermPrintFaithful )
The permissions of an encrypted document.
type PoolLimits ¶ added in v0.10.0
type PoolLimits struct {
// GlyphCaches is how many glyph mask caches of idle renderers are
// kept, each of up to 4 MB: 0 means 64, a negative number none. A
// render takes one per goroutine that draws.
GlyphCaches int
// LayerBytes bounds the buffers of transparency groups and soft masks
// a raster device keeps for its next group: 0 means 64 MB, a negative
// number none.
LayerBytes int64
}
PoolLimits bound what the process keeps between renders for the next one, whatever the document.
type Popup ¶ added in v0.9.0
type Popup struct {
// Index is the Index of the popup annotation.
Index int
// Bounds is its rectangle in points of the displayed page.
Bounds Rect
// Open says that the window is shown.
Open bool
}
Popup is the popup window of a markup annotation.
type PrintSettings ¶ added in v0.10.0
type PrintSettings struct {
// Scaling is "AppDefault" (the viewer's scaling, the default) or
// "None" (no scaling to the paper).
Scaling string
// Duplex is "Simplex", "DuplexFlipShortEdge" or "DuplexFlipLongEdge",
// empty if the document does not say.
Duplex string
// PickTrayByPDFSize says that the paper tray is chosen by the size of
// the page.
PickTrayByPDFSize bool
// Ranges are the pages to print, each a first and a last page,
// 0-based and inclusive; nil for all pages.
Ranges [][2]int
// Copies is the number of copies, 1 by default.
Copies int
}
PrintSettings is what a document asks its print dialogue to start with.
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
// LinkBorders draws the border of a link annotation that has one
// (/Border, /BS) and no appearance stream, in its colour (/C): the
// boxes LaTeX's hyperref puts around links, for one. Acrobat and
// pdf.js draw them on screen; PDFium, MuPDF and Preview do not, and
// neither does cera unless this is set. Changing it does not
// interpret the page again.
LinkBorders 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 Reply ¶ added in v0.9.0
type Reply struct {
// To is the Index of the annotation replied to.
To int
// Group says that the annotation is a part of that one rather than
// a reply to it (/RT /Group): viewers show both as one.
Group bool
}
Reply is the relation of a markup annotation to another one of its page.
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, SkipAnnotation and LinkBorders select the annotations,
// as for RenderOptions. A TextDevice sees the text of their
// appearances.
Annotations AnnotMode
SkipAnnotation func(index int) bool
LinkBorders 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 SaveOptions ¶ added in v0.10.0
type SaveOptions struct {
// Encrypt, when set, encrypts the file anew.
Encrypt *Encryption
// Decrypt writes the file of an encrypted document without its
// protection.
Decrypt bool
// ObjectStreams says whether the file is written in the compact form
// of PDF 1.5: the objects that are not streams packed into object
// streams, compressed, with a cross-reference stream. A form with
// thousands of small objects is a tenth smaller for it. The zero
// value, ObjectStreamsAsSource, writes the edited document as it was
// read, and a new document in the classic form.
ObjectStreams ObjectStreamMode
// Linearize lays the file out for a reader that gets it piece by
// piece ("fast web view"; PDF 2.0, Annex F): what the first page needs
// comes first, and a table of hints says where the other pages are, so
// that a viewer shows a page before the rest of the file has arrived.
// The whole file is laid out in memory before any of it is written. An
// update appended later (Editor.Update) makes it an ordinary file
// again.
Linearize bool
// PruneResources writes with every page the resources its content
// names and no others, and likewise with the form XObjects, tiling
// patterns and Type 3 fonts that content draws. A resource dictionary
// that all pages share keeps every font and image of the document
// with every page: after DeletePages, or in a file made of some pages
// of another, what only the other pages drew is then left out. A page
// whose content cannot be read to the end keeps what it has.
PruneResources bool
// JoinDuplicates writes streams that are the same — an image or a
// font program embedded once for every page it is on — and the fonts
// of the same program once, also those of different documents.
JoinDuplicates bool
// Compress stores the streams that the document has plain, or under a
// filter that packs worse (LZW, run length, ASCII85, ASCIIHex), with
// the Flate filter where that is shorter. Metadata streams stay plain.
Compress bool
// Drop names parts of the document that are left out.
Drop Drop
}
SaveOptions say how Editor.SaveWith writes the file.
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 Sheet ¶ added in v0.10.0
Sheet says how Editor.AddSheets puts pages on sheets: Columns by Rows of them on a sheet of Width by Height points, with a Margin around the sheet and a Gap between the pages.
type SignOptions ¶ added in v0.10.0
type SignOptions struct {
// Key signs, and Certificate is its certificate. The key is an RSA or
// an ECDSA key behind [crypto.Signer], so that it may be on a token or
// with a signing service; it is asked once, for a signature over a
// SHA-256 digest. Chain are the certificates between Certificate and
// a root, which go into the signature for who checks it.
Key crypto.Signer
Certificate *x509.Certificate
Chain []*x509.Certificate
// Field is the fully qualified name of the signature field to sign,
// one of the document that is not signed yet, or the name of a new
// one. Empty, a new field is named "Signature1", or by the first
// number that is free.
Field string
// Page and Rect place a new field: Rect is where it shows on Page, in
// points of the displayed page. With the zero Rect the signature is
// invisible. An existing field stays where it is.
Page int
Rect Rect
// Appearance draws what the field shows, on a canvas of the size of
// its rectangle; nil, or for an invisible signature, nothing is drawn.
// A signed field shows the same to everyone: whether the signature
// holds is for a viewer to say, beside the page.
Appearance func(c *Canvas)
// Name is the name of the signer, where the certificate should not
// speak for it; Reason, Location and Contact are what the signer
// states.
Name, Reason, Location, Contact string
// Time is when the signature is made, as the signer claims; the zero
// Time is now.
Time time.Time
// Certify makes a certification signature, the author's, which says
// what may be changed afterwards (DocMDP): 1 nothing, 2 filling in
// forms and signing, 3 also annotating. 0 makes an approval signature.
// A document is certified once, before it is signed.
Certify int
// Lock names the fields that may not change once the signature is
// made; nil locks none.
Lock *FieldLock
}
SignOptions describe a signature Editor.Sign makes.
type Signature ¶ added in v0.10.0
type Signature struct {
// Field is the signature field.
Field *Field
// SubFilter says how the signature is encoded: "adbe.pkcs7.detached",
// "ETSI.CAdES.detached", "adbe.pkcs7.sha1", "adbe.x509.rsa_sha1", or
// "ETSI.RFC3161" for a document timestamp.
SubFilter string
// Signer is the name of the signer: the common name of the signing
// certificate, else its subject, else the name the signature
// dictionary gives (/Name). It is what the file says until Verify
// has checked the signature.
Signer string
// Time is when the signature was made: the time of its timestamp
// token when it has one that holds, else what the signer claims (/M,
// or the signing time in the signature).
Time time.Time
// Reason and Location are what the signer states.
Reason, Location string
// CoversWholeFile reports that the signature covers the file to its
// end: nothing was appended after it.
CoversWholeFile bool
// Certification is the DocMDP permissions of a certification
// signature — 1: no changes, 2: filling in forms and signing, 3: also
// annotating — and 0 for an approval signature.
Certification int
// contains filtered or unexported fields
}
Signature is a signature of a document, in a signature field.
func (*Signature) Verify ¶ added in v0.10.0
func (s *Signature) Verify(opt VerifyOptions) (SignatureStatus, error)
Verify checks the signature: that the bytes it covers are those signed and the signature is its certificate's, what was appended to the file after it, and — with roots in opt — whether the certificate is trusted. It returns ErrSignatureUnsupported for a signature it cannot check; a signature that is checked and does not hold is a status with Intact false, not an error.
type SignatureStatus ¶ added in v0.10.0
type SignatureStatus struct {
// Intact reports that the bytes the signature covers are those that
// were signed, and that the signature is that of the key of
// Certificate. Nothing else of the status means anything without it.
Intact bool
// Changes is what was appended after the signature, and
// ChangesAllowed whether the certification of the document and the
// lock of the signature's field allow it: filling in fields that are
// not locked and signing unless the certification says no changes,
// annotating unless it says forms only. Other changes never are.
Changes Changes
ChangesAllowed bool
// Certificate is the signer's certificate and Certificates all the
// signature carries.
Certificate *x509.Certificate
Certificates []*x509.Certificate
// Trusted reports that Certificate leads to one of the roots of the
// options, valid at the time checked; TrustError says why not.
Trusted bool
TrustError error
// Timestamped reports that Signature.Time is the time of a timestamp
// token, signed by Timestamper, rather than the signer's claim. The
// timestamp authority's own chain is not checked.
Timestamped bool
Timestamper *x509.Certificate
}
SignatureStatus is the result of checking a signature.
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 StructAttr ¶ added in v0.10.0
type StructAttr struct {
// RowSpan and ColSpan are the rows and columns a table cell spans, 1
// by default.
RowSpan, ColSpan int
// Headers are the identifiers of the header cells of a cell; see
// [StructTree.ByID].
Headers []string
// Scope says what a header cell is the header of: "Row", "Column" or
// "Both", and "" where it does not say.
Scope string
// Summary describes a table.
Summary string
// ListNumbering is how the items of a list are labelled: "None" by
// default, "Disc", "Circle", "Square", "Decimal", "UpperRoman",
// "LowerRoman", "UpperAlpha", "LowerAlpha" and others of PDF 2.0.
ListNumbering string
// BBox is the box of a figure, a formula or a table in default user
// space of its page, as [Page.Boxes] are; the zero Rect for none.
BBox Rect
}
StructAttr are the attributes of a structure element that cera reads: those of tables and lists, and the box of a figure.
type StructElem ¶ added in v0.10.0
type StructElem struct {
// Type is the structure type as the document names it (/S), and Role
// the type that stands for: what the role map of the document
// (/RoleMap, and /RoleMapNS of the element's namespace) maps Type to,
// and Type itself where it maps it to nothing. A document may call its
// headings "Heading 1"; their Role is "H1". The standard types are
// those of PDF 2.0, 14.8.4: "Document", "Sect", "H1", "P", "L", "LI",
// "Table", "TR", "TH", "TD", "Figure", "Link" and the others.
Type, Role string
// ID identifies the element in the document (/ID); see
// [StructTree.ByID].
ID string
// Title names the element (/T). Alt describes it for a reader who
// does not see it, as for a figure. ActualText is the text the element
// stands for and is read as, instead of the text of its content.
// Expansion is what an abbreviation is short for (/E).
Title, Alt, ActualText, Expansion string
// Lang is the language of the element ("en-US"): its own /Lang, or
// that of the nearest element above that has one, or the document's.
Lang string
// Page is the page the content of the element is on, its own and that
// of the elements below it, and -1 for content on several pages. An
// element without content is on the page it or one above it names
// (/Pg), or -1.
Page int
// Kids are what the element consists of, in reading order.
Kids []StructKid
// contains filtered or unexported fields
}
StructElem is an element of the structure tree.
func (*StructElem) Attr ¶ added in v0.10.0
func (e *StructElem) Attr() StructAttr
Attr returns the attributes of the element, with their defaults for what it does not say. Do not modify Headers.
func (*StructElem) Children ¶ added in v0.10.0
func (e *StructElem) Children() iter.Seq[*StructElem]
Children returns the elements below e, without its content.
type StructKid ¶ added in v0.10.0
type StructKid struct {
// Elem is the element, nil for content and annotations.
Elem *StructElem
// Page is the page of the content or the annotation, and for an
// element its Page.
Page int
// MCID is the identifier of a marked-content sequence of Page, as in
// [TextChar.MCID] and [MarkedContent.MCID]; -1 for none. Content
// marked in a form XObject, which numbers it on its own, is left out.
MCID int
// Annot is the [Annotation.Index] of an annotation of Page that is
// part of the element, as the annotation of a Link is; -1 for none.
Annot int
}
StructKid is a part of a structure element: an element below it, a sequence of marked content, or an annotation.
type StructTree ¶ added in v0.10.0
type StructTree struct {
// Elems are the elements at the top of the tree, mostly one, a
// Document.
Elems []*StructElem
// Suspects says that the producer is not sure of the tree
// (/MarkInfo /Suspects), which it made by guessing at a layout. cera
// then orders the text of a page by its layout, not by the tree.
Suspects bool
// Truncated says that the tree has more elements or levels than are
// read (docs/budgets.md), so that part of it is missing.
Truncated bool
// contains filtered or unexported fields
}
StructTree is the structure tree of a document.
func (*StructTree) ByID ¶ added in v0.10.0
func (t *StructTree) ByID(id string) *StructElem
ByID returns the element with the identifier id, as the Headers of a table cell name its header cells, and nil for none. Of several elements with one identifier it is the first in the order of the tree.
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.
func (*TextIndex) Page ¶ added in v0.8.0
Page returns the text of page i (0-based). Several callers asking for the same page wait for one layout. When ctx ends before the text is laid out, Page returns its error and keeps nothing.
func (*TextIndex) SetBox ¶ added in v0.10.0
SetBox has every page show the box b, as Page.InBox does: the text, its quads and what Hit takes are then in points of that box. The pages laid out so far are dropped. Call it as SetRotation is called: before the index is used from several goroutines, or between such uses.
func (*TextIndex) SetRotation ¶ added in v0.10.0
SetRotation turns the view of every page by degrees, as Page.Rotated does: the text, its quads and what Hit takes are then in points of the turned pages. The pages laid out so far are dropped. It is for a viewer that turns its view; call it before the index is used from several goroutines, or between such uses.
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
// RTL reports a line that reads from right to left, as most of its
// letters do: its first character is at its right end, at the end of
// Quad along Dir.
RTL bool
// 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 VerifyOptions ¶ added in v0.10.0
type VerifyOptions struct {
// Roots are the certificates the caller trusts. Without them the
// chain is not checked and SignatureStatus.Trusted is false.
Roots *x509.CertPool
// Intermediates are certificates between the signer's and the roots,
// added to those the signature carries.
Intermediates *x509.CertPool
// At is the time the certificates must be valid at; zero for the time
// of the signature (Signature.Time), or now when it has none.
At time.Time
}
VerifyOptions say how to check a signature.
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 ViewSettings ¶ added in v0.10.0
type ViewSettings struct {
// Open is where to start: the page and view of /OpenAction, a
// destination or an action that leads to a place in the document,
// which [Document.Destination] or [LinkTarget.NamedPage] resolves. It
// is nil without one, and for an action that leads elsewhere or runs
// something — a script, an address, another file: nothing a viewer
// should do because a file was opened.
Open *LinkTarget
// PageMode is what is shown with the pages: "UseNone" (nothing, the
// default), "UseOutlines" (the outline), "UseThumbs" (thumbnails),
// "FullScreen", "UseOC" (the layers) or "UseAttachments".
PageMode string
// AfterFullScreen is the PageMode on leaving full screen, for a
// document whose PageMode is "FullScreen": "UseNone" (the default),
// "UseOutlines", "UseThumbs" or "UseOC".
AfterFullScreen string
// PageLayout is how the pages are laid out: "SinglePage" (one at a
// time, the default), "OneColumn" (one column, continuous),
// "TwoColumnLeft" and "TwoColumnRight" (two columns, odd pages on
// that side), "TwoPageLeft" and "TwoPageRight" (two pages at a time).
// The layouts with odd pages on the right start with a cover page.
PageLayout string
// RightToLeft says that the document reads from right to left: the
// pages of a spread run from the right.
RightToLeft bool
// DisplayDocTitle says that the title bar shows the title of the
// document ([Metadata.Title]) rather than the name of its file.
DisplayDocTitle bool
// FitWindow asks for the window to be sized to the first page,
// CenterWindow for it to be centred on the screen.
FitWindow, CenterWindow bool
// HideToolbar, HideMenubar and HideWindowUI ask for the tool bars,
// the menu bar and the scroll bars and navigation controls to be
// hidden.
HideToolbar, HideMenubar, HideWindowUI bool
// Print is what the print dialogue starts with.
Print PrintSettings
}
ViewSettings is how a document asks to be opened and printed: the /OpenAction, /PageMode, /PageLayout and /ViewerPreferences of its catalogue (PDF 2.0, 7.7.2 and 12.2), with the defaults of the specification where the document says nothing or says something else than the specification knows. They are wishes: a viewer follows those that suit it.
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
// Actions are what the widget does when it is activated — a push
// button pressed —, in the order they are to be done (/A and what is
// chained to it); see [WidgetAction] and [FormState.Do].
Actions []WidgetAction
// contains filtered or unexported fields
}
Widget is a widget annotation of a field: where and how the field is shown on a page.
type WidgetAction ¶ added in v0.10.0
type WidgetAction struct {
// Kind is the type of the action: "ResetForm", "Hide", "SubmitForm",
// "ImportData", "JavaScript", or one of those a link has ("GoTo",
// "GoToR", "URI", "Named", "Launch", ...), which Target describes.
Kind string
// Fields are the fully qualified names an action for fields lists:
// those to reset or submit, or with Exclude all but those; of a Hide
// action those whose widgets are shown or hidden. A name may be that
// of a node above fields and stands for them all. No names is every
// field, for ResetForm and SubmitForm.
Fields []string
Exclude bool
// Hide says of a Hide action whether it hides (true) or shows.
Hide bool
// URL is where a SubmitForm action sends, and the file of an
// ImportData action. Format is how: "FDF", "XFDF", "HTML" (the fields
// as an HTML form sends them) or "PDF" (the document itself); Get asks
// for HTTP GET, for HTML alone. Flags are the flags of the action as
// the file has them (PDF 2.0, table 239).
URL string
Format string
Get bool
Flags uint32
// Target is where an action of a link leads; see [LinkTarget].
Target *LinkTarget
// Script is the text of a JavaScript action. cera does not run it.
Script string
// contains filtered or unexported fields
}
WidgetAction is an action of a widget.
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
- annotlook.go
- annotmarkup.go
- annotwrite.go
- attachment.go
- budget.go
- cache.go
- canvas.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
- formaction.go
- formdata.go
- formedit.go
- formflatten.go
- formfont.go
- formgen.go
- formlayer.go
- formscript.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
- metawrite.go
- outline.go
- outlinewrite.go
- pagelabels.go
- pagesize.go
- pattern.go
- protection.go
- quad.go
- redact.go
- render.go
- rendergray.go
- shading.go
- shadingdraw.go
- sign.go
- signature.go
- signing.go
- structtree.go
- structure.go
- text.go
- textbidi.go
- textindex.go
- textlayout.go
- textpage.go
- textsearch.go
- textselect.go
- tiledraw.go
- transparency.go
- type3clip.go
- viewsettings.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. |
|
cms
Package cms reads the signed data of the Cryptographic Message Syntax (RFC 5652, PKCS #7) as far as PDF signatures use it, and checks it: the digest of what was signed against the signed attributes, the signature against the signer's certificate.
|
Package cms reads the signed data of the Cryptographic Message Syntax (RFC 5652, PKCS #7) as far as PDF signatures use it, and checks it: the digest of what was signed against the signed attributes, the signature against the signer's certificate. |
|
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. |