gdf

package module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 21, 2024 License: MIT Imports: 22 Imported by: 0

README

Go Reference

Package gdf defines an interface for generating PDFs. It hews closely to the basics of the PDF 2.0 specification and implements a relatively low-level API on which higher-level abstractions can be built. This project is a work in progress.

gdf should be sufficient for most basic English-language PDF use cases. It avoids complexity by purposefully ignoring some aspects of the PDF specification. These omissions may be critical if you need accessibility features or support for multiple languages.

Document Structure

A PDF document is a graph of objects. With the exception of the root PDF object, which has no parent, each object, depending on its type, can have 1 or more parents and 0 or more children. The PDF object can be thought of as a "context" in the sense of, e.g., a Cairo cairo_t or MuPDF fz_context. That is, any object derived from a PDF or one of its children should not be referenced by objects belonging to a different PDF. Operations on objects within a PDF context are not concurrency safe.

The general flow of a gdf PDF document generation program goes:

  1. Create a PDF struct.
  2. Load a Font.
  3. Create a new Page.
  4. Draw text/graphics to the Page's ContentStream.
  5. Append the Page to the PDF.
  6. Write the PDF to an output.

Graphics

Understanding the PDF coordinate system can go a long way to simplifying the use of this package.

Every item is drawn, according to its type, at the origin of its coordinate space - either user space, text space, glyph space (mostly irrelevant), image space, form space, or pattern space (unsupported). Each space has its origin at the lower left corner of the page and increases up and to the right. The coordinate space is then transformed by one or more affine matrices, always including the current transformation matrix, and rendered onto the page's "device space." Text space, for instance, is transformed first by the current text matrix and then by the current transformation matrix.

Transformation matrices are defined by 6 parameters representing the translation, scale, and shear of the X and Y coordinates of a point transformed by the given matrix. Each matrix includes an implicit third column of [0, 0, 1]. Because the space of an object can be scaled or rotated, the effect of certain operations may be difficult to intuit. For example, if the Current Transformation Matrix were [[1 0 0][2 0 0][0 0 1]], to draw a line from (10, 10) to (250, 250) in device space, you would need to first move the path cursor to (10, 5) in user space, and then draw and stroke a path to (250, 125), since the Current Transformation Matrix would scale the y-coordinates of the original space by two. This could be achieved through the following code:

    pdf := gdf.NewPDF() // create a new PDF instance
    page := gdf.NewPage(gdf.A4, gdf.NoMargins) // start a new page
    cs := page.C // content is drawn to a page's content stream
    cs.Concat(gdf.ScaleBy(1, 2)) // concatenate an affine matrix representing a 2*y scaling to the Current Transformation Matrix (by default the identity matrix)
    cs.MoveTo(10, 5) // start a new path at (10, 5); this will be (10, 10) on the page
    cs.LineTo(250, 125) // create a line to (250, 125), which will be (250, 250) on the page
    cs.Stroke() // stroke the line so that it appears on the page
    pdf.AppendPage(&page) // add the page to the current PDF document
    f, err := os.Create("out.pdf")
    if err != nil {
        panic(err)
    }
    defer f.Close()
    pdf.WriteTo(f) // write the PDF to out.pdf

Units

The default basic unit for a PDF document is the point, defined as 1/72 of an inch. However, text can be measured in terms of both points and unscaled font units. The font size (in points) indicates the number of points per side of a glyph's em square. PDF fonts always contain 1000 font units per em square, so a conversion from font units to points can be obtained by calculating fontSize*numFontUnits/1000. The CharSpace and WordSpace elements of a PDF's TextState are defined in font units.

Raster Images

In general, raster images displayed within a PDF document can be thought of as having two parts: a header, containing information about the image's size and encoding characteristics, and a byte slice representing the image's RGB/Gray/CMYK pixels in scanline order. (Alpha channel values must be encoded in a separate grayscale image.) Lossless compression filters can be applied to the byte slice to reduce its size, but this is can be costly. Where possible, it is best to store images as pre-compressed XImage objects. As a notable exception, most JPEG images can be embedded in a PDF without the need to decode and re-encode them.

Fonts

The PDF specification allows for several different types of font. gdf supports only TrueType/OpenType fonts. Unlike in many document formats, a PDF font determines the encoding of the text rendered in that font. Attending to all of the many font types, font table formats, encodings, etc. can quickly become tedious and overwhelming (not to mention difficult to debug without knowledge of non-Latin scripts). It is gdf's aim to be lightweight and simple, rather than comprehensive. gdf therefore only supports Windows-1252 ("WinAnsiEncoding") character encodings. gdf takes care of encoding the UTF-8 strings accepted as input to its functions, but users should be aware that any text that contains characters not included in the Windows-1252 character set will not be rendered as intended.

Text Formatting

While text can be drawn directly to a ContentStream by calling methods like ContentStream.ShowString(), the TextController type implements line-breaking and text-shaping algorithms, and simplifies text formatting by offering an easier to use API.

Annotations and AcroForms

Annotations are objects, rendered by the PDF viewer on a page, that are not part of the Page's ContentStream. gdf supports 2 kinds of annotations: TextAnnots and Widgets. To a far greater extent than the graphics objects controlled by the ContentStream, the visual appearance of an annotation depends on the PDF viewing software.

Widget annotations are the visual representations of an AcroForm field, and must be paired with an AcroField object. gdf supports only a subset of AcroForm capabilities. Whereas the PDF specification describes AcroForms as similar to HTML forms, which are intended to be "submitted" and to trigger an action on submission, the facilities provided by gdf allow only for the user to manipulate the Widget's state without submitting the form and/or triggering an action.

Roadmap

  1. Provide support for embedding JPEG and PNG images.
  2. Write a tool for converting SVGs to XObjects.
  3. Improve the text formatting interface.
  4. More stuff I haven't thought of.

Documentation

Index

Constants

