Documentation
¶
Overview ¶
Package pdfkit is a pure-Go, CGO-free PDF 1.7 writer with a Go-idiomatic API.
It builds documents from pages, draws vector graphics and text, embeds TrueType and OpenType/CFF fonts as subsetted composite (Type0) fonts, and places JPEG and raster images. Fonts are parsed and shaped with github.com/go-opentype/opentype; nothing outside the Go standard library and our own pure-Go libraries is required.
Quick start ¶
doc := pdfkit.New(pdfkit.Options{})
face, _ := pdfkit.LoadFont(ttfBytes)
p := doc.AddPage(pdfkit.A4)
p.SetFont(face, 24)
p.Text(72, 720, "Hello, PDF")
_ = doc.Write(w) // any io.Writer
Coordinate system ¶
User space is measured in points (1/72 inch) with the origin at the lower-left corner and y increasing upward, matching PDF. The Pt, Mm and In helpers convert physical units; the standard page sizes (A4, Letter, ...) and NewPageSize give a page's dimensions.
Text and fonts ¶
LoadFont parses a font blob once; a Font is immutable and may be shared. SetFont selects it for a page, then Text draws a left-to-right run. TextShaped runs the go-opentype shaper (GSUB/GPOS) for complex scripts and writes the run as one TJ array per baseline segment, with a numeric correction only where shaping departs from the font's own advances (kerning, marks). Font and colour operators are written once and not repeated while unchanged; coordinates carry at most four decimals. Every embedded font is written as a subset with Identity-H encoding, a per-glyph /W width array and a /ToUnicode CMap so copy and paste recover the original text. TrueType outlines embed as a subsetted FontFile2 / CIDFontType2 with a /CIDToGIDMap stream (the subset renumbers glyphs, so the map sends each CID — the original glyph id — to its subset id); CFF/OpenType outlines embed as a charstring-subsetted FontFile3 / CIDFontType0 whose glyph numbering is preserved, so an Identity /CIDToGIDMap suffices.
Images ¶
DrawJPEG stores the original JPEG bytes as a DCTDecode stream, so nothing is re-encoded. DrawPNG and DrawImage walk any image.Image into 8-bit DeviceRGB samples compressed with FlateDecode, and an image that is not fully opaque gets its alpha channel as a DeviceGray /SMask.
An image is content-addressed by its uncompressed samples together with the width, height, colour space, bits per component and the alpha samples — the raw JPEG bytes in the DCTDecode case. Pixel-identical bitmaps therefore share a single XObject across the whole document, whichever page paints them and whichever entry point embedded them; the samples are hashed before they are compressed, so a repeat never pays for compression twice. This matters for pages that reuse one icon many times: an HTML renderer feeding pdfkit 166 rasterised copies of a handful of icon SVGs now emits a handful of streams.
Determinism ¶
With the zero Options the output contains no timestamps and a content-derived /ID, so identical inputs produce byte-identical documents. Set Options.Now to stamp creation and modification dates. The image cache is consulted but never iterated: object order and /Im<i> numbering follow first-sighting order, so deduplication does not put map iteration on the output path.
Widget bridge ¶
The subpackage github.com/go-pdfkit/pdfkit/widget "prints" a github.com/go-widgets/toolkit widget tree onto a page: widget.Add as an image, widget.AddVector as vector operators with selectable text. It is a separate package so that importing pdfkit does not link the toolkit; a test fails if the root package's import graph ever reaches it again. Until v0.20.0 these were Page.AddWidget and Page.AddWidgetVector.
Font embedding ¶
go-opentype/opentype supplies every primitive PDF embedding needs: the descriptor scalars (units-per-em, bounding box, ascent/descent, cap height, italic angle, flags, StemV), the by-glyph advances for the /W array, and the glyph subsetters. TrueType 'glyf' fonts are subsetted with Font.SubsetTrueType and CFF fonts with Font.SubsetCFF, so pdfkit keeps no private sfnt re-parse or subsetter of its own. A CID-keyed CFF or a CFF2 (variable) font, which the preserve-numbering CFF subsetter does not handle, gracefully falls back to embedding its whole 'CFF '/'CFF2' table.
Example ¶
Example builds a one-page document with embedded-font text and vector graphics, then writes it to a buffer. The output is deterministic: with the zero Options there are no timestamps and the /ID is content-derived.
package main
import (
"bytes"
"fmt"
"os"
"strings"
"github.com/go-pdfkit/pdfkit"
)
func main() {
font, err := pdfkit.LoadFont(mustRead("testdata/SourceSerif4-Regular.otf"))
if err != nil {
panic(err)
}
doc := pdfkit.New(pdfkit.Options{Title: "Hello"})
p := doc.AddPage(pdfkit.A4)
p.SetFont(font, 24)
_ = p.Text(pdfkit.Mm(20), p.Height()-pdfkit.Mm(20), "Hello, pdfkit")
p.SetStrokeColor(pdfkit.RGB8(0x0d, 0x94, 0x88))
p.SetLineWidth(2)
p.MoveTo(pdfkit.Mm(20), pdfkit.Mm(20))
p.LineTo(pdfkit.Mm(190), pdfkit.Mm(20))
p.Stroke()
var buf bytes.Buffer
if err := doc.Write(&buf); err != nil {
panic(err)
}
fmt.Println(strings.SplitN(buf.String(), "\n", 2)[0])
}
func mustRead(path string) []byte {
b, err := os.ReadFile(path)
if err != nil {
panic(err)
}
return b
}
Output: %PDF-1.7
Index ¶
- Constants
- Variables
- func In(v float64) float64
- func Mm(v float64) float64
- func Pt(v float64) float64
- type Artifact
- type Attribute
- type CMYK
- type Color
- type Document
- type Font
- type Glyph
- type Gray
- type Name
- type Options
- type OutlineOptions
- type Page
- func (p *Page) AddLink(rect Rect, uri string)
- func (p *Page) AddNamedDest(name string, x, y float64)
- func (p *Page) AddNamedLink(rect Rect, dest string)
- func (p *Page) AddTaggedLink(e *StructElem, rect Rect, uri, contents string)
- func (p *Page) AddTaggedNamedLink(e *StructElem, rect Rect, dest, contents string)
- func (p *Page) AddTextAnnotation(a TextAnnotation)
- func (p *Page) BeginActualText(replacement string)
- func (p *Page) BeginArtifact(a Artifact)
- func (p *Page) BeginTag(e *StructElem)
- func (p *Page) Clip()
- func (p *Page) ClipEvenOdd()
- func (p *Page) ClosePath()
- func (p *Page) CurveTo(x1, y1, x2, y2, x3, y3 float64)
- func (p *Page) DrawImage(img image.Image, r Rect)
- func (p *Page) DrawJPEG(data []byte, r Rect) error
- func (p *Page) DrawPNG(data []byte, r Rect) error
- func (p *Page) EndMarkedContent()
- func (p *Page) EndPath()
- func (p *Page) Fill()
- func (p *Page) FillEvenOdd()
- func (p *Page) FillStroke()
- func (p *Page) FillStrokeEvenOdd()
- func (p *Page) Height() float64
- func (p *Page) LineTo(x, y float64)
- func (p *Page) MoveTo(x, y float64)
- func (p *Page) Rectangle(r Rect)
- func (p *Page) Restore()
- func (p *Page) Rotate(deg float64)
- func (p *Page) Save()
- func (p *Page) Scale(sx, sy float64)
- func (p *Page) SetAlpha(fill, stroke float64)
- func (p *Page) SetCharSpacing(v float64)
- func (p *Page) SetDash(pattern []float64, phase float64)
- func (p *Page) SetFillColor(c Color)
- func (p *Page) SetFont(f *Font, size float64)
- func (p *Page) SetLeading(v float64)
- func (p *Page) SetLineCap(style int)
- func (p *Page) SetLineJoin(style int)
- func (p *Page) SetLineWidth(w float64)
- func (p *Page) SetMiterLimit(limit float64)
- func (p *Page) SetRenderMode(mode int)
- func (p *Page) SetStrokeColor(c Color)
- func (p *Page) SetWordSpacing(v float64)
- func (p *Page) Shade(s Shading) error
- func (p *Page) ShowGlyphs(x, y float64, glyphs []Glyph) error
- func (p *Page) Skew(axDeg, ayDeg float64)
- func (p *Page) Stroke()
- func (p *Page) Text(x, y float64, s string) error
- func (p *Page) TextLines(x, y float64, lines []string) error
- func (p *Page) TextShaped(x, y float64, s string, features ...string) error
- func (p *Page) TextWidth(s string) float64
- func (p *Page) Transform(a, b, c, d, e, f float64)
- func (p *Page) Translate(tx, ty float64)
- func (p *Page) Width() float64
- func (p *Page) WrapText(s string, maxWidth float64) []string
- type PageSize
- type Point
- type RGB
- type Rect
- type Shading
- type Stop
- type StructElem
- type TextAnnotation
Examples ¶
Constants ¶
const ( CapButt = 0 CapRound = 1 CapSquare = 2 )
Line-cap styles for SetLineCap.
const ( JoinMiter = 0 JoinRound = 1 JoinBevel = 2 )
Line-join styles for SetLineJoin.
const ( StructDocument = "Document" StructPart = "Part" StructSect = "Sect" StructDiv = "Div" StructP = "P" StructH1 = "H1" StructH2 = "H2" StructH3 = "H3" StructH4 = "H4" StructH5 = "H5" StructH6 = "H6" StructL = "L" StructLI = "LI" StructLbl = "Lbl" StructLBody = "LBody" StructTable = "Table" StructTR = "TR" StructTH = "TH" StructTD = "TD" StructSpan = "Span" StructLink = "Link" StructAnnot = "Annot" StructFigure = "Figure" StructFormula = "Formula" StructCode = "Code" StructQuote = "Quote" StructBlockQuote = "BlockQuote" StructNote = "Note" StructCaption = "Caption" )
Standard structure types (ISO 32000-1:2008, 14.8.4). Any name may be used; these are the ones a reader knows without a role map.
const ( RenderFill = 0 // fill glyphs RenderStroke = 1 // stroke glyph outlines RenderFillStroke = 2 // fill then stroke RenderInvisible = 3 // neither (useful for OCR text layers) RenderFillClip = 4 // fill and add to clip RenderStrokeClip = 5 // stroke and add to clip RenderFSClip = 6 // fill, stroke and add to clip RenderClip = 7 // add to clip only )
Text render modes for SetRenderMode (a subset of PDF's Tr values).
const DefaultProducer = "go-pdfkit/pdfkit"
DefaultProducer is the /Producer value used when Options.Producer is empty.
Variables ¶
var ( A3 = PageSize{Width: Mm(297), Height: Mm(420)} A4 = PageSize{Width: Mm(210), Height: Mm(297)} A5 = PageSize{Width: Mm(148), Height: Mm(210)} Letter = PageSize{Width: In(8.5), Height: In(11)} Legal = PageSize{Width: In(8.5), Height: In(14)} Tabloid = PageSize{Width: In(11), Height: In(17)} )
Standard ISO 216 A-series and US page sizes, in points.
Functions ¶
Types ¶
type Artifact ¶ added in v0.18.0
type Artifact struct {
// Type is "Pagination", "Layout", "Page" or "Background"; empty writes
// a plain /Artifact BMC.
Type string
// Subtype refines a Pagination artifact: "Header", "Footer" or
// "Watermark".
Subtype string
// BBox, when not nil, is the artifact's extent in the page's user space
// (required for a Background artifact).
BBox *Rect
}
Artifact describes content that is not part of the document's matter (ISO 32000-1:2008, 14.8.2.2, Table 330): a page's background, a page number, a rule, an ornament.
type Attribute ¶ added in v0.19.0
Attribute is one standard structure attribute (ISO 32000-1:2008, 14.8.5): its owner ("Table", "List", "Layout", "PrintField"…), its key, and its value: a Name, an int, a float64 or a string (a text string).
type CMYK ¶
type CMYK struct{ C, M, Y, K float64 }
CMYK is a DeviceCMYK colour with cyan, magenta, yellow and black components in [0,1].
type Color ¶
type Color interface {
// contains filtered or unexported methods
}
Color is a paint in one of PDF's device colour spaces. Its ops method emits the content-stream operator that selects it for filling (stroke=false) or stroking (stroke=true). Component values are in the range [0,1].
type Document ¶
type Document struct {
// contains filtered or unexported fields
}
Document is a PDF document under construction. Build it with New, append pages with AddPage, then serialise with Write. It is not safe for concurrent use.
Example (MultiPage) ¶
ExampleDocument_multiPage lays out several pages of different sizes.
package main
import (
"bytes"
"fmt"
"github.com/go-pdfkit/pdfkit"
)
func main() {
doc := pdfkit.New(pdfkit.Options{})
doc.AddPage(pdfkit.A4)
doc.AddPage(pdfkit.Letter.Landscape())
doc.AddPage(pdfkit.NewPageSize(pdfkit.In(4), pdfkit.In(6)))
var buf bytes.Buffer
_ = doc.Write(&buf)
fmt.Println(bytes.Contains(buf.Bytes(), []byte("/Count 3")))
}
Output: true
func (*Document) AddOutlineItem ¶ added in v0.9.0
AddOutlineItem appends a bookmark to the document outline: title at nesting level (1 = top level; a higher level nests under the most recent shallower item), jumping to page pageIndex (0-based). Out-of-range pages are ignored. Items build the /Outlines tree a PDF viewer shows as its navigation sidebar.
func (*Document) AddOutlineItemWith ¶ added in v0.16.0
func (d *Document) AddOutlineItemWith(title string, level, pageIndex int, opts OutlineOptions)
AddOutlineItemWith is AddOutlineItem with a styled title and a position on the page.
func (*Document) AddPage ¶
AddPage appends a page of the given size (in points; see PageSize helpers and the standard sizes such as A4) and returns it for drawing.
func (*Document) Structure ¶ added in v0.18.0
func (d *Document) Structure() *StructElem
Structure returns the document's root element, a Document element, making it on the first call: a document that calls it is a tagged PDF. Its children are the top-level elements.
func (*Document) Write ¶
Write serialises the document to w as a complete PDF file: PDF 1.7 with a classic cross-reference table, or, when Options.ObjectStreams is set, PDF 1.5 with its small objects packed into object streams and a cross-reference stream in place of the table. It returns the first write error encountered. Calling Write does not consume the document; it may be written more than once.
type Font ¶
type Font struct {
// contains filtered or unexported fields
}
Font is a loaded TrueType or OpenType font ready to be used and embedded. It is immutable and may be shared across documents and goroutines; per-document glyph usage is tracked separately by the Document. Build one with LoadFont.
func LoadFont ¶
LoadFont parses a TrueType ('glyf') or OpenType/CFF ('OTTO'/CFF) font from its raw bytes. The bytes are retained and must not be mutated afterwards. Parsing, glyph indexing, metrics, shaping and subsetting are all delegated to github.com/go-opentype/opentype; pdfkit keeps no private sfnt re-parse.
func NewFont ¶ added in v0.15.0
NewFont wraps a font another component has already parsed, so that a program which laid its text out with an *opentype.Font — a layout engine measuring with the very faces it will print — embeds that same font without keeping its bytes or parsing it a second time.
The font must carry a 'cmap', as for LoadFont. A Font made this way has no whole-font fallback: embedding always goes through go-opentype's subsetter, which can only fail on a glyph id the font does not have, and ShowGlyphs refuses those up front.
func (*Font) IsCFF ¶
IsCFF reports whether the font carries CFF/OpenType outlines (embedded as a CIDFontType0), as opposed to TrueType 'glyf' outlines (CIDFontType2).
func (*Font) UnitsPerEm ¶
UnitsPerEm returns the font's design grid size.
type Glyph ¶ added in v0.15.0
type Glyph struct {
ID opentype.GlyphIndex
X, Y float64
Text string
}
Glyph is one glyph of a run whose layout the caller has already done: the glyph to draw, where its origin goes and the text it stands for.
X and Y are the glyph origin's offset from the run origin, in points, Y upwards as everywhere in the page's user space. Text is what copying the glyph out of the PDF should give (the /ToUnicode mapping, ISO 32000-1 §9.10.3): one character for most glyphs, several for a ligature, empty for a glyph that continues a cluster an earlier glyph already spoke for.
type Gray ¶
type Gray struct{ V float64 }
Gray is a DeviceGray colour: a single intensity from 0 (black) to 1 (white).
type Name ¶ added in v0.19.0
type Name string
Name is an attribute value written as a PDF name, such as Column for a table header's Scope.
type Options ¶
type Options struct {
// Title, Author, Subject and Keywords populate the document information
// dictionary. Empty values are omitted. Subject is a one-line description of
// the document; Keywords is a list of search terms (conventionally
// comma-separated). Each is written as a PDF text string, so a non-ASCII value
// is encoded UTF-16BE.
Title string
Author string
Subject string
Keywords string
// Producer is the /Producer string in the information dictionary. When
// empty it defaults to DefaultProducer.
Producer string
// Now, when non-nil, is called once at Write time to stamp /CreationDate
// and /ModDate. When nil no dates are written, keeping output reproducible;
// tests should leave it nil.
Now func() time.Time
// Compress enables FlateDecode compression of content and embedded-font
// streams. Image streams choose their own filter regardless.
Compress bool
// ObjectStreams packs the document's non-stream objects — page and font
// dictionaries, link annotations, outline items, name trees — into PDF 1.5
// object streams and replaces the classic cross-reference table with a
// cross-reference stream. With Compress also set the object streams are
// flate-compressed as a whole, which is where the saving is: a link
// annotation costs some 220 bytes as a bare indirect object plus its xref
// line, and a few tens of bytes packed with its neighbours. Off by default,
// so the bytes existing consumers get do not change: the file then declares
// PDF 1.7 and carries every object bare with a classic table.
ObjectStreams bool
// ID, when both entries are non-nil, is used verbatim as the trailer /ID
// pair. When nil the ID is derived deterministically from the document
// body, so identical documents get identical IDs without a clock.
ID [2][]byte
// Lang is the document's natural language, a language tag such as "en"
// or "fr-CA" (the catalog's /Lang, ISO 32000-1:2008, 14.9.2). A screen
// reader picks its voice from it; PDF/UA requires it.
Lang string
// DisplayDocTitle asks viewers to show Title in the window's title bar
// rather than the file name (/ViewerPreferences, 12.2). PDF/UA requires
// it.
DisplayDocTitle bool
// PDFUA declares the document a PDF/UA-1 file (ISO 14289-1): it writes
// the XMP metadata stream with the title and the pdfuaid:part
// identification. The document must be tagged (Document.Structure),
// with Title, Lang and DisplayDocTitle set, for the claim to hold; the
// rest, every drawing tagged or an artifact, is the caller's to keep.
PDFUA bool
}
Options configures a Document. The zero value is valid and yields a deterministic, uncompressed document with no timestamps.
type OutlineOptions ¶ added in v0.16.0
type OutlineOptions struct {
// Bold and Italic style the title in the viewer's sidebar (the item's /F
// flags).
Bold, Italic bool
// At, when not nil, is the point of the page the bookmark scrolls to — the
// top left of the view, in the page's user space — instead of fitting the
// whole page (the destination is [page /XYZ x y null]: the zoom is kept).
At *Point
}
OutlineOptions refines a bookmark added with AddOutlineItemWith.
type Page ¶
type Page struct {
// contains filtered or unexported fields
}
Page is a single page's content. It accumulates a content stream as drawing methods are called; the operators mirror PDF's imaging model. The default user space has its origin at the lower-left corner with y increasing upward.
func (*Page) AddLink ¶ added in v0.7.0
AddLink adds a borderless clickable link over rect — in the same PDF user-space coordinates the drawing methods use — that opens uri when activated. It is how a typeset hyperref link (\href/\url) becomes navigable in the PDF, matching the <a href> the SVG output already emits.
func (*Page) AddNamedDest ¶ added in v0.8.0
AddNamedDest anchors the named destination name at (x, y) on this page, so an internal link can jump to it. The point (x, y) is the top-left the viewer scrolls to, in the page's user space.
func (*Page) AddNamedLink ¶ added in v0.8.0
AddNamedLink adds a borderless clickable link over rect that jumps to the named destination dest in the same document — the in-PDF counterpart of the SVG output's <a href="#name"> for \hyperlink.
func (*Page) AddTaggedLink ¶ added in v0.18.0
func (p *Page) AddTaggedLink(e *StructElem, rect Rect, uri, contents string)
AddTaggedLink is AddLink for a tagged document: the annotation is a kid of the Link element e, after whatever e already holds, and contents is its alternate description (/Contents), which PDF/UA asks of every link.
func (*Page) AddTaggedNamedLink ¶ added in v0.18.0
func (p *Page) AddTaggedNamedLink(e *StructElem, rect Rect, dest, contents string)
AddTaggedNamedLink is AddNamedLink for a tagged document; see AddTaggedLink.
func (*Page) AddTextAnnotation ¶ added in v0.16.0
func (p *Page) AddTextAnnotation(a TextAnnotation)
AddTextAnnotation adds a text annotation to the page. An annotation with no Contents is ignored.
func (*Page) BeginActualText ¶ added in v0.17.0
BeginActualText starts a marked-content span (/Span ... BDC) whose text, for extraction, copying and searching, is replacement instead of the glyphs drawn inside it. An empty replacement makes what is drawn invisible to text extraction while it still shows: numbers in a margin, a numbered disc after a line of code. Readers that honour ActualText — Poppler's pdftotext does — then leave it out of the text; a reader that does not still draws and extracts it as before. End the span with EndMarkedContent; spans nest. A span may enclose whole text objects (BT ... ET), which is how it is meant to be used.
func (*Page) BeginArtifact ¶ added in v0.18.0
BeginArtifact starts a marked-content sequence of artifact content; end it with EndMarkedContent. A screen reader skips it, and a tagged document must mark every drawing that is not tagged this way (PDF/UA). A BeginArtifact while a tagged sequence is open closes that sequence first: an artifact may not sit inside tagged content.
func (*Page) BeginTag ¶ added in v0.18.0
func (p *Page) BeginTag(e *StructElem)
BeginTag starts a marked-content sequence of e's content: what is drawn until the matching EndMarkedContent belongs to e. The sequence is tagged with e's type and a fresh MCID, and e lists it as its next child, so calling BeginTag in reading order keeps the structure in reading order. Sequences may not nest (14.7.4.2 forbids one structure content item in another): a BeginTag while one is open closes the open one first.
func (*Page) Clip ¶
func (p *Page) Clip()
Clip intersects the clipping path with the current path using the nonzero rule (W). It must be followed by a path-painting or EndPath operator.
func (*Page) ClipEvenOdd ¶
func (p *Page) ClipEvenOdd()
ClipEvenOdd intersects the clipping path using the even-odd rule (W*).
func (*Page) ClosePath ¶
func (p *Page) ClosePath()
ClosePath closes the current subpath with a straight segment to its start (h).
func (*Page) CurveTo ¶
CurveTo adds a cubic Bézier segment to (x3, y3) with control points (x1, y1) and (x2, y2) (c).
func (*Page) DrawImage ¶
DrawImage embeds img and paints it into the rectangle r (in points). Any alpha channel becomes a soft mask, so partially transparent images composite correctly. Sample data is FlateDecode-compressed.
Pixel-identical images share one XObject document-wide: the samples are hashed before they are compressed, so redrawing the same bitmap costs a hash and nothing else.
func (*Page) DrawJPEG ¶
DrawJPEG embeds JPEG bytes directly (DCTDecode, no re-encoding) into r, preserving the original compression. Grayscale (1), RGB/YCbCr (3) and CMYK (4) component counts are supported.
func (*Page) DrawPNG ¶
DrawPNG decodes PNG bytes and embeds the image into r. It returns an error if the data is not a valid PNG.
func (*Page) EndMarkedContent ¶ added in v0.17.0
func (p *Page) EndMarkedContent()
EndMarkedContent ends the innermost marked-content sequence: a span BeginActualText started, a tagged sequence (BeginTag) or an artifact (BeginArtifact). Without one open it writes nothing, so a stray call cannot unbalance the stream.
func (*Page) EndPath ¶
func (p *Page) EndPath()
EndPath ends the path with no fill or stroke (n), used after a clip.
func (*Page) Fill ¶
func (p *Page) Fill()
Fill fills the current path with the nonzero winding rule (f).
func (*Page) FillEvenOdd ¶
func (p *Page) FillEvenOdd()
FillEvenOdd fills the current path with the even-odd rule (f*).
func (*Page) FillStroke ¶
func (p *Page) FillStroke()
FillStroke fills (nonzero) then strokes the current path (B).
func (*Page) FillStrokeEvenOdd ¶
func (p *Page) FillStrokeEvenOdd()
FillStrokeEvenOdd fills (even-odd) then strokes the current path (B*).
func (*Page) Restore ¶
func (p *Page) Restore()
Restore pops the graphics state (Q). The font/colour operators written since the matching Save are forgotten with it, so the next SetFont/SetFillColor/ SetStrokeColor writes even a value that looks unchanged.
func (*Page) Rotate ¶
Rotate rotates the coordinate system counter-clockwise by deg degrees about the origin.
func (*Page) SetAlpha ¶
SetAlpha sets the constant fill and stroke alpha (opacity) in [0,1] via an ExtGState resource (ca/CA).
func (*Page) SetCharSpacing ¶
SetCharSpacing sets additional spacing between glyphs, in points (Tc).
func (*Page) SetDash ¶
SetDash sets the line dash pattern and phase (d). An empty pattern restores a solid line.
func (*Page) SetFillColor ¶
SetFillColor selects the fill colour. Selecting the colour already in force writes nothing.
func (*Page) SetFont ¶
SetFont selects font f at the given size in points for subsequent text. The font is registered with the document for embedding on the first use.
func (*Page) SetLeading ¶
SetLeading sets the line leading (baseline-to-baseline distance) used by TextLines, in points (TL).
func (*Page) SetLineCap ¶
SetLineCap sets the line-cap style (J).
func (*Page) SetLineJoin ¶
SetLineJoin sets the line-join style (j).
func (*Page) SetLineWidth ¶
SetLineWidth sets the stroke line width in user-space units (w).
func (*Page) SetMiterLimit ¶
SetMiterLimit sets the miter limit (M).
func (*Page) SetRenderMode ¶
SetRenderMode sets the text rendering mode (Tr); see the Render constants.
func (*Page) SetStrokeColor ¶
SetStrokeColor selects the stroke colour. Selecting the colour already in force writes nothing.
func (*Page) SetWordSpacing ¶
SetWordSpacing sets additional spacing at space characters, in points (Tw). It has no visible effect on composite (Type0) fonts and is provided for completeness.
func (*Page) Shade ¶ added in v0.12.0
Shade paints the gradient over the current clip.
PDF has no "fill this path with a gradient" operator: a gradient is painted through whatever clip is in force. So the shape comes first and the paint second — set the path, clip to it, then Shade:
p.MoveTo(...); p.CurveTo(...); p.ClosePath() p.Clip(); p.EndPath() p.Shade(g)
Wrap the pair in Save and Restore, or the clip stays in force for everything drawn afterwards.
It reports an error for fewer than two stops, for a stop with no colour, for offsets that do not strictly increase, and for stops that do not all share one colour space — PDF names the space once for the whole shading, so a gradient from grey to CMYK cannot be written rather than being quietly converted.
func (*Page) ShowGlyphs ¶ added in v0.15.0
ShowGlyphs draws glyphs, already chosen and positioned by the caller, with the run origin at (x, y) in the current font and size.
It is the entry point for a layout engine that shapes and measures text itself: the PDF then shows the glyphs at exactly the positions the layout computed instead of re-deriving them from the font, which is what keeps a justified line, a letter-spaced heading or a tab stop where the layout put it. Each baseline segment is one TJ array (ISO 32000-1 §9.4.3): the viewer advances by each glyph's /W width, and a number is written only where the caller's position differs from that by at least a thousandth of an em, so plain unkerned text carries no numbers at all and the pen never drifts. A change of Y starts a new segment.
It reports errNoFont without a font, and an error — before writing anything — for a glyph id the font does not have or a position that is not a finite number.
func (*Page) Text ¶
Text draws s with its baseline origin at (x, y) using the current font. It returns errNoFont if no font is set.
func (*Page) TextLines ¶
TextLines draws consecutive lines starting with the first baseline at (x, y), advancing by the current leading between lines.
func (*Page) TextShaped ¶
TextShaped draws s with complex-script shaping (GSUB substitution and GPOS positioning) via the go-opentype shaper, placing the run's origin at (x, y). The default Text path stays a simple left-to-right cmap mapping; use this for Arabic, Indic, CJK and any text needing ligatures, marks or kerning. features names OpenType feature tags to enable (e.g. "liga").
The run is written as one TJ array per baseline segment: the viewer advances the pen by each glyph's /W width itself, so the only numbers in the stream are the corrections where shaping put a glyph somewhere else (kerning, a positioned mark) — none at all for plain unkerned text. A glyph with a vertical offset gets its own positioned Tj, since TJ cannot move the pen vertically.
func (*Page) TextWidth ¶
TextWidth returns the width of s in points at the current font and size. It returns 0 when no font is set.
func (*Page) Transform ¶
Transform concatenates the affine matrix [a b c d e f] onto the current transformation matrix (cm). Points map as x' = a*x + c*y + e and y' = b*x + d*y + f.
type PageSize ¶
PageSize is a page's dimensions in points.
func NewPageSize ¶
NewPageSize builds a custom page size from a width and height in points.
type Point ¶ added in v0.16.0
type Point struct{ X, Y float64 }
Point is a position in a page's user space, in points.
type RGB ¶
type RGB struct{ R, G, B float64 }
RGB is a DeviceRGB colour with red, green and blue components in [0,1].
type Rect ¶
Rect is an axis-aligned rectangle in user space, given by its lower-left corner and its size.
type Shading ¶ added in v0.12.0
type Shading struct {
X0, Y0, X1, Y1 float64
Stops []Stop
ExtendStart bool
ExtendEnd bool
Radial bool
R0, R1 float64
}
A Shading is an axial gradient: colour interpolated along the line from (X0,Y0) to (X1,Y1), in the page's user space (ISO 32000-1 §8.7.4.5.3, a type 2 shading).
It is what a logo, a chart's fill and a printed background all need, and until now the only way to put one in a PDF from here was to rasterise it — which turns a shape that scales without limit into pixels, and on a large print is exactly the defect the vector file was chosen to avoid.
Extend says whether the end colours carry on past the ends of the axis. Without them the area beyond each end is left unpainted, which for a gradient used as a background shows as two hard bands of nothing.
With Radial set it is a radial gradient instead (ISO 32000-1 §8.7.4.5.4, a type 3 shading): colour interpolated from the circle of radius R0 centred on (X0,Y0) to the circle of radius R1 centred on (X1,Y1). A CSS radial-gradient is the case X0,Y0 = X1,Y1 and R0 = 0; an elliptical one is that circle drawn under a Transform that scales one axis.
type Stop ¶ added in v0.12.0
A Stop is one colour on a gradient, at a position along it from 0 at the start to 1 at the end.
type StructElem ¶ added in v0.18.0
type StructElem struct {
// Type is the structure type, the /S entry: one of the Struct constants
// or another name.
Type string
// Alt is an alternate description, for a figure or a formula above all
// (14.9.3); ActualText is an exact replacement for the element's text
// (14.9.4); Lang its natural language, a language tag such as "fr"
// (14.9.2); Title a human-readable title (/T).
Alt, ActualText, Lang, Title string
// Attributes are the element's standard structure attributes
// (14.8.5): a table header's Scope, a cell's RowSpan, a list's
// ListNumbering… written as one attribute object per owner.
Attributes []Attribute
// contains filtered or unexported fields
}
StructElem is an element of the logical structure (a StructElem dictionary, ISO 32000-1:2008, Table 323). Make one with Document.Structure and Add.
func (*StructElem) Add ¶ added in v0.18.0
func (e *StructElem) Add(typ string) *StructElem
Add appends a child element of type typ and returns it.
func (*StructElem) Parent ¶ added in v0.18.0
func (e *StructElem) Parent() *StructElem
Parent returns the element's parent, nil for the root.
type TextAnnotation ¶ added in v0.16.0
type TextAnnotation struct {
// Rect is where the icon sits, in the page's user space (origin at the
// bottom left). A viewer draws the icon at a size of its own.
Rect Rect
// Contents is the note's text; line feeds start new lines.
Contents string
// Title is the note's author (/T), shown in the pop-up's title bar.
Title string
// Subject is a short summary (/Subj).
Subject string
// Name is the icon, one of the standard ones — "Note" (the default),
// "Comment", "Key", "Help", "NewParagraph", "Paragraph" or "Insert".
Name string
// Color is the icon's RGB colour, three components in 0..1; nil leaves
// it to the viewer.
Color []float64
// Opacity is the icon's constant opacity (/CA), in (0, 1]; 0 leaves it
// out, meaning opaque.
Opacity float64
}
TextAnnotation is a text ("sticky note") annotation: an icon on the page that opens a pop-up with Contents, as a reviewer's comment does. It is how a slide's speaker notes travel in a PDF.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package widget prints a go-widgets/toolkit widget tree onto a pdfkit page, so any UI composed from toolkit widgets can be "printed" to a PDF.
|
Package widget prints a go-widgets/toolkit widget tree onto a pdfkit page, so any UI composed from toolkit widgets can be "printed" to a PDF. |