Documentation
¶
Index ¶
- Variables
- func FloatToPoint(in float64) string
- func Serialize(item any) string
- type Annotation
- type Array
- type Dict
- type ExtGState
- type Face
- func (face *Face) AdvanceWidth(glyphID int) float64
- func (face *Face) Codepoint(r rune) int
- func (face *Face) Codepoints(runes []rune) []int
- func (face *Face) CompactSubset() error
- func (face *Face) InternalName() string
- func (face *Face) MapGlyph(oldGID int) int
- func (face *Face) OTFace() *ot.Face
- func (face *Face) RegisterChar(codepoint int)deprecated
- func (face *Face) RegisterChars(codepoints []int)deprecated
- func (face *Face) RegisterCodepoint(codepoint int)
- func (face *Face) RegisterCodepoints(codepoints []int)
- func (face *Face) RegisterGlyph(glyphID int, components string)
- type Form
- type Function
- type Imagefile
- func (imgf *Imagefile) BitsPerComponent() int
- func (imgf *Imagefile) Close() error
- func (imgf *Imagefile) GetPDFBoxDimensions(p int, boxName string) (map[string]float64, error)
- func (imgf *Imagefile) HasSoftMask() bool
- func (imgf *Imagefile) ImageObject() *Object
- func (imgf *Imagefile) InternalName() string
- func (imgf *Imagefile) SetStructParent(idx int)
- type Name
- type NameDest
- type NameTreeData
- type Object
- type Objectnumber
- type Outline
- type PDF
- func (pw *PDF) AddForm(content *Object, bbox [4]float64) *Form
- func (pw *PDF) AddPage(content *Object, page Objectnumber) *Page
- func (pw *PDF) Finish() error
- func (pw *PDF) FinishAndClose() error
- func (pw *PDF) GetCatalogNameTreeDict(dict Name) Dict
- func (pw *PDF) LoadFace(filename string, idx int) (*Face, error)
- func (pw *PDF) LoadImageFile(filename string) (*Imagefile, error)
- func (pw *PDF) LoadImageFileWithBox(filename string, box string, pagenumber int) (*Imagefile, error)
- func (pw *PDF) LoadImageFromReader(r io.ReadSeeker, box string, pagenumber int) (*Imagefile, error)
- func (pw *PDF) NewFaceFromData(data []byte, idx int) (*Face, error)
- func (pw *PDF) NewObject() *Object
- func (pw *PDF) NewObjectWithNumber(objnum Objectnumber) *Object
- func (pw *PDF) NextObject() Objectnumber
- func (pw *PDF) Print(s string) error
- func (pw *PDF) Printf(format string, a ...any) error
- func (pw *PDF) Println(s string) error
- func (pw *PDF) SetVersion(v Version)
- func (pw *PDF) Size() int64
- func (pw *PDF) WriteExtGState(gs ExtGState) (*Object, error)
- func (pw *PDF) WriteShadingPattern(p ShadingPattern) (*Object, error)
- type Page
- type Pages
- type Resources
- type Separation
- type Shading
- type ShadingPattern
- type SoftMask
- type String
- type TransparencyGroup
- type Version
Constants ¶
This section is empty.
Variables ¶
var ( OverprintOn = overprintState(true, 1) OverprintOff = overprintState(false, 0) )
Graphics states to switch overprinting on and off. With mode 1 a CMYK color prints only on the plates of its nonzero components: a 100% black prints on the black plate and keeps the cyan, magenta and yellow below it. Separation colors print on their own plate in either mode.
var ( // Logger is initialized to write to io.Discard and the default log level is // math.MaxInt, so it should never write anything. Logger *slog.Logger )
Functions ¶
func FloatToPoint ¶
FloatToPoint returns a string suitable as a PDF size value.
func Serialize ¶
Serialize returns a string representation of the item as it may appear in the PDF file. Arrays are written with square brackets, Dicts with double angle brackets, Strings (PDF strings) with parentheses or single angle brackets, depending on the contents and all other objects with their respective String() method.
Types ¶
type Annotation ¶
type Annotation struct {
Dictionary Dict
Subtype Name
Action string
Rect [4]float64 // x1, y1, x2, y2
Objectnumber Objectnumber // pre-reserved object number (0 = auto-assign)
}
An Annotation is a PDF element that is additional to the text, such as a hyperlink or a note.
type Dict ¶
Dict is a dictionary where each key begins with a slash (/). Each value can be a string, an array or another dictionary.
type ExtGState ¶ added in v1.1.21
type ExtGState struct {
FillAlpha *float64 // /ca, constant alpha for nonstroking (fill) operations
StrokeAlpha *float64 // /CA, constant alpha for stroking operations
BlendMode string // /BM blend mode name such as "Multiply"; empty omits the entry
StrokeOverprint *bool // /OP, overprint for stroking operations
FillOverprint *bool // /op, overprint for nonstroking (fill) operations
OverprintMode *int // /OPM, 1 leaves the plates of zero CMYK components alone
SoftMask *SoftMask // /SMask, see SoftMask
}
ExtGState describes a graphics state parameter dictionary (ISO 32000-2 section 8.4.5). Only the entries needed so far are modeled; a nil pointer or the empty string means "entry absent".
func (ExtGState) ResourceName ¶ added in v1.1.21
ResourceName derives a stable resource name from the contents, so equal parameter sets share one name (and, via WriteExtGState's cache, one indirect object) document-wide. Content streams can therefore reference the state by name ("/<name> gs") before the object is materialised in the page's /Resources/ExtGState dictionary.
type Face ¶
type Face struct {
Shaper *ot.Shaper
VariationSettings map[string]float64 // axis tag -> value for variable fonts
Filename string
PostscriptName string
FaceID int
Scale float64
UnitsPerEM int32
// contains filtered or unexported fields
}
Face represents a font structure with no specific size. To get the dimensions of a font, you need to create a Font object with a given size.
func (*Face) AdvanceWidth ¶ added in v1.1.6
AdvanceWidth returns the advance width of the glyph with the given ID in PDF text space units (1/1000 of text space, scaled by face.Scale).
func (*Face) Codepoint ¶
Codepoint tries to find the code point for r. If none found, 0 is returned.
func (*Face) Codepoints ¶
Codepoints returns the internal code points for the runes.
func (*Face) CompactSubset ¶ added in v1.1.0
CompactSubset enables compact glyph mapping for smaller font files. When called, glyph IDs are renumbered (0, 1, 2, ...) instead of keeping the original positions. Use MapGlyph() to convert old GIDs to new GIDs when writing content streams. Must be called after RegisterCodepoints() and before creating content streams.
func (*Face) InternalName ¶
InternalName returns a PDF usable name such as /F1
func (*Face) MapGlyph ¶ added in v1.1.0
MapGlyph maps an old glyph ID to the new glyph ID after compact subsetting. Only useful after calling CompactSubset(). If compact subsetting is not used, returns the original ID unchanged.
func (*Face) RegisterChar
deprecated
func (*Face) RegisterChars
deprecated
func (*Face) RegisterCodepoint ¶ added in v1.0.11
RegisterCodepoint marks the codepoint as used on the page. For font subsetting.
func (*Face) RegisterCodepoints ¶ added in v1.0.11
RegisterCodepoints marks the codepoints as used on the page. For font subsetting.
func (*Face) RegisterGlyph ¶ added in v1.1.12
RegisterGlyph marks the glyph as used on the page and records the source runes the glyph came from. The components string allows the ToUnicode CMap to recover the original text for glyphs without a direct cmap entry (typical for OpenType ligatures like fi/fl), so copy-paste yields the original characters instead of U+FFFD.
type Form ¶ added in v1.1.33
type Form struct {
Resources
Dict Dict // Additional dictionary entries such as "/StructParents"
BBox [4]float64
Group *TransparencyGroup // nil for a form without a transparency group
// contains filtered or unexported fields
}
A Form is a Form XObject: a content stream with its own resources that a page, another form or a soft mask paints as one object. There is no /Matrix by default, so coordinates in the form are those of the content stream that paints it.
func (*Form) ObjectNumber ¶ added in v1.1.33
func (f *Form) ObjectNumber() Objectnumber
ObjectNumber returns the object number of the form. A structure element needs it for marked content in the form.
type Function ¶ added in v1.1.16
type Function struct {
FunctionType int // 2 or 3
Domain [2]float64 // typically [0 1]
// FunctionType 2 fields
C0 []float64 // start color (0..1)
C1 []float64 // end color (0..1)
N float64 // exponent; 1 for linear interpolation
// FunctionType 3 fields
SubFunctions []Function // each must be FunctionType 2
Bounds []float64 // len = len(SubFunctions)-1
Encode [][2]float64 // len = len(SubFunctions)
}
Function describes a PDF Function (Section 7.10 of ISO 32000-1).
Two FunctionTypes are supported here:
FunctionType 2 (exponential interpolation) — used for a two-stop linear gradient. C0/C1 are the endpoints in 0..1 space with one value per component of the color space of the shading; N=1 yields linear interpolation, the only mode used for SVG.
FunctionType 3 (stitching) — chains multiple Type 2 sub-functions for gradients with three or more stops. Bounds partition the [0,1] domain and Encode remaps each sub-domain onto its sub-function's [0,1].
type Imagefile ¶
type Imagefile struct {
PageSizes map[int]map[string]map[string]float64
Format string
Filename string
Box string
NumberOfPages int
ScaleX float64
ScaleY float64
W int
H int
PageNumber int // The requested page number for PDF images (1-based)
// contains filtered or unexported fields
}
Imagefile represents a physical image file. Images to be place in the PDF must be derived from the image.
func (*Imagefile) BitsPerComponent ¶ added in v1.1.29
BitsPerComponent returns the bits per color component a bitmap image is written with, for example 8 or 16. It returns 0 for a PDF file.
func (*Imagefile) GetPDFBoxDimensions ¶
GetPDFBoxDimensions returns normalized box dimensions for the given page and box name. It always computes x, y, w, h and clamps non-Media boxes to the MediaBox. Supported names: "/MediaBox", "/CropBox", "/BleedBox", "/TrimBox", "/ArtBox". Fallbacks:
- missing /CropBox -> /MediaBox
- missing /ArtBox|/BleedBox|/TrimBox -> /CropBox if present, else /MediaBox
func (*Imagefile) HasSoftMask ¶ added in v1.1.29
HasSoftMask reports whether a bitmap image is written with a soft mask (/SMask), which is transparency: PDF/X-3 and PDF/A-1 don't allow it. A color key (/Mask) is not a soft mask.
func (*Imagefile) ImageObject ¶ added in v1.1.10
ImageObject returns the *Object that represents this Imagefile's XObject in the PDF, allocating it lazily on first call. Imagefile otherwise allocates it lazily via the SetObjIDGetter closure during PutFormXobjects, which is too late for callers that need the ObjectNumber at page-shipout time (notably the PDF/UA structure tagger that populates OBJR /Obj <ref>). This getter ensures the object exists; the closure recognises a pre-allocated object and returns its number on its first invocation.
func (*Imagefile) InternalName ¶
InternalName returns a PDF usable name such as /F1
func (*Imagefile) SetStructParent ¶ added in v1.1.10
SetStructParent stages a /StructParent entry for this image's Form XObject. The integer index is a key into the document's StructTreeRoot ParentTree that maps to the structure element this image belongs to (PDF/UA-1 §7.1 Note 1). With /StructParent set, the parent page does not need an enclosing marked-content sequence around the /Do call.
type Name ¶
type Name string
Name represents a PDF name such as Adobe Green. The String() method prepends a / (slash) to the name if not present.
type NameDest ¶
type NameDest struct {
Name String
PageObjectnumber Objectnumber
X float64
Y float64
// contains filtered or unexported fields
}
NameDest represents a named PDF destination. The origin of X and Y are in the top left corner and expressed in DTP points.
type NameTreeData ¶ added in v1.0.6
type NameTreeData map[String]Objectnumber
NameTreeData is a map of strings to object numbers which is sorted by key and converted to an array when written to the PDF. It is suitable for use in a name tree object.
type Object ¶
type Object struct {
Data *bytes.Buffer
Dictionary Dict
Array []any
ObjectNumber Objectnumber
Raw bool // Data holds everything between object number and endobj
ForceStream bool // Write stream even if Data is empty
// contains filtered or unexported fields
}
Object has information about a specific PDF object
func (*Object) SetCompression ¶
SetCompression turns on stream compression if compresslevel > 0
type Objectnumber ¶
type Objectnumber int
Objectnumber represents a PDF object number
func (Objectnumber) Ref ¶
func (o Objectnumber) Ref() string
Ref returns a reference to the object number
func (Objectnumber) String ¶
func (o Objectnumber) String() string
String returns a reference to the object number
type Outline ¶
type Outline struct {
Title string
Dest string
Children []*Outline
Open bool
// contains filtered or unexported fields
}
Outline represents PDF bookmarks. To create outlines, you need to assign previously created Dest items to the outline. When Open is true, the PDF viewer shows the child outlines.
type PDF ¶
type PDF struct {
Catalog Dict
InfoDict Dict
NameDestinations map[String]*NameDest
Colorspaces []*Separation
DefaultRGB Objectnumber // color space object for DeviceRGB on every page and in shadings, 0 for none
Outlines []*Outline
DefaultOffsetX float64
DefaultOffsetY float64
DefaultPageWidth float64
DefaultPageHeight float64
NoPages int // set when PDF is finished
// contains filtered or unexported fields
}
PDF is the central point of writing a PDF file.
func NewPDFWriter ¶
NewPDFWriter initializes and returns a PDF writer targeting file. It sets PDF version 1.7, prepares internal maps, a reusable zlib writer, and starts object numbering at 1 (object 0 is the free head entry).
func (*PDF) AddForm ¶ added in v1.1.33
AddForm makes a Form XObject from the content stream. Unlike AddPage it needs the clipping rectangle of the form. The form is written when the PDF is finished, so its resources can be set until then. Paint it by adding it to the Forms of the page and writing "/<name> Do".
func (*PDF) AddPage ¶
func (pw *PDF) AddPage(content *Object, page Objectnumber) *Page
AddPage adds a page to the PDF file. The content stream must a stream object (i.e. an object with data). Pass 0 for the page object number if you don't pre-allocate an object number for the page.
func (*PDF) FinishAndClose ¶ added in v1.0.8
FinishAndClose writes the trailer and xref section and closes the file if it implements io.Closer.
func (*PDF) GetCatalogNameTreeDict ¶ added in v1.0.6
GetCatalogNameTreeDict returns the Dict for the specified name. If it does not exist, it is created.
func (*PDF) LoadFace ¶
LoadFace loads a font from the disc. The index specifies the sub font to be loaded.
func (*PDF) LoadImageFile ¶
LoadImageFile loads an image from the disc. For PDF files it defaults to page 1 and the /MediaBox.
func (*PDF) LoadImageFileWithBox ¶
func (pw *PDF) LoadImageFileWithBox(filename string, box string, pagenumber int) (*Imagefile, error)
LoadImageFileWithBox loads an image from the disc with the given box and page number. If box is empty, it defaults to /MediaBox.
func (*PDF) LoadImageFromReader ¶ added in v1.1.8
LoadImageFromReader loads an image from the given reader with the given box and page number. If box is empty, it defaults to /MediaBox. The caller is responsible for closing the reader if needed.
func (*PDF) NewFaceFromData ¶
NewFaceFromData returns a Face object which is a representation of a font file.
func (*PDF) NewObject ¶
NewObject create a new PDF object and reserves an object number for it. The object is not written to the PDF until Save() is called.
func (*PDF) NewObjectWithNumber ¶
func (pw *PDF) NewObjectWithNumber(objnum Objectnumber) *Object
NewObjectWithNumber create a new PDF object and reserves an object number for it. The object is not written to the PDF until Save() is called.
func (*PDF) NextObject ¶
func (pw *PDF) NextObject() Objectnumber
NextObject returns the next free object number
func (*PDF) SetVersion ¶ added in v1.1.14
SetVersion overrides the default PDF version. Intended for callers that express version intent via a higher-level concept (e.g. Format in boxesandglue). Must be called before the first byte is written.
func (*PDF) WriteExtGState ¶ added in v1.1.21
WriteExtGState serialises gs as an indirect object and returns it, so callers can reference it from a Page's /Resources/ExtGState entry. Equal parameter sets are written only once per PDF: the object is cached under its ResourceName and shared between pages.
func (*PDF) WriteShadingPattern ¶ added in v1.1.16
func (pw *PDF) WriteShadingPattern(p ShadingPattern) (*Object, error)
WriteShadingPattern serialises a ShadingPattern as three chained indirect PDF objects (Function, Shading, Pattern) and returns the Pattern object so callers can reference it from a Page's /Resources/Pattern entry.
All sub-functions of a stitching function become individual indirect objects too, since /Functions in a Type 3 Function dictionary is an array of indirect references.
type Page ¶
type Page struct {
Resources
Dict Dict // Additional dictionary entries such as "/Trimbox"
Annotations []Annotation
Group *TransparencyGroup // nil for a page without a page group
Objnum Objectnumber // The "/Page" object
Width float64
Height float64
OffsetX float64
OffsetY float64
// contains filtered or unexported fields
}
Page contains information about a single page.
type Pages ¶
type Pages struct {
Pages []*Page
// contains filtered or unexported fields
}
Pages is the parent page structure
type Resources ¶ added in v1.1.33
type Resources struct {
Faces []*Face
Images []*Imagefile
// Forms maps a resource name (without the leading slash) to a form from
// PDF.AddForm. The name is the host's choice, so that a renderer can
// write "/<name> Do" before the form exists. Entries land in
// /Resources/XObject.
Forms map[Name]*Form
// Patterns maps a per-page-unique resource name (without the leading
// slash) to the indirect Pattern object returned by
// PDF.WriteShadingPattern. Entries land in /Resources/Pattern; the
// renderer (e.g. svgreader) refers to them as "/<name> scn" inside the
// content stream.
Patterns map[Name]*Object
// ExtGStates maps a resource name (without the leading slash) to the
// indirect graphics state parameter dictionary returned by
// PDF.WriteExtGState. Entries land in /Resources/ExtGState; content
// streams activate them with "/<name> gs".
ExtGStates map[Name]*Object
}
Resources holds what a content stream refers to by name. A page and a form each have their own set.
type Separation ¶
type Separation struct {
ID string
Name string
Obj Objectnumber
ICCProfile Objectnumber
C float64
M float64
Y float64
K float64
}
Separation represents a spot color
type Shading ¶ added in v1.1.16
type Shading struct {
ShadingType int // 2 = axial (linear), 3 = radial
ColorSpace Name // "/DeviceRGB" (default), "/DeviceGray", "/DeviceCMYK"
// Coords are in pattern space. Type 2 takes x0 y0 x1 y1, the two ends of
// the axis. Type 3 takes x0 y0 r0 x1 y1 r1, the start and the end circle,
// with r0 and r1 not negative.
Coords []float64
Function Function
Extend [2]bool // [extendStart extendEnd]
}
Shading describes a PDF Shading Dictionary (Section 8.7.4.5), either Type 2 (axial) or Type 3 (radial).
type ShadingPattern ¶ added in v1.1.16
ShadingPattern describes a PDF Pattern Dictionary of type 2 (Shading Pattern, Section 8.7.3.3). The matrix maps pattern space to default coordinate space, mirroring SVG's gradientTransform.
type SoftMask ¶ added in v1.1.33
type SoftMask struct {
Group *Form // /G, a form with a transparency group
Alpha bool // /S, use the alpha of the group instead of its luminosity
Backdrop []float64 // /BC, for a luminosity mask, in the color space of the group
}
SoftMask describes the /SMask entry of a graphics state (ISO 32000-2 section 11.6.5.3): a form whose result varies the opacity of what is painted while the graphics state is active. Without a Group the entry is /None, which ends a soft mask.
type String ¶
type String string
String is a string that gets automatically converted to (...) or hexadecimal form when placed in the PDF.
type TransparencyGroup ¶ added in v1.1.33
type TransparencyGroup struct {
// ColorSpace is the blending color space as it appears in the PDF, such
// as "/DeviceCMYK" or a reference to an ICC based color space. An empty
// string omits the entry.
ColorSpace string
Isolated bool // /I, the group does not see its backdrop
Knockout bool // /K, later objects replace earlier ones in the group
}
TransparencyGroup describes a /Group dictionary of subtype Transparency (ISO 32000-2 section 11.6.6). On a form it makes the content of the form one object for the compositing of the surrounding content, so a constant alpha applies to the result and not to each drawing operator.