View Source
const (
	AcroButton acroType = iota // Form type that includes checkboxes.
	AcroText
)
View Source
const (
	DefaultFieldFlags fieldFlags = 0

	// fieldFlags common to all AcroField types (Table 227)
	FfReadOnly fieldFlags = 1
	FfRequired fieldFlags = 1 << 1
	FfNoExport fieldFlags = 1 << 2

	// fieldFlags specific to button-type AcroFields (Table 229)
	FfNoToggleToOff  fieldFlags = 1 << 14
	FfRadio          fieldFlags = 1 << 15
	FfPushbutton     fieldFlags = 1 << 16
	FfRadiosInUnison fieldFlags = 1 << 25

	// fieldFlags specific to text-type AcroFields (Table 231)
	FfMultiline       fieldFlags = 1 << 12
	FfPassword        fieldFlags = 1 << 13
	FfFileSelect      fieldFlags = 1 << 20
	FfDoNotSpellCheck fieldFlags = 1 << 22 // can also be used with choice-type AcroFields
	FfDoNotScroll     fieldFlags = 1 << 23
	FfComb            fieldFlags = 1 << 24
	FfRichText        fieldFlags = 1 << 25

	// fieldFlags specific to choice-type AcroFields (Table 233)
	FfCombo             fieldFlags = 1 << 17
	FfEdit              fieldFlags = 1 << 18
	FfSort              fieldFlags = 1 << 19
	FfMultiSelect       fieldFlags = 1 << 21
	FfCommitOnSelChange fieldFlags = 1 << 26
)
View Source
const (
	// Flags specifying the behavior of TextAnnots and Widgets.
	InvisibleAnnot annotFlag = 1 << iota
	HiddenAnnot
	PrintAnnot // IMPORTANT: must be set for an annotation to appear when printed.
	NoZoomAnnot
	NoRotateAnnot
	NoViewAnnot
	ReadOnlyAnnot
	LockedAnnot
	ToggleNoViewAnnot
	LockedContentsAnnot
)
View Source
const (
	// PDF-viewer defined text annotation icon styles.
	CommentIcon textAnnotStyle = iota
	KeyIcon
	NoteIcon
	HelpIcon
	NewParagraphIcon
	ParagraphIcon
	InsertIcon
)
View Source
const (
	SinglePage pageLayout = 1 + iota
	OneColumn
	TwoColumnLeft
	TwoColumnRight
	TwoPageLeft
	TwoPageRight
)
View Source
const (
	DefaultMode pageMode = 1 + iota
	OutlinesMode
	ThumbsMode
	FullScreenMode
	OCMode
	AttachmentsMode
)
View Source
const (
	Deg  float64 = math.Pi / 180 // 1 degree in radians
	In   float64 = 72            // 1 inch in points
	Pica float64 = In / 6        // 1 PostScript pica in points
	Cm   float64 = In / 2.54     // 1 centimeter in points
	Mm   float64 = Cm / 10       // 1 millimeter in points
)
View Source
const (
	UseNone preference
	UseOutlines
	UseThumbs
	UseOC
	L2R
	R2L
	AppDefaultScaling
	NoScaling
	Simplex
	DuplexFlipShortEdge
	DuplexFlipLongEdge
)

Variables

View Source
var (
	Red   = RGBColor{1, 0, 0}
	Green = RGBColor{0, 1, 0}
	Blue  = RGBColor{0, 0, 1}
)
View Source
var (
	Cyan      = CMYKColor{1, 0, 0, 0}
	Magenta   = CMYKColor{0, 1, 0, 0}
	Yellow    = CMYKColor{0, 0, 1, 0}
	CMYKBlack = CMYKColor{0, 0, 0, 1}
)
View Source
var (
	ErrNested = fmt.Errorf("text objects cannot be statically nested")
	ErrClosed = fmt.Errorf("text object is already closed")
)
View Source
var (
	A5        = Rect{0, 0, 148 * Mm, 210 * Mm}
	A4        = Rect{0, 0, 210 * Mm, 297 * Mm}
	A3        = Rect{0, 0, 297 * Mm, 420 * Mm}
	USLetter  = Rect{0, 0, 8.5 * In, 11 * In}
	USLegal   = Rect{0, 0, 8.5 * In, 14 * In}
	USTabloid = Rect{0, 0, 11 * In, 17 * In}
)
View Source
var (
	NoMargins = Margins{}
	HalfInch  = Margins{.5 * In, .5 * In, .5 * In, .5 * In}
	OneInch   = Margins{In, In, In, In}
	OneCm     = Margins{Cm, Cm, Cm, Cm}
	FivePt    = Margins{5, 5, 5, 5}
)
View Source
var (
	ErrChildren = fmt.Errorf("acrofields supported by gdf may have at most 1 child")
)

Functions

func CenterV

func CenterV(height float64, rect Rect) float64

CenterV returns the y offset, in points, from the start of rect, needed to center a line of text vertically based on the text's height. This is a naive approach.

func FUToPt

func FUToPt(n, fontSize float64) float64

FUToPt converts n font units to points given a font size in points. For PDFs, ppem is always 1000.

func PtToFU

func PtToFU(n, fontSize float64) float64

PtToFU converts n points to font units given a font size in points. For PDFs, ppem is always 1000.

func TransformRect

func TransformRect(r Rect, m Matrix) (Point, Point, Point, Point)

TransformRect returns the coordinates of the vertices of R transformed by m in the order LL, UL, LR, UR. The returned points do not necessarily form a valid Rect.

Types

type AcroField added in v0.0.15

type AcroField struct {
	Name  string     // the partial field name
	Flags fieldFlags // field flags
	// contains filtered or unexported fields
}

An AcroField is an interactive element within a PDF. All AcroField elements are children of a document-level acroform node. Each AcroField must be instantiated on a Page by a Widget, and can be associated with only 1 Widget.

type AcroTextCfg added in v0.0.15

type AcroTextCfg struct {
	Flags       annotFlag
	Appearance  *XContent
	Font        *Font
	FontSize    float64
	IsMultiLine bool
	MaxLen      int
}

AcroTextCfgs can be used to instantiate text-type AcroFields. The PrintAnnot flag should be set in almost all cases. The Appearance *XObject can be left nil. Implements WidgetCfger.

type Alignment added in v0.0.9

type Alignment uint
const (
	Left Alignment = iota
	Right
	Center
)

type BlendMode added in v0.0.18

type BlendMode uint
const (
	Normal BlendMode = iota
	Multiply
	Screen
	Darken
	Lighten
	ColorDodge
	ColorBurn
	HardLight
	SoftLight
	Overlay
	Difference
	Exclusion
)

11.3.5.2 Separable blend modes

type CMYKColor

type CMYKColor struct {
	C, M, Y, K float64
}

CMYK Color; C, M, Y, and K must be in [0,1].

type CheckboxCfg added in v0.0.15

type CheckboxCfg struct {
	Flags       annotFlag
	Off, On     *XContent
	IsOnDefault bool
}

CheckBoxCfgs can be used to instantiate checkbox/button-type AcroFields. The PrintAnnot flag should be set in almost all cases. The Off and On *XObjects are mandatory, but can be reused by multiple Widgets. Implements WidgetCfger.

func DefaultCheckbox added in v0.0.15

func DefaultCheckbox() CheckboxCfg

The PDF spec requires a PDF document to describe the appearance of any acroform fields it contains. This means that the appearance of each form field is customizable, but it also means that the 'On' and 'Off' states (as well as the default state) of a checkbox need to be specified in advance. DefaultCheckbox is a convenience function that returns a Checkbox design suitable for use with most sizes of Checkbox. Checkboxes with dimensions smaller than 4 pts will look bad. The returned Checkbox design can be reused for any Checkbox-type (Button) acroform fields of the same size. NOTE: The appearance of a Checkbox may be dependent on the PDF viewer used to render it. This can be especially noticeable when withBorder is true. It is often preferable to draw the Checkbox border separately.

type Color

type Color interface {
	// contains filtered or unexported methods
}

type ColorSpace

type ColorSpace uint
const (
	DeviceGray ColorSpace = iota
	DeviceRGB
	DeviceCMYK
	PatternCS
)

func (ColorSpace) String added in v0.0.15

func (c ColorSpace) String() string

type ContentStream

type ContentStream struct {
	GS
	*TextObj
	// contains filtered or unexported fields
}

func (*ContentStream) BeginText added in v0.0.4

func (c *ContentStream) BeginText() (EndText, error)

BeginText declares a new text object within the ContentStream. It must be called before drawing any text to c. It returns an EndText function, which must be called to close the text object, and an error. All successive calls to BeginText before EndText is called will result in an error. Pairs of BeginText/EndText calls should not be interleaved with pairs of QSave/Restore calls, although each pair can fully contain instances of the other pair. BeginText automatically sets the current Text Matrix and the Line Matrix equal to the identity matrix. If you do not wish for all glyphs to appear at the origin, you must also adjust the current Text Matrix.

func (*ContentStream) CenterH added in v0.0.10

func (c *ContentStream) CenterH(t []rune, rect Rect) float64

CenterH returns the x offset, in points, from the start of rect, needed to center t horizontally, if drawn with c's current font at c's current font size.

func (*ContentStream) Circle added in v0.0.18

func (c *ContentStream) Circle(x, y, r float64)

Circle begins a new path and appends a circle of radius r with a center point of (x, y) to the path. The new current point becomes (x + r, y).

func (*ContentStream) Clip added in v0.0.5

func (c *ContentStream) Clip(wr FillRule)

Clip clips the path. It may appear after the last path construction operator and before the path-painting operator that terminates a path object.

func (*ContentStream) ClosePath added in v0.0.3

func (c *ContentStream) ClosePath()

ClosePath closes the current path; h.

func (*ContentStream) ClosePathFillStroke added in v0.0.5

func (c *ContentStream) ClosePathFillStroke(wr FillRule)

ClosePathFillStroke closes the path, fills the path, and then strokes the path; b.

func (*ContentStream) ClosePathStroke added in v0.0.5

func (c *ContentStream) ClosePathStroke()

ClosePathStroke closes and strokes the path; s.

func (*ContentStream) Concat added in v0.0.9

func (c *ContentStream) Concat(m Matrix)

Sets c's Current Transformation Matrix (c.GS.Matrix) to the matrix product of m and c.GS.Matrix.

func (*ContentStream) CubicBezier1 added in v0.0.10

func (c *ContentStream) CubicBezier1(x1, y1, x2, y2, x3, y3 float64)

CubicBezier1 appends a cubic Bézier curve to the current path; c. The curve extends from the current point to (x3, y3) using using (x1, y1) and (x2, y2) as the Bézier control points. If the PathState is not Building, no action is taken.

func (*ContentStream) CubicBezier2 added in v0.0.10

func (c *ContentStream) CubicBezier2(x2, y2, x3, y3 float64)

CubicBezier2 appends a cubic Bézier curve to the current path; v. The curve extends from the current point to (x3, y3), using the current point and (x2, y2) as the Bézier control points. If the PathState is not Building, no action is taken.

func (*ContentStream) CubicBezier3 added in v0.0.10

func (c *ContentStream) CubicBezier3(x1, y1, x3, y3 float64)

CubicBezier3 appends a cubic Bézier curve to the current path; y. The curve extends from the current point to (x3, y3), using (x1, y1) and (x3, y3) as the Bézier control points. If the PathState is not Building, no action is taken.

func (*ContentStream) DrawImage added in v0.1.0

func (c *ContentStream) DrawImage(img *Image)

func (*ContentStream) DrawImageTo added in v0.1.0

func (c *ContentStream) DrawImageTo(dst Rect, x *Image)

func (*ContentStream) DrawLine added in v0.0.15

func (c *ContentStream) DrawLine(x1, y1, x2, y2 float64)

DrawLine is a convenience function that strokes a line from Point{x1,y1} to Point{x2,y2}.

func (*ContentStream) DrawXContent added in v0.1.0

func (c *ContentStream) DrawXContent(x *XContent)

DrawXContent draws x to c at c's current point.

func (*ContentStream) DrawXContentTo added in v0.1.0

func (c *ContentStream) DrawXContentTo(dst Rect, x *XContent)

DrawXContent adjusts the CTM such that the contents of x are drawn to dst.

func (*ContentStream) Ellipse added in v0.0.18

func (c *ContentStream) Ellipse(x, y, rx, ry float64)

func (*ContentStream) EndPath added in v0.0.3

func (c *ContentStream) EndPath()

EndPath ends the current path. It is used primarily to apply changes to the current clipping path; n.

func (*ContentStream) ExtentFU added in v0.0.10

func (c *ContentStream) ExtentFU(t []rune) float64

ExtentFU returns the extent in font units of t, when set in c's current font. The returned value accounts for kerning, word spacing, and horizontal scaling.

func (*ContentStream) ExtentFontFU added in v0.0.10

func (c *ContentStream) ExtentFontFU(t []rune, f *Font) float64

ExtentFontFU returns the extent in font units of t, when set in font f. The returned value accounts for kerning, word spacing, and horizontal scaling.

func (*ContentStream) ExtentFontPts added in v0.0.10

func (c *ContentStream) ExtentFontPts(t []rune, f *Font, size float64) float64

ExtentFontPts returns the extent in points of text, when set in font f at the given size. The returned value accounts for kerning, word spacing, and horizontal scaling.

func (*ContentStream) ExtentKernsFU added in v0.0.10

func (c *ContentStream) ExtentKernsFU(t []rune, kerns []int) (float64, error)

ExtentKernsFU returns the extent in font units of t, when set in c's current font. The returned value accounts for kerning, word spacing, and horizontal scaling.

func (*ContentStream) ExtentKernsPts added in v0.0.10

func (c *ContentStream) ExtentKernsPts(t []rune, kerns []int) (float64, error)

ExtentKernsPts returns the extent in points of t, when set in c's current font at the current font size. The returned value accounts for kerning, word spacing, and horizontal scaling.

func (*ContentStream) ExtentPts added in v0.0.10

func (c *ContentStream) ExtentPts(t []rune) float64

ExtentPts returns the extent in points of t, when set in c's current font at the current font size. The returned value accounts for kerning, word spacing, and horizontal scaling.

func (*ContentStream) Fill

func (c *ContentStream) Fill(wr FillRule)

Fill fills the path.

func (*ContentStream) FillStroke added in v0.0.3

func (c *ContentStream) FillStroke(wr FillRule)

FillStroke fills and then strokes the path.

func (*ContentStream) LineString added in v0.0.15

func (c *ContentStream) LineString(s string)

LineString writes s (without kerning) to c and advances the text matrix by the extent of s; '.

func (*ContentStream) LineTo added in v0.0.3

func (c *ContentStream) LineTo(x, y float64)

LineTo appends a straight line from the current point to (x, y), which becomes the new current point; l. If the PathState is not Building, no action is taken.

func (*ContentStream) MoveTo added in v0.0.3

func (c *ContentStream) MoveTo(x, y float64)

MoveTo begins a new path starting at (x, y); m.

func (*ContentStream) NextLine added in v0.0.11

func (c *ContentStream) NextLine()

NextLine begins a new text line by setting the current text matrix and line matrix equal to the line matrix offset by (0, -c.Leading); T*.

func (*ContentStream) QRestore added in v0.0.4

func (c *ContentStream) QRestore() error

QRestore pops the most recent addition to c's GSStack off the stack and sets c's current GS equal to that value. It returns an error if c's GSStack is empty or if c.BeginText() has been called after the last call to c.QSave(), and the returned EndText function has not yet been called.

func (*ContentStream) QSave added in v0.0.4

func (c *ContentStream) QSave()

QSave pushes the current GS (graphics sate) to c's GSStack (graphics state stack).

func (*ContentStream) RawExtentFU added in v0.0.10

func (c *ContentStream) RawExtentFU(t []rune) float64

RawExtentFU returns the extent in font units of t, when set in c's current font. The returned value accounts for word spacing and horizontal scaling, but does not account for kerning.

func (*ContentStream) RawExtentPts added in v0.0.10

func (c *ContentStream) RawExtentPts(t []rune) float64

RawExtentPts returns the extent in points of t, when set in c's current font at the current font size. The returned value accounts for word spacing and horizontal scaling, but does not account for kerning.

func (*ContentStream) RawTextCursor

func (c *ContentStream) RawTextCursor() Point

RawTextCursor returns the x and y coordinates of the point (0,0,1) transformed only by the current text matrix.

func (*ContentStream) Re

func (c *ContentStream) Re(x, y, w, h float64)

Re appends a rectangle, of width w and height h, starting at the point (x, y), to the current path; re.

func (*ContentStream) Re2 added in v0.0.8

func (c *ContentStream) Re2(r Rect)

Re2 appends r to the current path; it is intended as a possibly more convenient version of Re.

func (*ContentStream) SetAlphaConst added in v0.0.18

func (c *ContentStream) SetAlphaConst(a float64, stroke bool)

SetAlphaConst sets c's non-stroking or stroking alpha constant to a, which must be a value in [0.0, 1.0], where 0 corresponds to full transparency and 1 corresponds to full opacity.

func (*ContentStream) SetCharSpace added in v0.0.11

func (c *ContentStream) SetCharSpace(f float64)

SetCharSpace sets the content stream's character spacing (c.TextState.CharSpace) f.

func (*ContentStream) SetColor

func (c *ContentStream) SetColor(cl Color)

Sets c's non-stroking color (NColor) to cl and sets its NColorSpace to cl's ColorSpace.

func (*ContentStream) SetColorStroke

func (c *ContentStream) SetColorStroke(cl Color)

Sets c's stroking color (SColor) to cl and sets its SColorSpace to cl's ColorSpace.

func (*ContentStream) SetDashPattern added in v0.0.4

func (c *ContentStream) SetDashPattern(d DashPattern)

Sets the dash pattern (c.GS.DashPattern) to d.

func (*ContentStream) SetExtGS added in v0.0.18

func (c *ContentStream) SetExtGS(extGState map[string]any)

SetExtGS sets c's graphic state to extGS. Use with caution, and refer to 8.4.5 / Table 57 of the PDF spec.

func (*ContentStream) SetFlatness added in v0.0.12

func (c *ContentStream) SetFlatness(f float64)

Set the flatness (c.GS.Flatness) to f.

func (*ContentStream) SetFont added in v0.0.11

func (c *ContentStream) SetFont(size float64, font *Font)

SetFont sets the current font size and font (c.TextState.Font and c.TextState.FontSize) to size and font.

func (*ContentStream) SetHScale added in v0.0.11

func (c *ContentStream) SetHScale(f float64)

SetHScale sets the content stream's horizontal text scaling percentage (c.TextState.Scale) to f. The default value is 100.0 percent.

func (*ContentStream) SetLeading added in v0.0.11

func (c *ContentStream) SetLeading(f float64)

SetLeading sets the content stream's text leading/line height (c.TextState.Leading) to f.

func (*ContentStream) SetLineCap added in v0.0.4

func (c *ContentStream) SetLineCap(lc LineCap)

Sets the line cap style (c.GS.LineCap) to lc.

func (*ContentStream) SetLineJoin added in v0.0.4

func (c *ContentStream) SetLineJoin(lj LineJoin)

Sets the line join style (c.GS.LineJoin) to lj.

func (*ContentStream) SetLineWidth added in v0.0.4

func (c *ContentStream) SetLineWidth(f float64)

Sets the line width (c.GS.LineWidth) to f.

func (*ContentStream) SetMiterLimit added in v0.0.4

func (c *ContentStream) SetMiterLimit(ml float64)

Sets miter limit (c.GS.MiterLimit) to ml.

func (*ContentStream) SetRenderIntent added in v0.0.4

func (c *ContentStream) SetRenderIntent(n string)

Sets the rendering intent (c.GS.RenderingIntent) to n.

func (*ContentStream) SetRenderMode added in v0.0.11

func (c *ContentStream) SetRenderMode(r RenderMode)

SetRenderMode sets the current text rendering mode (c.TextState.RenderMode) to r.

func (*ContentStream) SetRise added in v0.0.11

func (c *ContentStream) SetRise(f float64)

SetRise sets the current text rise (c.TextState.RenderMode) to f.

func (*ContentStream) SetTextMatrix added in v0.0.11

func (c *ContentStream) SetTextMatrix(m Matrix)

SetTextMatrix sets the current text object's text matrix and line matrix to m; Tm.

func (*ContentStream) SetWordSpace added in v0.0.11

func (c *ContentStream) SetWordSpace(f float64)

SetWordSpace sets the content stream's word spacing (c.TextState.WordSpace) to f.

func (*ContentStream) ShowString added in v0.0.11

func (c *ContentStream) ShowString(s string)

ShowString writes s (without kerning) to c and advances the text matrix by the extent of s; Tj.

func (*ContentStream) ShowText added in v0.0.11

func (c *ContentStream) ShowText(t []rune, kerns []int) error

ShowText writes t (with kerning) to c and advances the text matrix by the extent of t; TJ.

func (*ContentStream) Stroke added in v0.0.3

func (c *ContentStream) Stroke()

Stroke strokes the path; S.

func (*ContentStream) TextCursor

func (c *ContentStream) TextCursor() Point

TextCursor returns the x and y coordinates of the point (0,0,1) transformed by the current text matrix and the current transformation matrix.

func (*ContentStream) TextOffset added in v0.0.11

func (c *ContentStream) TextOffset(x, y float64)

TextOffset offsets the current text object's text matrix by x and y, and sets the text object's line matrix equal to its text matrix.

func (*ContentStream) TextOffsetLeading added in v0.0.11

func (c *ContentStream) TextOffsetLeading(x, y float64)

TextOffsetLeading sets the content stream's current leading to y and then calls c.TextOffset(x, y).

type ControllerCfg added in v0.0.9

type ControllerCfg struct {
	Alignment
	Justification
	RenderMode
	FontSize       float64
	Leading        float64
	IsIndented     bool
	NColor, SColor Color   // default non-stroking and stroking colors
	Looseness      float64 // the ratio of the maximum allowable space advance and the normal space advance in justified text
	Tightness      float64 // the ratio of the minimum allowable space advance and the normal space advance in justified text
	IsBold, IsItal bool
}

A ControllerCfg specifies options for the formatting of text drawn by a TextController.

func NewControllerCfg added in v0.0.9

func NewControllerCfg(fontSize, leading float64) ControllerCfg

type DashPattern

type DashPattern struct {
	Array []int
	Phase int
}

type EndText added in v0.0.4

type EndText func() error

An EndText function return by c.BeginText() must be invoked to close a section of text written to c.

type FillRule added in v0.0.18

type FillRule bool

A FillRule represents an algorithm for determining whether a particular point is interior to a path. See ISO 32000-2:2020 sections 8.5.3.3.2 and 8.5.3.3.3 for further details. NonZero is the default, but EvenOdd can produce results that are easier to intuit.

const (
	NonZero FillRule = false
	EvenOdd FillRule = true
)

type Filter

type Filter uint

A Filter is a compression algorithm that can compress internal PDF data.

const (
	DefaultFilter Filter = iota
	Flate
	DCTDecode
	NoFilter
)

func (Filter) String added in v0.0.15

func (f Filter) String() string

type Font

type Font struct {
	SFNT *sfnt.Font // The source TrueType or OpenType font.
	// contains filtered or unexported fields
}

A Font represents a TrueType/OpenType font. Any given Font struct should be used on at most 1 PDF. To use the same underlying font on multiple PDF files, derive a new Font struct from the source font file or bytes for each PDF.

func LoadTrueType added in v0.0.5

func LoadTrueType(b []byte, flag FontFlag) (*Font, error)

LoadTrueType returns a *Font object, which can be used for drawing text to a ContentStream or XObject, and an error.

func LoadTrueTypeFile added in v0.0.5

func LoadTrueTypeFile(path string, flag FontFlag) (*Font, error)

LoadTrueTypeFile returns a *Font object, which can be used for drawing text to a ContentStream or XObject, and an error.

func (*Font) AscDesc added in v0.1.0

func (f *Font) AscDesc(r rune) (float64, float64)

AscDesc returns the ascent and descent, in font units, of the glyph corresponding to the given rune.

func (*Font) GlyphAdvance added in v0.1.0

func (f *Font) GlyphAdvance(r rune) int

GlyphAdvance returns the advance of r in font units.

func (*Font) ShapedGlyphAdv added in v0.1.0

func (f *Font) ShapedGlyphAdv(r1, r2 rune) (int, int)

ShapedGlyphAdv returns the advance and kerning of r1 when set before r2.

func (*Font) TextAscDesc added in v0.1.0

func (f *Font) TextAscDesc(text []rune) (float64, float64)

TextAscDesc returns the maximum ascent and descent, in font units, of the glyphs in the given text.

type FontFamily added in v0.0.9

type FontFamily struct {
	Regular, Bold, Ital, BoldItal *Font
}

type FontFlag

type FontFlag uint32
const (
	FixedPitch  FontFlag = 1 << 0
	Serif       FontFlag = 1 << 1
	Symbolic    FontFlag = 1 << 2
	Script      FontFlag = 1 << 3
	Nonsymbolic FontFlag = 1 << 5
	Italic      FontFlag = 1 << 6
	AllCap      FontFlag = 1 << 16
	SmallCap    FontFlag = 1 << 17
	ForceBold   FontFlag = 1 << 18

	NoSubset FontFlag = 1 << 19 // Prevent gdf from subsetting a font. Not in the PDF spec.
)

type FormatText added in v0.0.9

type FormatText []rune

FormatText represents a slice of runes that can specify the formatting and content of the source text. The TextController applies the following rules to the formatting directives contained in FormatText:

  1. rune(-1) is interpreted as end of text. Any runes that appear after this character will not be parsed.
  2. rune(-2) is interpreted as a color indicator. This character must be followed by three comma-separated 3-digit integers in [0,255] that specify the red, green, and blue components of an RGBColor. (This is equivalent to setting the non-stroking color of the document to RGBColor{R:float64(red)/255, G:float64(green)/255, B:float64(blue)/255}).
  3. rune(-3) toggles bold text on and off.
  4. rune(-4) toggles italic text on and off. The bold and italic indicators can be used to switch among fonts in a given font family.

type GColor

type GColor float64

Grayscale color; must be in [0,1].

const (
	Black GColor = 0
	Gray  GColor = .5
	White GColor = 1
)

type GS

type GS struct {
	Matrix // Current Transformation Matrix
	TextState
	LineCap
	LineJoin
	DashPattern
	PathState
	CurPt               Point      // Current path point
	NColorSpace         ColorSpace // non-stroking
	SColorSpace         ColorSpace // stroking
	NColor              Color      // non-stroking
	SColor              Color      // stroking
	LineWidth           float64
	MiterLimit          float64
	RenderingIntent     string
	StrokeAdj           bool
	BlendMode           string
	SoftMask            string
	AlphaConstant       float64
	StrokeAlphaConstant float64
	AlphaSource         bool
	BPComp              string
	Overprint           bool
	OverprintMode       uint
	BlackGen            string
	UndercolorRem       string
	Transfer            string
	Halftone            string
	Flatness            float64
	Smoothness          float64
}

A GS struct represents a ContentStream's graphics state.

type Image added in v0.1.0

type Image struct {
	Data             []byte
	Width            int // The width of the image in pixels.
	Height           int // The height of the image in pixels.
	ColorSpace       ColorSpace
	BitsPerComponent int    // The bit depth of the image's encoding.
	Alpha            *Image // An image's alpha channel, if present, must be encoded as a separate image. The Alpha image's ColorSpace should be DeviceGray.
	AppliedFilter    Filter // The filter used to pre-compress the image Data.
	RawDataLen       int    // The length (in bytes) of the uncompressed image Data; only needed if AppliedFilter is nonzero.
	// contains filtered or unexported fields
}

An Image represents a raster image.

func (*Image) Bytes added in v0.1.0

func (x *Image) Bytes() []byte

type InfoDict added in v0.0.15

type InfoDict struct {
	Title        string
	Author       string
	Subject      string
	Keywords     string
	Creator      string
	Producer     string
	CreationDate time.Time
	ModDate      time.Time
	// contains filtered or unexported fields
}

An InfoDict represents a PDF's document information dictionary, which describes document level metadata. The PDF 2.0 Specification deprecates the use of all InfoDict fields except CreationDate and ModDate in favor of XMP Metadata. Adding an InfoDict to a PDF therefore has the effect of setting the output PDF version to 1.7. Although this is feature deprecated for PDF 2.0, info dictionary metadata has broader support among PDF readers than XMP, and is the most common method for representing certain document properties.

type Justification added in v0.0.9

type Justification uint
const (
	Ragged Justification = iota
	Justified
)

type LineCap

type LineCap uint
const (
	ButtCap LineCap = iota
	RoundCap
	SquareCap
)

type LineJoin

type LineJoin uint
const (
	MiterJoin LineJoin = iota
	RoundJoin
	BevelJoin
)

type Margins

type Margins struct {
	Left, Right, Top, Bottom float64
}

Each field in a Margins struct represents an interior offset from the corresponding edge of a Rect.

type Matrix

type Matrix struct {
	A float64 // X scale
	B float64 // X shear
	C float64 // Y shear
	D float64 // Y scale
	E float64 // X offset
	F float64 // Y offset
}

A Matrix represents the first 2 columns of a 3-column affine transformation matrix, whose third column is always [0,0,1]. Matrices are used to represent transformations applied to an object's coordinate space by the PDF viewer. A ContentStream's Current Transformation Matrix (CTM, c.GS.Matrix) and text matrix (c.TextObj.Matrix) are the only two matrices within a PDF that gdf allows users to directly manipulate. CTMs can be altered by calling c.Concat(m). Text matrices are implicitly altered by any text showing operation, and can be explicitly set through calls to c.SetTextMatrix(m). Whereas Concat sets the CTM to the matrix product of m and the CTM, SetTextMatrix replaces the current text matrix with m.

func Mul

func Mul(m1, m2 Matrix) Matrix

Mul returns the matrix product of m1 and m2. Note: this operation is not commutative.

func NewMatrix

func NewMatrix() Matrix

NewMatrix returns a new instance of the Identity Matrix. This function should be used instead of Matrix{} or *new(Matrix), since empty matrices can result in undefined behavior. When combining transformations, the PDF spec's recommended order of operations is translate, rotate, scale or skew.

func Rotate

func Rotate(theta float64) Matrix

Rotate returns a Matrix that represents the rotation of a coordinate space counter-clockwise about the origin by theta.

func ScaleBy

func ScaleBy(scaleX, scaleY float64) Matrix

ScaleBy returns a Matrix that represents the scaling of a coordinate space by scaleX and scaleY.

func Skew

func Skew(xTheta, yTheta float64) Matrix

Skew returns a Matrix that represents the transformation of a coordinate space by skewing its x axis by xTheta and its y axis by yTheta.

func Translate

func Translate(dX, dY float64) Matrix

Translate returns a Matrix that represents the translation of a coordinate space by dX and dY.

func (Matrix) Inverse added in v0.0.12

func (m Matrix) Inverse() (Matrix, error)

Inverse returns the inverse of m and an error. If m has no inverse, an empty Matrix and a non-nil error are returned.

type PDF

type PDF struct {
	// contains filtered or unexported fields
}

func NewPDF

func NewPDF() *PDF

func (*PDF) AddXMPMetaData added in v0.0.8

func (p *PDF) AddXMPMetaData(b []byte)

Includes the XMP data represented by b as document-level metadata for the encoded PDF. Currently, gdf does not perform any validation on b.

func (*PDF) AppendPage added in v0.0.8

func (p *PDF) AppendPage(page *Page)

Appends page to p.

func (*PDF) InsertPage added in v0.0.8

func (p *PDF) InsertPage(page *Page, i int) error

Inserts page at index i of the PDF's internal page structure.

func (*PDF) NewAcroField added in v0.0.15

func (p *PDF) NewAcroField() *AcroField

All AcroFields should be created using the PDF.NewAcroField() method. Once an AcroField is created, it must be paired with a Widget and added to a Page that must, in turn, be appended to p.

func (*PDF) NewImage added in v0.1.0

func (p *PDF) NewImage(x XImage) *Image

NewImage returns an Image that can be drawn to ContentStreams derived from p.

func (*PDF) ReplacePage added in v0.0.8

func (p *PDF) ReplacePage(page *Page, i int) error

ReplacePage replaces the page at index i of the PDF's internal page structure with page.

func (*PDF) SetInfo added in v0.0.15

func (p *PDF) SetInfo(id InfoDict)

func (*PDF) SetLanguage added in v0.0.15

func (p *PDF) SetLanguage(s string)

SetLanguage sets the default natural language of all text in the PDF to s, which must be a string representation of a valid BCP 47 language tag. (See golang.org/x/text/language). NOTE: gdf currently only supports Windows-1252 ("WinAnsiEncoding") for most textual elements in a PDF document. Text that appears in annotations may represent a wider range of characters, depending on the reader used to view the PDF.

func (*PDF) SetPageLayout added in v0.0.15

func (p *PDF) SetPageLayout(pl pageLayout)

func (*PDF) SetPageMode added in v0.0.15

func (p *PDF) SetPageMode(pm pageMode)

func (*PDF) SetViewPrefs added in v0.0.15

func (p *PDF) SetViewPrefs(v ViewPrefs)

SetViewPrefs indicates the desired display settings for the PDF viewer to use when displaying p.

func (*PDF) WriteTo added in v0.0.9

func (p *PDF) WriteTo(w io.Writer) (int64, error)

Builds the PDF and writes it to w. Attempting to write an empty PDF, i.e., one without any content streams, causes a panic.

type Page

type Page struct {
	C        *ContentStream
	MediaBox Rect
	CropBox  Rect // "the rectangle of user space corresponding to the visible area of the intended output medium (display window or printed page)"
	Margins
	// contains filtered or unexported fields
}

func NewPage

func NewPage(pageSize Rect, margins Margins) Page

NewPage returns a new Page object with the specified size and margins.

func (*Page) AddAcroField added in v0.0.15

func (p *Page) AddAcroField(w *Widget, f *AcroField, dst Rect, strokeBorder bool) error

AddAcroField adds an AcroField, whose visible component is w, to p. dst specifies the area of p's user space onto which w is drawn. If strokeBorder is true, dst is added to the page's path, and the border is stroked with the current stroke width and stroke color. Once f has been added to p, p must be appended to the PDF from which f was derived prior to the invocation of PDF.WriteTo().

func (*Page) Annotate added in v0.0.15

func (p *Page) Annotate(t *TextAnnot, r Rect)

Annotate draws the TextAnnot t to the area of p described by r.

type PageRange added in v0.0.15

type PageRange struct {
	Start, End uint
}

type PathState

type PathState uint

A PathState represents a ContentStream's current path operations state.

const (
	NoPath PathState = iota
	Building
	Clipping
)

type Point

type Point struct {
	X, Y float64
}

Point represents a Point. All Points implicitly include a Z coordinate of 1.

func Transform

func Transform(p Point, m Matrix) Point

Transform returns the Point resulting from the transformation of p by m.

func (Point) ToRect added in v0.0.15

func (p Point) ToRect(w, h float64) Rect

p.ToRect returns a Rect where p is the lower left vertex, w is the width, and h is the height.

type RGBColor

type RGBColor struct {
	R, G, B float64
}

RGB Color; R,G, and B must be in [0,1].

type Rect

type Rect struct {
	LLX, LLY, URX, URY float64
}

A Rect represents a rectangular area of a coordinate space, where (LLX, LLY) is the lower left vertex and (URX, URY) is the upper right vertex.

func NewRect added in v0.0.13

func NewRect(ll, ur Point) Rect

NewRect returns a Rect where ll is the lower left vertex and ur is the upper right vertex.

func (Rect) Angles added in v0.0.5

func (r Rect) Angles() (float64, float64)

Angles returns the angle, in radians, formed by the lower side of the rectangle and the lower-left to upper-right diagonal, and that angle's complement.

func (Rect) Bounds added in v0.0.11

func (r Rect) Bounds(m Margins) Rect

Bounds returns the Rect that results from applying m to r without checking whether that Rect is valid.

func (Rect) Diagonal added in v0.0.5

func (r Rect) Diagonal() float64

Diagonal returns the length of r's diagonal.

func (Rect) Height

func (r Rect) Height() float64

Height returns r's height.

func (Rect) Landscape added in v0.0.11

func (r Rect) Landscape() Rect

Landscape returns the rectangle that results from swapping r's x and y values.

func (Rect) String added in v0.0.15

func (r Rect) String() string

func (Rect) Width

func (r Rect) Width() float64

Width returns r's width.

type RenderMode

type RenderMode uint
const (
	FillText RenderMode = iota
	StrokeText
	FillStrokeText
	Invisible
	FillTextAddPath
	StrokeTextAddPath
	FillStrokeTextAddPath
	AddTextPath
)

type TextAnnot added in v0.0.15

type TextAnnot struct {
	Contents     string // Text to be displayed by the annotation.
	User         string // Name of the user creating the comment.
	ModDate      time.Time
	CreationDate time.Time
	Subject      string
	Open         bool
	Name         string // Unique annotation name.
	Flags        annotFlag
	IconStyle    textAnnotStyle
	Appearance   *XContent // Optional; if nil the IconStyle is used; overrides the IconStyle if non-nil.
	Color
	// contains filtered or unexported fields
}

A TextAnnot is text that appears in a pop-up when the user hovers over the annotated area of a page. The Appearance *XObject, if provided, describes the appearance of the TextAnnot's note icon, which is normally always visible on the viewed page. The Color field specifies the color of the pop-up annotation.

type TextController added in v0.0.9

type TextController struct {
	// contains filtered or unexported fields
}

A TextController is a struct that aids in writing text to a ContentStream. The TextController can break text into lines and paragraphs, determine the appropriate kerning for glyphs in a string, and draw text according to the format specified by the ControllerCfg struct.

func NewTextController added in v0.0.9

func NewTextController(src FormatText, lineWidth float64, f FontFamily, cfg ControllerCfg) (TextController, error)

NewTextController returns a TextController that is ready to write src to ContentStreams. It returns an invalid TextController and an error if it encounters a problem while parsing and shaping src.

func (*TextController) DrawText added in v0.0.9

func (tc *TextController) DrawText(c *ContentStream, area Rect) (Point, bool, error)

type TextObj

type TextObj struct {
	Matrix
	LineMatrix Matrix
}

type TextState

type TextState struct {
	*Font
	FontSize  float64 // points
	CharSpace float64 // points
	WordSpace float64 // points
	HScale    float64 // horizontal scale, as a percentage of the normal width
	Leading   float64 // points
	Rise      float64 // points
	RenderMode
}

type ViewPrefs added in v0.0.15

type ViewPrefs struct {
	HideToolbar           bool
	HideMenu              bool
	HideWindowUI          bool
	FitWindow             bool
	CenterWindow          bool
	DisplayDocTitle       bool
	NonFullScreenPageMode bool
	Direction             preference
	PrintScaling          preference
	Duplex                preference
	PrintPageRange        []PageRange
	NumCopies             uint
}

A ViewPrefs struct can be used to configure details of how the PDF viewer handles the output file.

type Widget added in v0.0.15

type Widget struct {
	AcroType     acroType
	Flags        annotFlag // 12.5.3 annotation flags
	User         string
	ModDate      time.Time
	CreationDate time.Time
	Subject      string
	Open         bool
	Name         string // unique text string identifying the Widget
	Opts         []string
	// contains filtered or unexported fields
}

A Widget is an annotation that serves as the visible representation of an interactive acroform field.

func NewWidget added in v0.0.15

func NewWidget(cfg WidgetCfger) *Widget

NewWidget returns a new *Widget as configured by cfg.

type WidgetCfger added in v0.0.15

type WidgetCfger interface {
	// contains filtered or unexported methods
}

WidgetCfger is an interface used to configure Widgets and their associated AcroFields. It is implemented by AcroTextCfg and CheckboxCfg.

type XContent added in v0.1.0

type XContent struct {
	ContentStream
	BBox Rect
}

An XContent struct represents a PDF form-type XObject. It is essentially a ContentStream that can be displayed by multiple Pages of a PDF.

func NewXContent added in v0.1.0

func NewXContent(b []byte, BBox Rect) *XContent

func (*XContent) Bytes added in v0.1.0

func (x *XContent) Bytes() []byte

type XImage added in v0.0.15

type XImage struct {
	Data             []byte
	Width            int // The width of the image in pixels.
	Height           int // The height of the image in pixels.
	ColorSpace       ColorSpace
	BitsPerComponent int    // The bit depth of the image's encoding.
	AppliedFilter    Filter // The filter used to pre-compress the image Data.
	RawDataLen       int    // The length (in bytes) of the uncompressed image Data; only needed if AppliedFilter is nonzero.
	Alpha            *XImage
}

An XImage represents an image that is external to any given PDF.

func LoadXImage added in v0.1.0

func LoadXImage(r io.Reader) (XImage, error)

LoadXImage reads a gob-encoded XImage from r.

func (*XImage) FlateCompress added in v0.1.0

func (x *XImage) FlateCompress() error

FlateCompress compresses x's Data using the Flate filter, and updates the XImage to indicate that the filter has been applied. Most images (except JPEGs) are compressed using this filter automatically when the output PDF file is written. However, completing the process ahead of time by calling FlateCompress and then re-using a pre-decoded and pre-compressed XImage can be significantly more efficient.

func (XImage) SaveTo added in v0.1.0

func (x XImage) SaveTo(w io.Writer) error

SaveTo writes the gob encoding of x to w.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL