Documentation
¶
Overview ¶
Package creator provides a high-level API for creating and modifying PDF documents.
Package creator provides a high-level API for creating PDF documents.
This package offers a fluent, developer-friendly interface for PDF creation, hiding the complexity of the underlying domain model.
Example:
c := creator.New()
c.SetTitle("My Document")
c.SetAuthor("John Doe")
page, err := c.NewPageWithSize(creator.A4)
// Add content to page...
err = c.WriteToFile("output.pdf")
Package creator provides a high-level API for creating and modifying PDF documents.
Package creator provides a high-level API for creating and modifying PDF documents.
Index ¶
- Constants
- Variables
- func CMToPoints(cm float64) float64
- func InchesToPoints(inches float64) float64
- func MMToPoints(mm float64) float64
- func Merge(output string, inputs ...string) error
- func MergeDocuments(output string, docs ...*document.Document) error
- func PointsToCM(points float64) float64
- func PointsToInches(points float64) float64
- func PointsToMM(points float64) float64
- type Alignment
- type Appender
- func (a *Appender) AddPage(size PageSize) (*Page, error)
- func (a *Appender) CanFlattenForm() bool
- func (a *Appender) Close() error
- func (a *Appender) Document() *document.Document
- func (a *Appender) FlattenFields(names ...string) error
- func (a *Appender) FlattenForm() error
- func (a *Appender) GetFieldValue(name string) (interface{}, error)
- func (a *Appender) GetFormFields() ([]*forms.FieldInfo, error)
- func (a *Appender) GetPage(index int) (*Page, error)
- func (a *Appender) GetParserReader() *parser.Reader
- func (a *Appender) HasForm() bool
- func (a *Appender) PageCount() int
- func (a *Appender) SetFieldValue(name string, value interface{}) error
- func (a *Appender) SetKeywords(keywords ...string)
- func (a *Appender) SetMetadata(title, author, subject string)
- func (a *Appender) WriteToFile(path string) error
- func (a *Appender) WriteToFileContext(ctx context.Context, path string) error
- type BezierOptions
- type BezierSegment
- type BlendMode
- type Block
- func (b *Block) Clear()
- func (b *Block) ContentHeight() float64
- func (b *Block) ContentWidth() float64
- func (b *Block) Draw(d Drawable) error
- func (b *Block) DrawAt(d Drawable, x, y float64) error
- func (b *Block) GetDrawables() []DrawablePosition
- func (b *Block) GetLayoutContext() *LayoutContext
- func (b *Block) Height() float64
- func (b *Block) Margins() Margins
- func (b *Block) MoveCursor(dx, dy float64)
- func (b *Block) SetCursor(x, y float64)
- func (b *Block) SetHeight(height float64)
- func (b *Block) SetMargins(m Margins)
- func (b *Block) SetWidth(width float64)
- func (b *Block) Width() float64
- type Bookmark
- type Border
- type Chapter
- func (c *Chapter) Add(d Drawable) error
- func (c *Chapter) Content() []Drawable
- func (c *Chapter) Draw(ctx *LayoutContext, page *Page) error
- func (c *Chapter) FullTitle() string
- func (c *Chapter) GetAllChapters() []*Chapter
- func (c *Chapter) Height(ctx *LayoutContext) float64
- func (c *Chapter) Level() int
- func (c *Chapter) NewSubChapter(title string) *Chapter
- func (c *Chapter) Number() []int
- func (c *Chapter) NumberString() string
- func (c *Chapter) PageIndex() int
- func (c *Chapter) Parent() *Chapter
- func (c *Chapter) SetStyle(style ChapterStyle)
- func (c *Chapter) SetTitle(title string)
- func (c *Chapter) Style() ChapterStyle
- func (c *Chapter) SubChapters() []*Chapter
- func (c *Chapter) Title() string
- type ChapterStyle
- type CircleOptions
- type Color
- type ColorCMYK
- type ColorRGBA
- type ColorSpace
- type ColorStop
- type Creator
- func (c *Creator) AddBookmark(title string, pageIndex int, level int) error
- func (c *Creator) AddChapter(ch *Chapter) error
- func (c *Creator) Bookmarks() []Bookmark
- func (c *Creator) Bytes() ([]byte, error)
- func (c *Creator) Chapters() []*Chapter
- func (c *Creator) DisableTOC()
- func (c *Creator) Document() *document.Document
- func (c *Creator) EnableTOC()
- func (c *Creator) FooterHeight() float64
- func (c *Creator) HeaderHeight() float64
- func (c *Creator) NewPage() (*Page, error)
- func (c *Creator) NewPageWithDimensions(widthPt, heightPt float64) (*Page, error)
- func (c *Creator) NewPageWithSize(size PageSize, orientation ...Orientation) (*Page, error)
- func (c *Creator) PageCount() int
- func (c *Creator) SetAuthor(author string)
- func (c *Creator) SetEncryption(opts EncryptionOptions) error
- func (c *Creator) SetFooterFunc(f FooterFunc)
- func (c *Creator) SetFooterHeight(h float64)
- func (c *Creator) SetHeaderFunc(f HeaderFunc)
- func (c *Creator) SetHeaderHeight(h float64)
- func (c *Creator) SetKeywords(keywords ...string)
- func (c *Creator) SetMargins(top, right, bottom, left float64) error
- func (c *Creator) SetMetadata(title, author, subject string)
- func (c *Creator) SetPageSize(size PageSize)
- func (c *Creator) SetSkipFooterOnFirstPage(skip bool)
- func (c *Creator) SetSkipHeaderOnFirstPage(skip bool)
- func (c *Creator) SetSubject(subject string)
- func (c *Creator) SetTitle(title string)
- func (c *Creator) SkipFooterOnFirstPage() bool
- func (c *Creator) SkipHeaderOnFirstPage() bool
- func (c *Creator) TOC() *TOC
- func (c *Creator) TOCEnabled() bool
- func (c *Creator) Validate() error
- func (c *Creator) WriteTo(w io.Writer) (int64, error)
- func (c *Creator) WriteToContext(ctx context.Context, w io.Writer) (int64, error)
- func (c *Creator) WriteToFile(path string) error
- func (c *Creator) WriteToFileContext(ctx context.Context, path string) error
- type CustomFont
- func (f *CustomFont) Build() error
- func (f *CustomFont) GetSubset() *fonts.FontSubset
- func (f *CustomFont) GetTTF() *fonts.TTFFont
- func (f *CustomFont) ID() string
- func (f *CustomFont) MeasureString(text string, size float64) float64
- func (f *CustomFont) PostScriptName() string
- func (f *CustomFont) UnitsPerEm() uint16
- func (f *CustomFont) UseChar(ch rune)
- func (f *CustomFont) UseString(text string)
- type Division
- func (d *Division) Add(drawable Drawable) *Division
- func (d *Division) Background() *Color
- func (d *Division) Clear() *Division
- func (d *Division) ContentWidth(ctx *LayoutContext) float64
- func (d *Division) Draw(ctx *LayoutContext, page *Page) error
- func (d *Division) Drawables() []Drawable
- func (d *Division) Height(ctx *LayoutContext) float64
- func (d *Division) Padding() Margins
- func (d *Division) SetBackground(c Color) *Division
- func (d *Division) SetBorder(b Border) *Division
- func (d *Division) SetBorderBottom(b Border) *Division
- func (d *Division) SetBorderLeft(b Border) *Division
- func (d *Division) SetBorderRight(b Border) *Division
- func (d *Division) SetBorderTop(b Border) *Division
- func (d *Division) SetMargins(m Margins) *Division
- func (d *Division) SetMinHeight(h float64) *Division
- func (d *Division) SetPadding(top, right, bottom, left float64) *Division
- func (d *Division) SetPaddingAll(p float64) *Division
- func (d *Division) SetWidth(w float64) *Division
- type Drawable
- type DrawablePosition
- type EllipseOptions
- type EncryptionAlgorithm
- type EncryptionOptions
- type Fill
- type FillRule
- type FontName
- type FooterFunc
- type FooterFunctionArgs
- type Gradient
- type GradientType
- type GraphicsOpType
- type GraphicsOperation
- type GraphicsState
- type HeaderFunc
- type HeaderFunctionArgs
- type HighlightAnnotation
- type Image
- func (img *Image) AlphaMask() []byte
- func (img *Image) BitsPerComponent() int
- func (img *Image) ColorSpace() ColorSpace
- func (img *Image) Components() int
- func (img *Image) Data() []byte
- func (img *Image) Format() string
- func (img *Image) HasAlpha() bool
- func (img *Image) Height() int
- func (img *Image) Width() int
- type LayoutContext
- func (ctx *LayoutContext) AvailableHeight() float64
- func (ctx *LayoutContext) AvailableWidth() float64
- func (ctx *LayoutContext) CanFit(height float64) bool
- func (ctx *LayoutContext) ContentBottom() float64
- func (ctx *LayoutContext) ContentLeft() float64
- func (ctx *LayoutContext) ContentRight() float64
- func (ctx *LayoutContext) ContentTop() float64
- func (ctx *LayoutContext) CurrentPDFY() float64
- func (ctx *LayoutContext) MoveCursor(dx, dy float64)
- func (ctx *LayoutContext) NewLine(lineHeight float64)
- func (ctx *LayoutContext) ResetX()
- func (ctx *LayoutContext) SetCursor(x, y float64)
- type LineCap
- type LineJoin
- type LineOptions
- type LinkStyle
- type List
- func (l *List) Add(text string) *List
- func (l *List) AddItem(item ListItem) *List
- func (l *List) AddSubList(subList *List) *List
- func (l *List) Draw(ctx *LayoutContext, page *Page) error
- func (l *List) Height(ctx *LayoutContext) float64
- func (l *List) SetBulletChar(char string) *List
- func (l *List) SetColor(c Color) *List
- func (l *List) SetFont(font FontName, size float64) *List
- func (l *List) SetIndent(indent float64) *List
- func (l *List) SetLineSpacing(spacing float64) *List
- func (l *List) SetMarkerIndent(indent float64) *List
- func (l *List) SetMarkerType(t MarkerType) *List
- func (l *List) SetNumberFormat(f NumberFormat) *List
- func (l *List) SetStartNumber(n int) *List
- type ListItem
- type Margins
- type MarkerType
- type Merger
- func (m *Merger) AddAllPages(path string) error
- func (m *Merger) AddPageRange(path string, start, end int) error
- func (m *Merger) AddPages(path string, pageNums ...int) error
- func (m *Merger) Close() error
- func (m *Merger) Write(path string) error
- func (m *Merger) WriteContext(ctx context.Context, path string) error
- type NumberFormat
- type Orientation
- type Page
- func (p *Page) AddField(field interface{}) error
- func (p *Page) AddHighlightAnnotation(annotation *HighlightAnnotation) error
- func (p *Page) AddInternalLink(text string, destPage int, x, y float64, font FontName, size float64) error
- func (p *Page) AddLink(text, url string, x, y float64, font FontName, size float64) error
- func (p *Page) AddLinkStyled(text, url string, x, y float64, style LinkStyle) error
- func (p *Page) AddStampAnnotation(annotation *StampAnnotation) error
- func (p *Page) AddStrikeOutAnnotation(annotation *StrikeOutAnnotation) error
- func (p *Page) AddText(text string, x, y float64, font FontName, size float64) error
- func (p *Page) AddTextAnnotation(annotation *TextAnnotation) error
- func (p *Page) AddTextColor(text string, x, y float64, font FontName, size float64, color Color) error
- func (p *Page) AddTextColorAlpha(text string, x, y float64, font FontName, size float64, color Color, ...) error
- func (p *Page) AddTextColorCMYK(text string, x, y float64, font FontName, size float64, color ColorCMYK) error
- func (p *Page) AddTextColorRotated(text string, x, y float64, font FontName, size float64, color Color, ...) error
- func (p *Page) AddTextColorRotatedAlpha(text string, x, y float64, font FontName, size float64, color Color, ...) error
- func (p *Page) AddTextCustomFont(text string, x, y float64, font *CustomFont, size float64) error
- func (p *Page) AddTextCustomFontColor(text string, x, y float64, font *CustomFont, size float64, color Color) error
- func (p *Page) AddTextCustomFontColorAlpha(text string, x, y float64, font *CustomFont, size float64, color Color, ...) error
- func (p *Page) AddTextCustomFontColorRotated(text string, x, y float64, font *CustomFont, size float64, color Color, ...) error
- func (p *Page) AddTextCustomFontColorRotatedAlpha(text string, x, y float64, font *CustomFont, size float64, color Color, ...) error
- func (p *Page) AddTextCustomFontRotated(text string, x, y float64, font *CustomFont, size float64, rotation float64) error
- func (p *Page) AddTextRotated(text string, x, y float64, font FontName, size float64, rotation float64) error
- func (p *Page) AddUnderlineAnnotation(annotation *UnderlineAnnotation) error
- func (p *Page) BeginClipRect(x, y, width, height float64) error
- func (p *Page) ContentHeight() float64
- func (p *Page) ContentWidth() float64
- func (p *Page) Draw(d Drawable) error
- func (p *Page) DrawAt(d Drawable, x, y float64) error
- func (p *Page) DrawBezierCurve(segments []BezierSegment, opts *BezierOptions) error
- func (p *Page) DrawCircle(cx, cy, radius float64, opts *CircleOptions) error
- func (p *Page) DrawEllipse(cx, cy, rx, ry float64, opts *EllipseOptions) error
- func (p *Page) DrawImage(img *Image, x, y, width, height float64) error
- func (p *Page) DrawImageFit(img *Image, x, y, maxWidth, maxHeight float64) error
- func (p *Page) DrawLine(x1, y1, x2, y2 float64, opts *LineOptions) error
- func (p *Page) DrawPolygon(vertices []Point, opts *PolygonOptions) error
- func (p *Page) DrawPolyline(vertices []Point, opts *PolylineOptions) error
- func (p *Page) DrawQuadBezierCurve(segments []QuadBezierSegment, opts *BezierOptions) error
- func (p *Page) DrawRect(x, y, width, height float64, opts *RectOptions) error
- func (p *Page) DrawRectFilled(x, y, width, height float64, fillColor Color) error
- func (p *Page) DrawTextClipped(text string, textX, textY, clipX, clipY, clipW, clipH float64, ...) error
- func (p *Page) DrawWatermark(wm *TextWatermark) error
- func (p *Page) EndClip() error
- func (p *Page) GetLayoutContext() *LayoutContext
- func (p *Page) GraphicsOperations() []GraphicsOperation
- func (p *Page) Height() float64
- func (p *Page) Margins() Margins
- func (p *Page) MoveCursor(x, y float64)
- func (p *Page) Rotate(degrees int) error
- func (p *Page) Rotation() int
- func (p *Page) SetMargins(top, right, bottom, left float64) error
- func (p *Page) SetRotation(degrees int) error
- func (p *Page) Surface() *Surface
- func (p *Page) TextOperations() []TextOperation
- func (p *Page) Width() float64
- type PageRange
- type PageSize
- type Paint
- type Paragraph
- func (p *Paragraph) Alignment() Alignment
- func (p *Paragraph) Color() Color
- func (p *Paragraph) Draw(ctx *LayoutContext, page *Page) error
- func (p *Paragraph) Font() FontName
- func (p *Paragraph) FontSize() float64
- func (p *Paragraph) Height(ctx *LayoutContext) float64
- func (p *Paragraph) LineSpacing() float64
- func (p *Paragraph) SetAlignment(a Alignment) *Paragraph
- func (p *Paragraph) SetColor(c Color) *Paragraph
- func (p *Paragraph) SetFont(font FontName, size float64) *Paragraph
- func (p *Paragraph) SetLineSpacing(spacing float64) *Paragraph
- func (p *Paragraph) SetText(text string) *Paragraph
- func (p *Paragraph) Text() string
- func (p *Paragraph) WrapTextLines(availableWidth float64) []string
- type Path
- func (p *Path) AddArc(center Point, radius, startAngle, endAngle float64) *Path
- func (p *Path) AddCircle(center Point, radius float64) *Path
- func (p *Path) AddEllipse(rect Rect) *Path
- func (p *Path) AddRect(rect Rect) *Path
- func (p *Path) AddRoundedRect(rect Rect, radius float64) *Path
- func (p *Path) Bounds() Rect
- func (p *Path) Clone() *Path
- func (p *Path) Close() *Path
- func (p *Path) CubicTo(c1x, c1y, c2x, c2y, x, y float64) *Path
- func (p *Path) IsEmpty() bool
- func (p *Path) LineTo(x, y float64) *Path
- func (p *Path) MoveTo(x, y float64) *Path
- func (p *Path) QuadraticTo(cx, cy, x, y float64) *Path
- type Permission
- type Point
- type PolygonOptions
- type PolylineOptions
- type QuadBezierSegment
- type Rect
- type RectOptions
- type Splitter
- func (s *Splitter) Close() error
- func (s *Splitter) ExtractPages(pages ...int) (*document.Document, error)
- func (s *Splitter) SetFilenamePattern(pattern string)
- func (s *Splitter) Split(outputDir string) error
- func (s *Splitter) SplitByRanges(ranges ...PageRange) error
- func (s *Splitter) SplitByRangesContext(ctx context.Context, ranges ...PageRange) error
- func (s *Splitter) SplitContext(ctx context.Context, outputDir string) error
- type StampAnnotation
- type StrikeOutAnnotation
- type Stroke
- func (s *Stroke) Validate() error
- func (s *Stroke) WithDash(dashArray []float64, dashPhase float64) *Stroke
- func (s *Stroke) WithLineCap(cap LineCap) *Stroke
- func (s *Stroke) WithLineJoin(join LineJoin) *Stroke
- func (s *Stroke) WithMiterLimit(limit float64) *Stroke
- func (s *Stroke) WithWidth(width float64) *Stroke
- type StyledParagraph
- func (sp *StyledParagraph) Append(text string) *StyledParagraph
- func (sp *StyledParagraph) AppendStyled(text string, style TextStyle) *StyledParagraph
- func (sp *StyledParagraph) Draw(ctx *LayoutContext, page *Page) error
- func (sp *StyledParagraph) Height(ctx *LayoutContext) float64
- func (sp *StyledParagraph) SetAlignment(a Alignment) *StyledParagraph
- func (sp *StyledParagraph) SetLineSpacing(spacing float64) *StyledParagraph
- type Surface
- func (s *Surface) CurrentBlendMode() BlendMode
- func (s *Surface) CurrentClipPath() *Path
- func (s *Surface) CurrentFill() *Fill
- func (s *Surface) CurrentOpacity() float64
- func (s *Surface) CurrentStroke() *Stroke
- func (s *Surface) CurrentTransform() Transform
- func (s *Surface) DrawPath(path *Path) error
- func (s *Surface) DrawRect(rect Rect) error
- func (s *Surface) FillPath(path *Path) error
- func (s *Surface) Pop()
- func (s *Surface) PushBlendMode(mode BlendMode)
- func (s *Surface) PushClipCircle(center Point, radius float64) error
- func (s *Surface) PushClipEllipse(rect Rect) error
- func (s *Surface) PushClipPath(path *Path, rule FillRule) error
- func (s *Surface) PushClipRect(rect Rect) error
- func (s *Surface) PushOpacity(opacity float64) error
- func (s *Surface) PushTransform(t Transform)
- func (s *Surface) SetFill(fill *Fill)
- func (s *Surface) SetStroke(stroke *Stroke)
- func (s *Surface) StackDepth() int
- func (s *Surface) StrokePath(path *Path) error
- type TOC
- func (t *TOC) Draw(ctx *LayoutContext, page *Page) error
- func (t *TOC) GetEntries() []TOCEntry
- func (t *TOC) Height(ctx *LayoutContext) float64
- func (t *TOC) Leader() string
- func (t *TOC) SetLeader(leader string)
- func (t *TOC) SetShowPageNumbers(show bool)
- func (t *TOC) SetStyle(style TOCStyle)
- func (t *TOC) SetTitle(title string)
- func (t *TOC) ShowPageNumbers() bool
- func (t *TOC) Style() TOCStyle
- func (t *TOC) Title() string
- type TOCEntry
- type TOCStyle
- type TableCell
- type TableLayout
- func (t *TableLayout) AddHeaderRow(cells ...string) *TableLayout
- func (t *TableLayout) AddRow(cells ...string) *TableLayout
- func (t *TableLayout) AddRowCells(cells ...TableCell) *TableLayout
- func (t *TableLayout) ColumnCount() int
- func (t *TableLayout) Draw(ctx *LayoutContext, page *Page) error
- func (t *TableLayout) HeaderRowCount() int
- func (t *TableLayout) Height(_ *LayoutContext) float64
- func (t *TableLayout) RowCount() int
- func (t *TableLayout) SetBorder(width float64, color Color) *TableLayout
- func (t *TableLayout) SetCellPadding(padding float64) *TableLayout
- func (t *TableLayout) SetColumnWidths(widths ...float64) *TableLayout
- type TableRow
- type TextAnnotation
- type TextChunk
- type TextOperation
- type TextStyle
- type TextWatermark
- func (w *TextWatermark) Color() Color
- func (w *TextWatermark) Font() FontName
- func (w *TextWatermark) FontSize() float64
- func (w *TextWatermark) Opacity() float64
- func (w *TextWatermark) Position() WatermarkPosition
- func (w *TextWatermark) Rotation() float64
- func (w *TextWatermark) SetColor(color Color) error
- func (w *TextWatermark) SetFont(font FontName, size float64) error
- func (w *TextWatermark) SetOpacity(opacity float64) error
- func (w *TextWatermark) SetPosition(position WatermarkPosition) error
- func (w *TextWatermark) SetRotation(degrees float64) error
- func (w *TextWatermark) Text() string
- type Transform
- type UnderlineAnnotation
- type WatermarkPosition
Examples ¶
Constants ¶
const ( // PermissionPrint allows printing the document. PermissionPrint = security.PermissionPrint // PermissionModify allows modifying the document. PermissionModify = security.PermissionModify // PermissionCopy allows copying text and graphics. PermissionCopy = security.PermissionCopy // PermissionAnnotate allows adding or modifying annotations. PermissionAnnotate = security.PermissionAnnotate // PermissionFillForms allows filling form fields. PermissionFillForms = security.PermissionFillForms // PermissionExtract allows extracting text for accessibility. PermissionExtract = security.PermissionExtract // PermissionAssemble allows assembling the document. PermissionAssemble = security.PermissionAssemble // PermissionPrintHighQuality allows high-quality printing. PermissionPrintHighQuality = security.PermissionPrintHighQuality // PermissionAll grants all permissions. PermissionAll = security.PermissionAll // PermissionNone grants no permissions. PermissionNone = security.PermissionNone )
Permission constants.
const ( // DefaultHeaderHeight is the default height for headers (50 points). DefaultHeaderHeight = 50.0 DefaultFooterHeight = 30.0 )
Default header and footer heights in points.
const ( // PointsPerInch is the number of PDF points in one inch. // 1 inch = 72 points (PostScript/PDF standard). PointsPerInch = document.PointsPerInch // PointsPerMM is the number of PDF points in one millimeter. // 1 mm = 72/25.4 ≈ 2.83465 points. PointsPerMM = document.PointsPerMM // PointsPerCM is the number of PDF points in one centimeter. // 1 cm = 72/2.54 ≈ 28.3465 points. PointsPerCM = document.PointsPerCM )
Unit conversion constants.
Use these with the conversion helper functions to convert between real-world units and PDF points before calling NewPageWithDimensions.
const ( // StampApproved represents an "Approved" stamp. StampApproved = document.StampApproved // StampNotApproved represents a "Not Approved" stamp. StampNotApproved = document.StampNotApproved // StampDraft represents a "Draft" stamp. StampDraft = document.StampDraft // StampFinal represents a "Final" stamp. StampFinal = document.StampFinal // StampConfidential represents a "Confidential" stamp. StampConfidential = document.StampConfidential // StampForComment represents a "For Comment" stamp. StampForComment = document.StampForComment // StampForPublicRelease represents a "For Public Release" stamp. StampForPublicRelease = document.StampForPublicRelease // StampAsIs represents an "As Is" stamp. StampAsIs = document.StampAsIs // StampDepartmental represents a "Departmental" stamp. StampDepartmental = document.StampDepartmental // StampExperimental represents an "Experimental" stamp. StampExperimental = document.StampExperimental // StampExpired represents an "Expired" stamp. StampExpired = document.StampExpired // StampNotForPublicRelease represents a "Not For Public Release" stamp. StampNotForPublicRelease = document.StampNotForPublicRelease )
Predefined stamp names (exported for user convenience).
Variables ¶
var ( // ErrEmptyBookmarkTitle is returned when bookmark title is empty. ErrEmptyBookmarkTitle = errors.New("bookmark title cannot be empty") // ErrInvalidBookmarkPage is returned when page index is invalid. ErrInvalidBookmarkPage = errors.New("invalid bookmark page index") // ErrInvalidBookmarkLevel is returned when level is invalid. ErrInvalidBookmarkLevel = errors.New("invalid bookmark level") )
Bookmark-related errors.
var ( // ErrInvalidMargins is returned when margins are negative. ErrInvalidMargins = errors.New("margins must be non-negative") // ErrWriterNotImplemented is returned when PDF writer is not yet implemented. ErrWriterNotImplemented = errors.New("PDF writer not yet implemented (Phase 3 TODO)") )
Errors.
var ( // ErrUnsupportedImageFormat is returned for unsupported image formats. ErrUnsupportedImageFormat = errors.New("unsupported image format (supported: JPEG, PNG)") // ErrInvalidImageDimensions is returned for zero/negative dimensions. ErrInvalidImageDimensions = errors.New("image dimensions must be positive") )
Errors.
var ( // ErrContentOutOfBounds is returned when content is positioned outside margins. ErrContentOutOfBounds = errors.New("content is outside page margins") // ErrUnsupportedFieldType is returned when an unsupported field type is added. ErrUnsupportedFieldType = errors.New("unsupported form field type") )
Errors.
var ( // ErrPopWithoutPush is returned when Pop is called without a matching Push. ErrPopWithoutPush = errors.New("Pop() called without matching Push*()") // ErrInvalidRect is returned when a rectangle has invalid dimensions. ErrInvalidRect = errors.New("invalid rectangle dimensions") )
Errors
var ( // Black is pure black (RGB: 0, 0, 0). Black = Color{0, 0, 0} // White is pure white (RGB: 255, 255, 255). White = Color{1, 1, 1} // Red is pure red (RGB: 255, 0, 0). Red = Color{1, 0, 0} // Green is pure green (RGB: 0, 255, 0). Green = Color{0, 1, 0} // Blue is pure blue (RGB: 0, 0, 255). Blue = Color{0, 0, 1} // Gray is 50% gray (RGB: 128, 128, 128). Gray = Color{0.5, 0.5, 0.5} // DarkGray is 25% gray (RGB: 64, 64, 64). DarkGray = Color{0.25, 0.25, 0.25} // LightGray is 75% gray (RGB: 192, 192, 192). LightGray = Color{0.75, 0.75, 0.75} // Yellow is pure yellow (RGB: 255, 255, 0). Yellow = Color{1, 1, 0} // Cyan is pure cyan (RGB: 0, 255, 255). Cyan = Color{0, 1, 1} // Magenta is pure magenta (RGB: 255, 0, 255). Magenta = Color{1, 0, 1} )
Predefined colors for common use cases.
var ( // CMYKBlack is pure black (100% black ink). CMYKBlack = ColorCMYK{0, 0, 0, 1} // CMYKWhite is white (no ink - paper color). CMYKWhite = ColorCMYK{0, 0, 0, 0} // CMYKCyan is pure cyan (100% cyan ink). CMYKCyan = ColorCMYK{1, 0, 0, 0} // CMYKMagenta is pure magenta (100% magenta ink). CMYKMagenta = ColorCMYK{0, 1, 0, 0} // CMYKYellow is pure yellow (100% yellow ink). CMYKYellow = ColorCMYK{0, 0, 1, 0} // CMYKRed is red (magenta + yellow). CMYKRed = ColorCMYK{0, 1, 1, 0} // CMYKGreen is green (cyan + yellow). CMYKGreen = ColorCMYK{1, 0, 1, 0} // CMYKBlue is blue (cyan + magenta). CMYKBlue = ColorCMYK{1, 1, 0, 0} )
Predefined CMYK colors for common print use cases.
var ( // TransparentBlack is fully transparent black (RGBA: 0, 0, 0, 0). TransparentBlack = ColorRGBA{0, 0, 0, 0} // SemiTransparentBlack is 50% transparent black. SemiTransparentBlack = ColorRGBA{0, 0, 0, 0.5} // TransparentWhite is fully transparent white. TransparentWhite = ColorRGBA{1, 1, 1, 0} // SemiTransparentWhite is 50% transparent white. SemiTransparentWhite = ColorRGBA{1, 1, 1, 0.5} // TransparentRed is fully transparent red. TransparentRed = ColorRGBA{1, 0, 0, 0} // SemiTransparentRed is 50% transparent red. SemiTransparentRed = ColorRGBA{1, 0, 0, 0.5} // TransparentGreen is fully transparent green. TransparentGreen = ColorRGBA{0, 1, 0, 0} // SemiTransparentGreen is 50% transparent green. SemiTransparentGreen = ColorRGBA{0, 1, 0, 0.5} // TransparentBlue is fully transparent blue. TransparentBlue = ColorRGBA{0, 0, 1, 0} // SemiTransparentBlue is 50% transparent blue. SemiTransparentBlue = ColorRGBA{0, 0, 1, 0.5} )
Predefined transparent colors for common use cases.
var ( // ErrInvalidColor is returned when a color has invalid component values. ErrInvalidColor = errors.New("invalid color component values") )
Errors
var ( // ErrInvalidFill is returned when a fill configuration is invalid. ErrInvalidFill = errors.New("invalid fill configuration") )
Errors
var ( // ErrInvalidStroke is returned when a stroke configuration is invalid. ErrInvalidStroke = errors.New("invalid stroke configuration") )
Errors
Functions ¶
func CMToPoints ¶ added in v0.4.0
CMToPoints converts centimeters to PDF points.
Example:
width := creator.CMToPoints(21) // ≈ 595 points (A4 width)
func InchesToPoints ¶ added in v0.4.0
InchesToPoints converts inches to PDF points.
Example:
width := creator.InchesToPoints(8.5) // 612 points (Letter width)
func MMToPoints ¶ added in v0.4.0
MMToPoints converts millimeters to PDF points.
Example:
width := creator.MMToPoints(210) // ≈ 595 points (A4 width)
func Merge ¶
Merge merges multiple PDF files into a single output file.
This is a convenience function that merges all pages from all input files in the order they are specified.
Parameters:
- output: Path to the output PDF file
- inputs: Paths to the input PDF files (must have at least 1)
Returns an error if:
- No input files specified
- Any input file cannot be opened or is invalid
- Output file cannot be created
Example:
err := creator.Merge("output.pdf", "file1.pdf", "file2.pdf", "file3.pdf")
if err != nil {
log.Fatal(err)
}
func MergeDocuments ¶
MergeDocuments merges multiple already-opened Document instances.
This is useful when you already have documents loaded in memory or when you want to merge specific documents programmatically.
Parameters:
- output: Path to the output PDF file
- docs: Document instances to merge (must have at least 1)
Returns an error if:
- No documents specified
- Output file cannot be created
Example:
doc1, _ := gxpdf.Open("file1.pdf")
doc2, _ := gxpdf.Open("file2.pdf")
err := creator.MergeDocuments("output.pdf", doc1, doc2)
func PointsToCM ¶ added in v0.4.0
PointsToCM converts PDF points to centimeters.
Example:
cm := creator.PointsToCM(595) // ≈ 21 cm (A4 width)
func PointsToInches ¶ added in v0.4.0
PointsToInches converts PDF points to inches.
Example:
inches := creator.PointsToInches(612) // 8.5 (Letter width)
func PointsToMM ¶ added in v0.4.0
PointsToMM converts PDF points to millimeters.
Example:
mm := creator.PointsToMM(595) // ≈ 210 mm (A4 width)
Types ¶
type Appender ¶
type Appender struct {
// contains filtered or unexported fields
}
Appender provides functionality to modify existing PDF documents.
It allows you to:
- Open an existing PDF for modification
- Add new pages to the document
- Add content to existing pages (watermarks, stamps, annotations)
- Merge multiple PDFs into one
- Save changes incrementally (append mode) or create a new file
Example - Add watermark to all pages:
app, err := creator.NewAppender("input.pdf")
if err != nil {
log.Fatal(err)
}
defer app.Close()
for i := 0; i < app.PageCount(); i++ {
page, err := app.GetPage(i)
if err != nil {
log.Fatal(err)
}
page.AddText("CONFIDENTIAL", 300, 400, creator.HelveticaBold, 48)
}
err = app.WriteToFile("output.pdf")
Example - Append new page:
app, err := creator.NewAppender("input.pdf")
if err != nil {
log.Fatal(err)
}
defer app.Close()
newPage, err := app.AddPage(creator.A4)
if err != nil {
log.Fatal(err)
}
newPage.AddText("New content", 100, 700, creator.Helvetica, 12)
err = app.WriteToFile("output.pdf")
func NewAppender ¶
NewAppender opens an existing PDF file for modification.
The file is opened and parsed immediately. Remember to call Close() when done to release resources.
Returns an error if:
- File cannot be opened
- File is not a valid PDF
- PDF is encrypted (not yet supported)
Example:
app, err := creator.NewAppender("existing.pdf")
if err != nil {
log.Fatal(err)
}
defer app.Close()
func (*Appender) AddPage ¶
AddPage adds a new page with the specified size.
The new page is appended to the end of the document. Returns the newly created page for adding content.
Example:
page, err := app.AddPage(creator.A4)
if err != nil {
log.Fatal(err)
}
page.AddText("New content", 100, 700, creator.Helvetica, 12)
func (*Appender) CanFlattenForm ¶ added in v0.2.0
CanFlattenForm returns true if the document has fields that can be flattened.
func (*Appender) Close ¶
Close closes the underlying PDF file and releases resources.
It's safe to call Close() multiple times.
Example:
app, err := creator.NewAppender("input.pdf")
if err != nil {
log.Fatal(err)
}
defer app.Close()
func (*Appender) Document ¶
Document returns the underlying domain document.
This is provided for advanced use cases where you need direct access to the domain model. Most users should use the Appender API instead.
Example:
doc := app.Document() // Direct domain operations...
func (*Appender) FlattenFields ¶ added in v0.2.0
FlattenFields converts specific form fields to static content.
If no names are provided, all fields are flattened.
Example:
// Flatten only specific fields
app.FlattenFields("name", "email", "signature")
func (*Appender) FlattenForm ¶ added in v0.2.0
FlattenForm converts all form fields to static content.
This removes interactivity by rendering field appearances directly onto pages. The resulting PDF looks the same but fields are no longer editable.
Use this when:
- Creating final versions of filled forms
- Preventing further editing
- Reducing file complexity
Example:
app, err := creator.NewAppender("filled_form.pdf")
if err != nil {
log.Fatal(err)
}
defer app.Close()
if err := app.FlattenForm(); err != nil {
log.Fatal(err)
}
app.WriteToFile("flattened.pdf")
func (*Appender) GetFieldValue ¶ added in v0.2.0
GetFieldValue returns the current value of a form field.
Returns the value from pending updates if the field has been modified, otherwise returns the original value from the PDF.
Example:
value, err := app.GetFieldValue("name")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Name: %v\n", value)
func (*Appender) GetFormFields ¶ added in v0.2.0
GetFormFields returns all form fields from the PDF.
This includes field metadata such as name, type, current value, and options.
Example:
fields, err := app.GetFormFields()
if err != nil {
log.Fatal(err)
}
for _, f := range fields {
fmt.Printf("%s (%s): %v\n", f.Name, f.Type, f.Value)
}
func (*Appender) GetPage ¶
GetPage returns the page at the specified index (0-based).
This allows you to add content to existing pages. The page can be modified by calling methods like AddText, DrawLine, etc.
Returns an error if the page index is out of bounds.
Example:
page, err := app.GetPage(0)
if err != nil {
log.Fatal(err)
}
page.AddText("Watermark", 300, 400, creator.HelveticaBold, 48)
func (*Appender) GetParserReader ¶
GetParserReader returns the underlying parser.Reader for advanced operations.
This is useful for extracting text, images, or other content from the original PDF. Most users should not need this - use the high-level Appender methods instead.
Example:
parserReader := app.GetParserReader() // Advanced parser operations...
func (*Appender) HasForm ¶ added in v0.2.0
HasForm returns true if the PDF contains an interactive form.
Example:
if app.HasForm() {
fields, _ := app.GetFormFields()
fmt.Printf("Found %d form fields\n", len(fields))
}
func (*Appender) PageCount ¶
PageCount returns the total number of pages in the document.
This includes both original pages and newly added pages.
Example:
count := app.PageCount()
fmt.Printf("Document has %d pages\n", count)
func (*Appender) SetFieldValue ¶ added in v0.2.0
SetFieldValue sets a form field value by name.
The value type depends on the field type:
- Text field: string
- Checkbox: bool or string ("Yes", "Off")
- Radio button: string (option name)
- Choice field: string or []string (for multi-select)
Returns an error if:
- The field is not found
- The PDF has no interactive form
- The value type is incompatible with the field type
Example:
app, err := creator.NewAppender("form.pdf")
if err != nil {
log.Fatal(err)
}
defer app.Close()
// Fill text field
if err := app.SetFieldValue("name", "John Doe"); err != nil {
log.Fatal(err)
}
// Fill checkbox
if err := app.SetFieldValue("agree", true); err != nil {
log.Fatal(err)
}
app.WriteToFile("filled.pdf")
func (*Appender) SetKeywords ¶
SetKeywords sets document keywords for search/indexing.
Example:
app.SetKeywords("modified", "watermarked", "confidential")
func (*Appender) SetMetadata ¶
SetMetadata updates the document metadata.
This replaces any existing metadata in the original PDF.
Example:
app.SetMetadata("Modified Document", "John Doe", "Updated Report")
func (*Appender) WriteToFile ¶
WriteToFile writes the modified PDF to a file.
This creates a new PDF file with all modifications applied. The original file is not modified.
For large PDFs, consider using WriteToFileIncremental() instead, which appends only the changes (not yet implemented).
Example:
err := app.WriteToFile("output.pdf")
if err != nil {
log.Fatal(err)
}
func (*Appender) WriteToFileContext ¶
WriteToFileContext writes the modified PDF with context support.
This allows cancellation and timeout control.
Example:
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() err := app.WriteToFileContext(ctx, "output.pdf")
type BezierOptions ¶
type BezierOptions struct {
// Color is the curve color (RGB, 0.0 to 1.0 range).
// If ColorCMYK is set, this field is ignored.
Color Color
// ColorCMYK is the curve color in CMYK color space (optional).
// If set, this takes precedence over Color (RGB).
ColorCMYK *ColorCMYK
// Width is the curve width in points (default: 1.0).
Width float64
// Dashed enables dashed curve rendering.
Dashed bool
// DashArray defines the dash pattern (e.g., [3, 1] for "3 on, 1 off").
// Only used when Dashed is true.
DashArray []float64
// DashPhase is the starting offset into the dash pattern.
// Only used when Dashed is true.
DashPhase float64
// Closed determines if the curve path should be closed.
// If true, a line is drawn from the last segment's end point
// back to the first segment's start point.
Closed bool
// FillColor is the fill color for closed curves (nil = no fill).
// Only used when Closed is true.
// Mutually exclusive with FillGradient.
FillColor *Color
// FillGradient is the gradient fill for closed curves (nil = no gradient fill).
// Only used when Closed is true.
// Mutually exclusive with FillColor.
FillGradient *Gradient
// Opacity is the bezier curve opacity (0.0 = transparent, 1.0 = opaque).
// Optional. If set, applies transparency via ExtGState.
// Affects both stroke and fill (if Closed is true).
// Range: [0.0, 1.0]
Opacity *float64
}
BezierOptions configures Bézier curve drawing.
type BezierSegment ¶
type BezierSegment struct {
// Start is the starting point (P0).
// For the first segment, this is the curve's starting point.
// For subsequent segments, this should match the previous segment's End point.
Start Point
// C1 is the first control point.
C1 Point
// C2 is the second control point.
C2 Point
// End is the ending point (P1).
End Point
}
BezierSegment represents a cubic Bézier curve segment.
A cubic Bézier curve is defined by:
- Start point (P0)
- First control point (C1)
- Second control point (C2)
- End point (P1)
The curve starts at P0, is pulled toward C1 and C2, and ends at P1.
type BlendMode ¶ added in v0.2.0
type BlendMode int
BlendMode defines how colors blend with the background.
const ( // BlendModeNormal is the default blend mode (simple alpha compositing). BlendModeNormal BlendMode = iota // BlendModeMultiply multiplies the source and destination colors. BlendModeMultiply // BlendModeScreen inverts, multiplies, and inverts again. BlendModeScreen // BlendModeOverlay combines Multiply and Screen based on destination. BlendModeOverlay // BlendModeDarken selects the darker of source and destination. BlendModeDarken // BlendModeLighten selects the lighter of source and destination. BlendModeLighten // BlendModeColorDodge brightens the destination based on source. BlendModeColorDodge // BlendModeColorBurn darkens the destination based on source. BlendModeColorBurn // BlendModeHardLight is like Overlay but uses source instead of destination. BlendModeHardLight // BlendModeSoftLight is a softer version of HardLight. BlendModeSoftLight // BlendModeDifference subtracts the darker from the lighter. BlendModeDifference // BlendModeExclusion is like Difference but with lower contrast. BlendModeExclusion )
type Block ¶
type Block struct {
// contains filtered or unexported fields
}
Block represents a rectangular area for drawing content.
Blocks are used as containers for header/footer content and provide a bounded region where Drawable elements can be placed. Content is positioned relative to the block's origin (top-left corner).
Example:
block := NewBlock(500, 50)
block.SetMargins(Margins{Left: 10, Right: 10})
p := NewParagraph("Header Text")
block.Draw(p)
func NewBlock ¶
NewBlock creates a new block with the specified dimensions.
Parameters:
- width: Block width in points
- height: Block height in points
Example:
block := NewBlock(500, 50) // 500pt wide, 50pt tall
func (*Block) ContentHeight ¶
ContentHeight returns the usable height inside the block (height minus margins).
func (*Block) ContentWidth ¶
ContentWidth returns the usable width inside the block (width minus margins).
func (*Block) Draw ¶
Draw adds a drawable element to the block at the current position.
The drawable is positioned at the block's current cursor position, which starts at (0, 0) relative to the block's content area.
Returns an error if the drawable is nil.
func (*Block) DrawAt ¶
DrawAt adds a drawable element at a specific position within the block.
Coordinates are relative to the block's top-left corner (before margins).
Parameters:
- d: The drawable element to add
- x: Horizontal position from left edge of block
- y: Vertical position from top edge of block
Returns an error if the drawable is nil.
func (*Block) GetDrawables ¶
func (b *Block) GetDrawables() []DrawablePosition
GetDrawables returns all drawable elements with their positions.
This is used internally to render the block contents to a page.
func (*Block) GetLayoutContext ¶
func (b *Block) GetLayoutContext() *LayoutContext
GetLayoutContext creates a LayoutContext for this block.
This allows Drawable elements to query the available space and position themselves correctly within the block.
func (*Block) MoveCursor ¶
MoveCursor moves the current drawing position by the specified delta.
func (*Block) SetCursor ¶
SetCursor sets the current drawing position within the block.
This affects subsequent Draw() calls.
func (*Block) SetMargins ¶
SetMargins sets the block margins.
Margins define the padding inside the block, reducing the available drawing area.
type Bookmark ¶
type Bookmark struct {
// Title is the text displayed in the bookmark tree.
Title string
// PageIndex is the target page (0-based index).
// 0 = first page, 1 = second page, etc.
PageIndex int
// Level is the nesting level in the bookmark hierarchy.
// 0 = top-level, 1 = child of top-level, 2 = grandchild, etc.
Level int
}
Bookmark represents a PDF bookmark (also known as outline item).
Bookmarks provide a navigational tree structure in PDF documents. They allow users to jump to specific pages and create a table of contents.
Example:
bookmark := Bookmark{
Title: "Chapter 1",
PageIndex: 0, // First page (0-based)
Level: 0, // Top-level bookmark
}
type Border ¶
type Border struct {
// Width is the border line width in points.
Width float64
// Color is the border color (RGB, 0.0 to 1.0 range).
Color Color
}
Border defines the border style for a division.
Border controls the appearance of a division's outline, including width and color. Individual borders can be set per side.
Example:
border := Border{Width: 1.0, Color: Black}
div.SetBorder(border)
type Chapter ¶
type Chapter struct {
// contains filtered or unexported fields
}
Chapter represents a document chapter with title and content.
Chapters provide hierarchical document structure with automatic numbering. They can contain sub-chapters (sections, subsections, etc.) up to any depth.
Example:
ch := NewChapter("Introduction")
ch.Add(NewParagraph("This is the introduction..."))
sec := ch.NewSubChapter("Background")
sec.Add(NewParagraph("Background information..."))
func NewChapter ¶
NewChapter creates a new top-level chapter with the given title.
The chapter uses default styling and can have content and sub-chapters added.
Example:
ch := NewChapter("Chapter 1: Introduction")
ch.Add(NewParagraph("Welcome to this document..."))
func (*Chapter) Add ¶
Add adds a content element (paragraph, table, etc.) to the chapter.
Example:
ch.Add(NewParagraph("This is the introduction..."))
ch.Add(NewTable())
func (*Chapter) Draw ¶
func (c *Chapter) Draw(ctx *LayoutContext, page *Page) error
Draw renders the chapter on the page.
This renders: 1. Chapter heading (with number if enabled) 2. All content elements 3. All sub-chapters (recursively).
func (*Chapter) FullTitle ¶
FullTitle returns the title with number prefix if numbering is enabled.
For example: "1.2 Background" or just "Background" if ShowNumber is false.
func (*Chapter) GetAllChapters ¶
GetAllChapters returns a flat list of this chapter and all sub-chapters.
The list is in document order (depth-first traversal).
This is useful for building table of contents.
func (*Chapter) Height ¶
func (c *Chapter) Height(ctx *LayoutContext) float64
Height calculates the total height needed to render this chapter.
This includes the heading, all content, and all sub-chapters.
func (*Chapter) Level ¶
Level returns the nesting level of the chapter.
Top-level chapters return 0, sub-chapters return 1, etc.
func (*Chapter) NewSubChapter ¶
NewSubChapter creates a new sub-chapter (section) under this chapter.
The sub-chapter inherits styling from the parent but with smaller font size. Numbering is automatically assigned based on the position.
Example:
ch := NewChapter("Introduction")
sec1 := ch.NewSubChapter("Background") // 1.1 Background
sec2 := ch.NewSubChapter("Motivation") // 1.2 Motivation
subsec := sec1.NewSubChapter("History") // 1.1.1 History
func (*Chapter) Number ¶
Number returns the chapter number components.
For example, section 1.2.3 returns []int{1, 2, 3}.
func (*Chapter) NumberString ¶
NumberString returns the formatted chapter number.
For example: "1", "1.2", "1.2.3".
func (*Chapter) PageIndex ¶
PageIndex returns the page index where the chapter starts.
Returns -1 if not yet rendered.
func (*Chapter) SetStyle ¶
func (c *Chapter) SetStyle(style ChapterStyle)
SetStyle sets the chapter heading style.
func (*Chapter) Style ¶
func (c *Chapter) Style() ChapterStyle
Style returns the current chapter heading style.
func (*Chapter) SubChapters ¶
SubChapters returns all sub-chapters.
type ChapterStyle ¶
type ChapterStyle struct {
// Font for the chapter title
Font FontName
// FontSize for the chapter title
FontSize float64
// Color for the chapter title
Color Color
// SpaceBefore is the vertical space before the chapter heading
SpaceBefore float64
// SpaceAfter is the vertical space after the chapter heading
SpaceAfter float64
// ShowNumber indicates whether to show chapter numbers
ShowNumber bool
// NumberSeparator is the separator between number components (default: ".")
NumberSeparator string
}
ChapterStyle defines the visual style for chapter headings.
func DefaultChapterStyle ¶
func DefaultChapterStyle() ChapterStyle
DefaultChapterStyle returns the default chapter heading style.
Default style:
- Font: HelveticaBold
- FontSize: 18pt (scaled down for sub-chapters)
- Color: Black
- SpaceBefore: 20pt
- SpaceAfter: 10pt
- ShowNumber: true
- NumberSeparator: "."
type CircleOptions ¶
type CircleOptions struct {
// StrokeColor is the border color (nil = no stroke).
// If StrokeColorCMYK is set, this field is ignored.
StrokeColor *Color
// StrokeColorCMYK is the border color in CMYK (nil = no stroke).
// If set, this takes precedence over StrokeColor (RGB).
StrokeColorCMYK *ColorCMYK
// StrokeWidth is the border width in points (default: 1.0).
StrokeWidth float64
// FillColor is the fill color (nil = no fill).
// Mutually exclusive with FillGradient and FillColorCMYK.
// If FillColorCMYK is set, this field is ignored.
FillColor *Color
// FillColorCMYK is the fill color in CMYK (nil = no fill).
// If set, this takes precedence over FillColor (RGB).
// Mutually exclusive with FillGradient.
FillColorCMYK *ColorCMYK
// FillGradient is the gradient fill (nil = no gradient fill).
// Mutually exclusive with FillColor and FillColorCMYK.
FillGradient *Gradient
// Opacity is the circle opacity (0.0 = transparent, 1.0 = opaque).
// Optional. If set, applies transparency via ExtGState.
// Affects both fill and stroke.
// Range: [0.0, 1.0]
Opacity *float64
}
CircleOptions configures circle drawing.
type Color ¶
type Color struct {
R float64 // Red component (0.0 to 1.0)
G float64 // Green component (0.0 to 1.0)
B float64 // Blue component (0.0 to 1.0)
}
Color represents an RGB color with values in the range [0.0, 1.0].
PDF uses RGB color space where: - 0.0 = no intensity (black for all channels) - 1.0 = full intensity (white for all channels)
Example:
black := Color{0, 0, 0} // RGB(0, 0, 0)
white := Color{1, 1, 1} // RGB(255, 255, 255)
red := Color{1, 0, 0} // RGB(255, 0, 0)
gray := Color{0.5, 0.5, 0.5} // RGB(128, 128, 128)
func GrayN ¶ added in v0.2.0
GrayN creates a Color from a grayscale value (0-255).
This is a convenience function for creating gray colors from numeric values. All RGB components are set to the same value.
Note: Use the Gray variable for the predefined 50% gray color.
Parameters:
- value: Grayscale value (0 = black, 255 = white)
Example:
black := creator.GrayN(0) gray := creator.GrayN(128) white := creator.GrayN(255)
func Hex ¶ added in v0.2.0
Hex creates a Color from a hex color string.
Supported formats:
- "#RGB" (short form, e.g., "#F00" = red)
- "#RRGGBB" (long form, e.g., "#FF0000" = red)
- "RGB" (without #)
- "RRGGBB" (without #)
Parameters:
- hex: Hex color string
Example:
red, _ := creator.Hex("#FF0000")
green, _ := creator.Hex("00FF00")
blue, _ := creator.Hex("#00F")
func RGB ¶ added in v0.2.0
RGB creates a Color from 8-bit RGB values (0-255).
This is a convenience function for creating colors from common 8-bit color values instead of normalized floats.
Parameters:
- r: Red component (0 to 255)
- g: Green component (0 to 255)
- b: Blue component (0 to 255)
Example:
red := creator.RGB(255, 0, 0) green := creator.RGB(0, 255, 0) gray := creator.RGB(128, 128, 128)
func (Color) ToCMYK ¶
ToCMYK converts an RGB color to CMYK.
Conversion formula:
K = 1 - max(R, G, B) C = (1 - R - K) / (1 - K) M = (1 - G - K) / (1 - K) Y = (1 - B - K) / (1 - K)
Special case: Pure black (R=0, G=0, B=0) is represented as K=1, C=M=Y=0.
Note: This is a simple conversion. For precise color matching in professional printing, use ICC color profiles.
Example:
rgb := Color{1, 0, 0} // Red in RGB
cmyk := rgb.ToCMYK() // Converts to CMYK{0, 1, 1, 0}
type ColorCMYK ¶
type ColorCMYK struct {
C float64 // Cyan component (0.0 to 1.0)
M float64 // Magenta component (0.0 to 1.0)
Y float64 // Yellow component (0.0 to 1.0)
K float64 // blacK component (0.0 to 1.0)
}
ColorCMYK represents a CMYK color with values in the range [0.0, 1.0].
CMYK (Cyan, Magenta, Yellow, blacK) is a subtractive color model used in professional printing. Unlike RGB (additive), CMYK works by subtracting colors from white.
PDF supports CMYK color space natively via DeviceCMYK.
Example:
black := ColorCMYK{0, 0, 0, 1} // 100% black
white := ColorCMYK{0, 0, 0, 0} // No ink (paper white)
cyan := ColorCMYK{1, 0, 0, 0} // 100% cyan
magenta := ColorCMYK{0, 1, 0, 0} // 100% magenta
yellow := ColorCMYK{0, 0, 1, 0} // 100% yellow
red := ColorCMYK{0, 1, 1, 0} // Magenta + Yellow = Red
Reference: PDF 1.7 Specification, Section 8.6.4.4 (DeviceCMYK Color Space).
func NewColorCMYK ¶
NewColorCMYK creates a new CMYK color.
Parameters:
- c: Cyan component (0.0 to 1.0)
- m: Magenta component (0.0 to 1.0)
- y: Yellow component (0.0 to 1.0)
- k: blacK component (0.0 to 1.0)
Example:
cyan := creator.NewColorCMYK(1.0, 0.0, 0.0, 0.0) red := creator.NewColorCMYK(0.0, 1.0, 1.0, 0.0)
func (ColorCMYK) ToRGB ¶
ToRGB converts a CMYK color to RGB.
Conversion formula:
R = (1 - C) * (1 - K) G = (1 - M) * (1 - K) B = (1 - Y) * (1 - K)
Note: This is a simple conversion. For precise color matching in professional printing, use ICC color profiles.
Example:
cmyk := ColorCMYK{0, 1, 1, 0} // Red in CMYK
rgb := cmyk.ToRGB() // Converts to RGB{1, 0, 0}
type ColorRGBA ¶ added in v0.2.0
type ColorRGBA struct {
R float64 // Red component (0.0 to 1.0)
G float64 // Green component (0.0 to 1.0)
B float64 // Blue component (0.0 to 1.0)
A float64 // Alpha component (0.0 = transparent, 1.0 = opaque)
}
ColorRGBA represents an RGBA color with alpha channel (transparency).
All values are in the range [0.0, 1.0]: - R, G, B: Color components (0.0 = no intensity, 1.0 = full intensity) - A: Alpha channel (0.0 = fully transparent, 1.0 = fully opaque)
PDF uses ExtGState (Extended Graphics State) with /ca parameter to implement transparency. The alpha value controls both fill and stroke opacity.
Example:
// Semi-transparent red
transparentRed := ColorRGBA{1, 0, 0, 0.5}
// Fully transparent (invisible)
invisible := ColorRGBA{0, 0, 0, 0}
// Fully opaque (same as Color)
opaque := ColorRGBA{1, 0, 0, 1}
Reference: PDF 1.7 Specification, Section 8.4.5 (Extended Graphics State).
func NewColorRGBA ¶ added in v0.2.0
NewColorRGBA creates a new RGBA color with alpha channel.
Parameters:
- r: Red component (0.0 to 1.0)
- g: Green component (0.0 to 1.0)
- b: Blue component (0.0 to 1.0)
- a: Alpha component (0.0 = transparent, 1.0 = opaque)
Example:
// 50% transparent red red := creator.NewColorRGBA(1.0, 0.0, 0.0, 0.5) // 30% transparent blue blue := creator.NewColorRGBA(0.0, 0.0, 1.0, 0.3)
func RGBA ¶ added in v0.2.0
RGBA creates a ColorRGBA from 8-bit RGB values and normalized alpha.
Parameters:
- r: Red component (0 to 255)
- g: Green component (0 to 255)
- b: Blue component (0 to 255)
- a: Alpha component (0.0 = transparent, 1.0 = opaque)
Example:
transparentRed := creator.RGBA(255, 0, 0, 0.5) semiTransparentBlue := creator.RGBA(0, 0, 255, 0.3)
func (ColorRGBA) ToColor ¶ added in v0.2.0
ToColor converts RGBA to RGB (discards alpha channel).
Returns the RGB color without transparency.
type ColorSpace ¶
type ColorSpace string
ColorSpace represents the image color space.
const ( // ColorSpaceRGB is RGB color space (3 components). ColorSpaceRGB ColorSpace = "DeviceRGB" // ColorSpaceCMYK is CMYK color space (4 components). ColorSpaceCMYK ColorSpace = "DeviceCMYK" // ColorSpaceGray is grayscale (1 component). ColorSpaceGray ColorSpace = "DeviceGray" )
type ColorStop ¶
type ColorStop struct {
// Position is the location of this color stop in the gradient (0.0 to 1.0).
// 0.0 = start, 1.0 = end.
Position float64
// Color is the RGB color at this position.
Color Color
}
ColorStop represents a color transition point in a gradient.
A gradient is defined by multiple color stops along a [0, 1] domain. Position 0 is the start, position 1 is the end.
Example:
stops := []ColorStop{
{Position: 0.0, Color: Red}, // Start: red
{Position: 0.5, Color: Yellow}, // Middle: yellow
{Position: 1.0, Color: Green}, // End: green
}
type Creator ¶
type Creator struct {
// contains filtered or unexported fields
}
Creator is a high-level API for creating PDF documents.
It provides a fluent interface for document creation with sensible defaults and simplified methods. Creator wraps the underlying domain model (Document) and provides a more intuitive API for common use cases.
Thread Safety ¶
Creator is NOT safe for concurrent use. Each goroutine should create its own Creator instance. However, multiple Creator instances can safely be used concurrently without synchronization.
Example ¶
c := creator.New()
c.SetPageSize(creator.A4)
c.SetMargins(72, 72, 72, 72) // 1 inch on all sides
page := c.NewPage()
// Add content...
c.WriteToFile("output.pdf")
func New ¶
func New() *Creator
New creates a new Creator with default settings.
Default settings: - Page size: A4 (595 × 842 points) - Margins: 72 points (1 inch) on all sides - PDF version: 1.7
Example:
c := creator.New()
c.SetTitle("My Document")
func (*Creator) AddBookmark ¶
AddBookmark adds a bookmark to the document.
Bookmarks create a navigational tree structure (outline) in the PDF. Use Level to create nested bookmarks (chapters → sections → subsections).
Parameters:
- title: Text to display in the bookmark tree
- pageIndex: Target page (0-based: 0 = first page, 1 = second, etc.)
- level: Nesting level (0 = top-level, 1 = child, 2 = grandchild, etc.)
Returns an error if the parameters are invalid.
Example:
c := creator.New()
page1, _ := c.NewPage()
page2, _ := c.NewPage()
page3, _ := c.NewPage()
// Add top-level bookmarks
c.AddBookmark("Chapter 1", 0, 0) // Points to page 1
c.AddBookmark("Chapter 2", 2, 0) // Points to page 3
// Add nested bookmarks (sections under Chapter 1)
c.AddBookmark("Section 1.1", 0, 1) // Child of Chapter 1
c.AddBookmark("Section 1.2", 1, 1) // Child of Chapter 1
c.WriteToFile("document.pdf")
func (*Creator) AddChapter ¶
AddChapter adds a chapter to the document.
Chapters provide document structure with automatic numbering and optional Table of Contents integration.
The chapter will be rendered on a new page, and all sub-chapters will be included automatically.
Example:
c := creator.New()
c.EnableTOC()
ch1 := creator.NewChapter("Introduction")
ch1.Add(creator.NewParagraph("This is the introduction..."))
c.AddChapter(ch1)
ch2 := creator.NewChapter("Methods")
sec := ch2.NewSubChapter("Background")
c.AddChapter(ch2)
func (*Creator) Bookmarks ¶
Bookmarks returns a copy of all bookmarks in the document.
The returned slice is a copy, so modifications won't affect the document. Bookmarks are returned in the order they were added.
Example:
c.AddBookmark("Chapter 1", 0, 0)
c.AddBookmark("Section 1.1", 0, 1)
bookmarks := c.Bookmarks()
fmt.Printf("Document has %d bookmarks\n", len(bookmarks))
func (*Creator) Bytes ¶ added in v0.2.0
Bytes returns the PDF document as a byte slice.
This is a convenience method that writes to an in-memory buffer. For large documents, consider using WriteTo with a streaming writer.
Example:
pdfBytes, err := c.Bytes()
if err != nil {
log.Fatal(err)
}
// Use pdfBytes...
func (*Creator) DisableTOC ¶
func (c *Creator) DisableTOC()
DisableTOC disables automatic Table of Contents generation.
func (*Creator) Document ¶
Document returns the underlying domain document.
This is provided for advanced use cases where you need direct access to the domain model. Most users should use the Creator API instead.
Example:
doc := c.Document() // Direct domain operations...
func (*Creator) EnableTOC ¶
func (c *Creator) EnableTOC()
EnableTOC enables automatic Table of Contents generation.
When enabled, the TOC will be inserted at the beginning of the document and will include all chapters added via AddChapter.
The TOC includes clickable links to each chapter and section.
Example:
c := creator.New()
c.EnableTOC()
ch1 := creator.NewChapter("Introduction")
c.AddChapter(ch1)
c.WriteToFile("document.pdf") // TOC is automatically generated
func (*Creator) FooterHeight ¶
FooterHeight returns the current footer height in points.
func (*Creator) HeaderHeight ¶
HeaderHeight returns the current header height in points.
func (*Creator) NewPage ¶
NewPage adds a new page with the default page size.
The page uses the default page size set via SetPageSize. If no default is set, A4 is used.
Returns the newly created page for method chaining.
Example:
page := c.NewPage() // Add content to page...
func (*Creator) NewPageWithDimensions ¶ added in v0.4.0
NewPageWithDimensions adds a new page with explicit width and height in PDF points.
This is useful when no standard size fits your needs, or when importing content from real-world measurements (use InchesToPoints/MMToPoints to convert).
Parameters:
- widthPt: Page width in PDF points (must be > 0)
- heightPt: Page height in PDF points (must be > 0)
Returns the newly created page or an error if dimensions are invalid.
Example:
// A custom 6 × 9 inch page
page, err := c.NewPageWithDimensions(
creator.InchesToPoints(6),
creator.InchesToPoints(9),
)
For standard sizes in landscape orientation, prefer Creator.NewPageWithSize with the Landscape option instead of swapping dimensions manually.
func (*Creator) NewPageWithSize ¶
func (c *Creator) NewPageWithSize(size PageSize, orientation ...Orientation) (*Page, error)
NewPageWithSize adds a new page with a specific standard size and optional orientation.
By default pages are created in portrait orientation (taller than wide). Pass Landscape to create a true landscape page with swapped width and height. This uses the industry-standard swapped-MediaBox approach — no /Rotate entry is written, so content coordinates remain natural.
Example:
page, err := c.NewPageWithSize(creator.Letter) // portrait page, err := c.NewPageWithSize(creator.A4, creator.Landscape) // 842 × 595 pt page, err := c.NewPageWithSize(creator.Letter, creator.Landscape) // 792 × 612 pt
func (*Creator) SetEncryption ¶
func (c *Creator) SetEncryption(opts EncryptionOptions) error
SetEncryption enables encryption for the PDF document.
This must be called BEFORE writing the PDF to file.
Example:
c := creator.New()
c.SetEncryption(creator.EncryptionOptions{
UserPassword: "userpass",
OwnerPassword: "ownerpass",
Permissions: creator.PermissionPrint | creator.PermissionCopy,
Algorithm: creator.EncryptionAES128, // Recommended
})
c.WriteToFile("protected.pdf")
Note: Encryption is applied during WriteToFile.
Example ¶
c := New()
// Enable encryption with user and owner passwords.
_ = c.SetEncryption(EncryptionOptions{
UserPassword: "userpass",
OwnerPassword: "ownerpass",
Permissions: PermissionPrint | PermissionCopy,
KeyLength: 128,
})
// Document will be encrypted when written to file.
// (WriteToFile not shown here as it requires more setup)
Example (Aes128) ¶
c := New()
// Enable AES-128 encryption (recommended).
_ = c.SetEncryption(EncryptionOptions{
UserPassword: "userpass",
OwnerPassword: "ownerpass",
Permissions: PermissionPrint | PermissionCopy,
Algorithm: EncryptionAES128,
})
// Document will be encrypted when written to file.
Example (Aes256) ¶
c := New()
// Enable AES-256 encryption (most secure).
_ = c.SetEncryption(EncryptionOptions{
UserPassword: "userpass",
OwnerPassword: "ownerpass",
Permissions: PermissionAll,
Algorithm: EncryptionAES256,
})
// Document will be encrypted when written to file.
func (*Creator) SetFooterFunc ¶
func (c *Creator) SetFooterFunc(f FooterFunc)
SetFooterFunc sets the function to render footers on each page.
The function is called once for each page during PDF generation. It receives page information and a Block to draw footer content into.
Example:
c.SetFooterFunc(func(args FooterFunctionArgs) {
text := fmt.Sprintf("Page %d of %d", args.PageNum, args.TotalPages)
p := NewParagraph(text)
p.SetAlignment(AlignCenter)
args.Block.Draw(p)
})
func (*Creator) SetFooterHeight ¶
SetFooterHeight sets the height reserved for footers in points.
Default: 30 points.
Example:
c.SetFooterHeight(25) // 25 points for footer
func (*Creator) SetHeaderFunc ¶
func (c *Creator) SetHeaderFunc(f HeaderFunc)
SetHeaderFunc sets the function to render headers on each page.
The function is called once for each page during PDF generation. It receives page information and a Block to draw header content into.
Example:
c.SetHeaderFunc(func(args HeaderFunctionArgs) {
p := NewParagraph("Document Title")
p.SetFont(HelveticaBold, 10)
args.Block.Draw(p)
})
func (*Creator) SetHeaderHeight ¶
SetHeaderHeight sets the height reserved for headers in points.
Default: 50 points.
Example:
c.SetHeaderHeight(40) // 40 points for header
func (*Creator) SetKeywords ¶
SetKeywords sets document keywords for search/indexing.
Example:
c.SetKeywords("report", "2025", "finance", "annual")
func (*Creator) SetMargins ¶
SetMargins sets the default margins for new pages.
Margins are specified in points (1 point = 1/72 inch).
Example:
c.SetMargins(72, 72, 72, 72) // 1 inch on all sides c.SetMargins(36, 36, 36, 36) // 0.5 inch on all sides
func (*Creator) SetMetadata ¶
SetMetadata sets all document metadata at once.
Example:
c.SetMetadata("My Document", "John Doe", "Annual Report")
func (*Creator) SetPageSize ¶
SetPageSize sets the default page size for new pages.
This affects all pages added after calling this method. Existing pages are not affected.
Example:
c.SetPageSize(creator.Letter) // 8.5 × 11 inches c.NewPage() // Uses Letter size
func (*Creator) SetSkipFooterOnFirstPage ¶
SetSkipFooterOnFirstPage sets whether to skip the footer on the first page.
This is useful for documents with a title page that should not have a footer.
Example:
c.SetSkipFooterOnFirstPage(true) // No footer on page 1
func (*Creator) SetSkipHeaderOnFirstPage ¶
SetSkipHeaderOnFirstPage sets whether to skip the header on the first page.
This is useful for documents with a title page that should not have a header.
Example:
c.SetSkipHeaderOnFirstPage(true) // No header on page 1
func (*Creator) SetSubject ¶
SetSubject sets the document subject.
Example:
c.SetSubject("Financial Report")
func (*Creator) SetTitle ¶
SetTitle sets the document title.
Example:
c.SetTitle("Annual Report 2025")
func (*Creator) SkipFooterOnFirstPage ¶
SkipFooterOnFirstPage returns whether footers are skipped on the first page.
func (*Creator) SkipHeaderOnFirstPage ¶
SkipHeaderOnFirstPage returns whether headers are skipped on the first page.
func (*Creator) TOC ¶
TOC returns the Table of Contents instance for customization.
This allows customizing TOC appearance before rendering.
Example:
c.EnableTOC()
toc := c.TOC()
toc.SetTitle("Contents")
style := toc.Style()
style.TitleSize = 28
toc.SetStyle(style)
func (*Creator) TOCEnabled ¶
TOCEnabled returns whether TOC generation is enabled.
func (*Creator) Validate ¶
Validate checks if the document is valid and ready to be written.
Returns an error if: - Document has no pages - Any page validation fails
It's recommended to call this before WriteToFile to catch errors early.
func (*Creator) WriteTo ¶ added in v0.2.0
WriteTo writes the PDF document to an io.Writer.
This implements io.WriterTo and is useful for:
- Writing to HTTP responses
- Writing to memory buffers
- Writing to network connections
- Any other io.Writer implementation
Example:
var buf bytes.Buffer
n, err := c.WriteTo(&buf)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Wrote %d bytes\n", n)
func (*Creator) WriteToContext ¶ added in v0.2.0
WriteToContext writes the PDF document to an io.Writer with context support.
This allows cancellation and timeout control during PDF generation.
Example:
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() var buf bytes.Buffer n, err := c.WriteToContext(ctx, &buf)
func (*Creator) WriteToFile ¶
WriteToFile writes the PDF document to a file.
This will: 1. Validate the document 2. Generate the PDF structure 3. Write to the specified file
Returns an error if validation or writing fails.
Example:
err := c.WriteToFile("output.pdf")
if err != nil {
log.Fatal(err)
}
func (*Creator) WriteToFileContext ¶
WriteToFileContext writes the PDF document to a file with context support.
This allows cancellation and timeout control. The context is checked at multiple points during PDF generation:
- Before rendering TOC and chapters
- Before validation
- Before writing to file
Example:
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() err := c.WriteToFileContext(ctx, "output.pdf")
type CustomFont ¶
type CustomFont struct {
// contains filtered or unexported fields
}
CustomFont represents an embedded TrueType/OpenType font.
Custom fonts allow you to use any TTF/OTF font file in your PDFs, including fonts with Unicode support (Cyrillic, CJK, etc.).
The font is embedded as a subset containing only the glyphs used in the document, reducing file size.
Example:
font, err := LoadFont("fonts/OpenSans-Regular.ttf")
if err != nil {
log.Fatal(err)
}
p := NewParagraph("Текст на русском")
p.SetCustomFont(font, 12)
func LoadFont ¶
func LoadFont(path string) (*CustomFont, error)
LoadFont loads a TrueType/OpenType font file.
Supported formats:
- TrueType (.ttf)
- OpenType with TrueType outlines (.otf)
Not yet supported:
- OpenType with CFF outlines (.otf with PostScript outlines)
- TrueType Collections (.ttc)
Returns an error if the file cannot be read or is not a valid font.
func (*CustomFont) Build ¶
func (f *CustomFont) Build() error
Build builds the font subset.
This must be called before writing the PDF. It's automatically called by the Creator when finalizing the document.
func (*CustomFont) GetSubset ¶
func (f *CustomFont) GetSubset() *fonts.FontSubset
GetSubset returns the font subset (for internal use).
func (*CustomFont) GetTTF ¶ added in v0.1.1
func (f *CustomFont) GetTTF() *fonts.TTFFont
GetTTF returns the parsed TrueType font (for internal use).
func (*CustomFont) ID ¶ added in v0.1.1
func (f *CustomFont) ID() string
ID returns a unique identifier for this font instance.
The ID is used to track fonts across pages and avoid duplicates.
func (*CustomFont) MeasureString ¶
func (f *CustomFont) MeasureString(text string, size float64) float64
MeasureString returns the width of a string in points at the given size.
This is used for layout calculations (word wrapping, alignment, etc.).
func (*CustomFont) PostScriptName ¶
func (f *CustomFont) PostScriptName() string
PostScriptName returns the PostScript name of the font.
This is used as the font name in the PDF.
func (*CustomFont) UnitsPerEm ¶
func (f *CustomFont) UnitsPerEm() uint16
UnitsPerEm returns the units per em for this font.
func (*CustomFont) UseChar ¶
func (f *CustomFont) UseChar(ch rune)
UseChar marks a character as used (for subsetting).
This is called automatically by text rendering functions. You don't need to call this manually.
func (*CustomFont) UseString ¶
func (f *CustomFont) UseString(text string)
UseString marks all characters in a string as used.
This is called automatically by text rendering functions. You don't need to call this manually.
type Division ¶
type Division struct {
// contains filtered or unexported fields
}
Division is a container for grouping multiple Drawables.
Division provides a box model with support for: - Background color - Borders (all sides or individual) - Padding (inner spacing) - Margins (outer spacing) - Width and minimum height control
Example:
div := NewDivision()
div.SetBackground(White)
div.SetBorder(Border{Width: 1, Color: Gray})
div.SetPaddingAll(10)
div.Add(NewParagraph("Content"))
page.Draw(div)
func NewDivision ¶
func NewDivision() *Division
NewDivision creates a new empty division.
The division starts with no content, transparent background, no borders, no padding, and no margins.
Example:
div := NewDivision()
div.Add(NewParagraph("Hello"))
func (*Division) Add ¶
Add adds a drawable element to the division.
Elements are drawn in the order they are added.
Example:
div.Add(NewParagraph("First"))
div.Add(NewParagraph("Second"))
func (*Division) Background ¶
Background returns the background color, or nil if transparent.
func (*Division) Clear ¶
Clear removes all drawable elements from the division.
This does not affect styling (background, borders, padding, margins).
Example:
div.Clear() // Remove all content
func (*Division) ContentWidth ¶
func (d *Division) ContentWidth(ctx *LayoutContext) float64
ContentWidth calculates the available width for content.
This accounts for padding and border widths.
func (*Division) Draw ¶
func (d *Division) Draw(ctx *LayoutContext, page *Page) error
Draw renders the division and its contents on the page.
Drawing sequence: 1. Apply margins (adjust cursor) 2. Draw background 3. Draw borders 4. Draw content (with padding) 5. Update cursor position.
func (*Division) Drawables ¶
Drawables returns all drawable elements in the division.
The returned slice is a direct reference, not a copy.
func (*Division) Height ¶
func (d *Division) Height(ctx *LayoutContext) float64
Height calculates the total height of the division.
This includes content height, padding, and borders.
func (*Division) SetBackground ¶
SetBackground sets the background color for the division.
The background fills the entire division area (including padding, but excluding margins).
Example:
div.SetBackground(White)
func (*Division) SetBorder ¶
SetBorder sets the border for all sides of the division.
Individual borders (top, right, bottom, left) can override this if set separately.
Example:
div.SetBorder(Border{Width: 2, Color: Black})
func (*Division) SetBorderBottom ¶
SetBorderBottom sets the bottom border, overriding the default border.
Example:
div.SetBorderBottom(Border{Width: 3, Color: Red})
func (*Division) SetBorderLeft ¶
SetBorderLeft sets the left border, overriding the default border.
Example:
div.SetBorderLeft(Border{Width: 4, Color: Blue})
func (*Division) SetBorderRight ¶
SetBorderRight sets the right border, overriding the default border.
Example:
div.SetBorderRight(Border{Width: 1, Color: Gray})
func (*Division) SetBorderTop ¶
SetBorderTop sets the top border, overriding the default border.
Example:
div.SetBorderTop(Border{Width: 3, Color: Red})
func (*Division) SetMargins ¶
SetMargins sets margins for the division.
Margins are the outer spacing around the division (outside the border).
Example:
div.SetMargins(Margins{Top: 10, Right: 5, Bottom: 10, Left: 5})
func (*Division) SetMinHeight ¶
SetMinHeight sets the minimum height for the division.
The division will be at least this tall, even if content is shorter.
Example:
div.SetMinHeight(100) // At least 100 points tall
func (*Division) SetPadding ¶
SetPadding sets padding for all sides individually.
Padding is the inner spacing between the border and content.
Example:
div.SetPadding(10, 15, 10, 15) // top, right, bottom, left
func (*Division) SetPaddingAll ¶
SetPaddingAll sets the same padding for all sides.
This is a convenience method for uniform padding.
Example:
div.SetPaddingAll(15) // 15 points on all sides
type Drawable ¶
type Drawable interface {
// Draw renders the element on the page using the layout context.
// The context's cursor position is updated after drawing.
Draw(ctx *LayoutContext, page *Page) error
// Height returns the pre-calculated height of the element.
// This is used for page break detection and layout planning.
Height(ctx *LayoutContext) float64
}
Drawable is an interface for elements that can be drawn on a page.
Elements implementing this interface can be used with Page.Draw() for automatic layout and positioning.
type DrawablePosition ¶
DrawablePosition stores a drawable with its position within the block.
type EllipseOptions ¶
type EllipseOptions struct {
// StrokeColor is the border color (nil = no stroke).
// If StrokeColorCMYK is set, this field is ignored.
StrokeColor *Color
// StrokeColorCMYK is the border color in CMYK (nil = no stroke).
// If set, this takes precedence over StrokeColor (RGB).
StrokeColorCMYK *ColorCMYK
// StrokeWidth is the border width in points (default: 1.0).
StrokeWidth float64
// FillColor is the fill color (nil = no fill).
// Mutually exclusive with FillGradient and FillColorCMYK.
// If FillColorCMYK is set, this field is ignored.
FillColor *Color
// FillColorCMYK is the fill color in CMYK (nil = no fill).
// If set, this takes precedence over FillColor (RGB).
// Mutually exclusive with FillGradient.
FillColorCMYK *ColorCMYK
// FillGradient is the gradient fill (nil = no gradient fill).
// Mutually exclusive with FillColor and FillColorCMYK.
FillGradient *Gradient
// Opacity is the ellipse opacity (0.0 = transparent, 1.0 = opaque).
// Optional. If set, applies transparency via ExtGState.
// Affects both fill and stroke.
// Range: [0.0, 1.0]
Opacity *float64
}
EllipseOptions configures ellipse drawing.
type EncryptionAlgorithm ¶
type EncryptionAlgorithm int
EncryptionAlgorithm specifies the encryption algorithm to use.
const ( // EncryptionRC4_40 uses RC4 with 40-bit keys (PDF 1.1+, legacy). EncryptionRC4_40 EncryptionAlgorithm = iota // EncryptionRC4_128 uses RC4 with 128-bit keys (PDF 1.4+, legacy). EncryptionRC4_128 // EncryptionAES128 uses AES-128 encryption (PDF 1.5+, recommended). EncryptionAES128 // EncryptionAES256 uses AES-256 encryption (PDF 1.7+, most secure). EncryptionAES256 )
type EncryptionOptions ¶
type EncryptionOptions struct {
// UserPassword allows opening the document with restrictions.
// If empty, document can be opened without password (but with restrictions).
UserPassword string
// OwnerPassword allows opening the document with full access.
// If empty, defaults to UserPassword.
OwnerPassword string
// Permissions specifies what operations are allowed.
// Use Permission constants (PermissionPrint, PermissionCopy, etc.).
Permissions Permission
// Algorithm specifies the encryption algorithm.
// Valid values: EncryptionRC4_40, EncryptionRC4_128, EncryptionAES128, EncryptionAES256.
// Default: EncryptionAES128.
Algorithm EncryptionAlgorithm
// KeyLength specifies the encryption key length in bits (deprecated, use Algorithm instead).
// Valid values: 40 (PDF 1.1+), 128 (PDF 1.4+), 256 (PDF 1.7+).
// If Algorithm is set, KeyLength is ignored.
// Default: 128 (for backward compatibility).
KeyLength int
}
EncryptionOptions holds the encryption settings for PDF creation.
Use SetEncryption to enable password protection and permissions control.
Example:
c := creator.New()
c.SetEncryption(creator.EncryptionOptions{
UserPassword: "userpass",
OwnerPassword: "ownerpass",
Permissions: creator.PermissionPrint | creator.PermissionCopy,
Algorithm: creator.EncryptionAES128, // or EncryptionAES256
})
Example (Permissions) ¶
c := New()
// Allow only printing, no modifications.
_ = c.SetEncryption(EncryptionOptions{
UserPassword: "secret",
Permissions: PermissionPrint,
KeyLength: 128,
})
// Allow print and copy, but no modify.
_ = c.SetEncryption(EncryptionOptions{
UserPassword: "secret",
Permissions: PermissionPrint | PermissionCopy,
KeyLength: 128,
})
// Allow all operations.
_ = c.SetEncryption(EncryptionOptions{
UserPassword: "secret",
Permissions: PermissionAll,
KeyLength: 128,
})
type Fill ¶ added in v0.2.0
type Fill struct {
// Paint is the paint source (Color, ColorRGBA, ColorCMYK, or Gradient).
Paint Paint
// Opacity is the fill opacity (0.0 = transparent, 1.0 = opaque).
// This is multiplied with the paint's alpha if using ColorRGBA.
Opacity float64
// Rule is the fill rule (NonZero or EvenOdd).
// Determines which areas are "inside" the path for complex shapes.
Rule FillRule
}
Fill represents fill configuration for shapes.
Fill controls how shapes are filled with paint (color or gradient). It includes the paint source, opacity, and fill rule.
Example:
// Solid color fill
fill := &Fill{
Paint: Red,
Opacity: 1.0,
Rule: FillRuleNonZero,
}
// Gradient fill with transparency
grad := NewLinearGradient(0, 0, 100, 0)
grad.AddColorStop(0, Red)
grad.AddColorStop(1, Blue)
fill := &Fill{
Paint: grad,
Opacity: 0.8,
Rule: FillRuleNonZero,
}
func NewFill ¶ added in v0.2.0
NewFill creates a new Fill with the specified paint.
Default values:
- Opacity: 1.0 (fully opaque)
- Rule: FillRuleNonZero
Parameters:
- paint: Paint source (Color, ColorRGBA, ColorCMYK, or Gradient)
Example:
fill := NewFill(Red) fill := NewFill(NewLinearGradient(0, 0, 100, 0))
func (*Fill) Validate ¶ added in v0.2.0
Validate validates the fill configuration.
Checks:
- Paint is not nil
- Opacity is in range [0, 1]
- If paint is a Gradient, validate gradient
Returns an error if validation fails.
func (*Fill) WithOpacity ¶ added in v0.2.0
WithOpacity returns a new Fill with the specified opacity.
Parameters:
- opacity: Opacity value (0.0 = transparent, 1.0 = opaque)
Example:
fill := NewFill(Red).WithOpacity(0.5)
type FillRule ¶ added in v0.2.0
type FillRule int
FillRule defines how to determine which areas are "inside" a path.
PDF supports two fill rules:
- NonZero winding rule (default): Counts path direction crossings
- EvenOdd rule: Counts total path crossings
Reference: PDF 1.7 Specification, Section 8.5.3.3 (Filling).
const ( // FillRuleNonZero uses the non-zero winding rule. // // A point is inside if the winding number is non-zero. // Winding number counts +1 for left-to-right crossings, // -1 for right-to-left crossings. // // PDF operator: f (fill) or F (deprecated). FillRuleNonZero FillRule = iota // FillRuleEvenOdd uses the even-odd rule. // // A point is inside if a ray from the point crosses // the path an odd number of times. // // PDF operator: f* (eofill). FillRuleEvenOdd )
type FontName ¶
type FontName string
FontName represents one of the Standard 14 fonts built into all PDF readers.
These fonts do not require embedding and are guaranteed to be available in all PDF viewers.
Reference: PDF 1.7 Specification, Section 9.6.2.2 (Standard Type 1 Fonts).
const ( // TimesRoman is Times Roman (serif, regular weight, normal style). TimesRoman FontName = "Times-Roman" // TimesBold is Times Bold (serif, bold weight, normal style). TimesBold FontName = "Times-Bold" // TimesItalic is Times Italic (serif, regular weight, italic style). TimesItalic FontName = "Times-Italic" // TimesBoldItalic is Times Bold Italic (serif, bold weight, italic style). TimesBoldItalic FontName = "Times-BoldItalic" )
Standard 14 fonts - Serif family (Times).
const ( // Helvetica is Helvetica (sans-serif, regular weight, normal style). Helvetica FontName = "Helvetica" // HelveticaBold is Helvetica Bold (sans-serif, bold weight, normal style). HelveticaBold FontName = "Helvetica-Bold" // HelveticaOblique is Helvetica Oblique (sans-serif, regular weight, oblique style). HelveticaOblique FontName = "Helvetica-Oblique" // HelveticaBoldOblique is Helvetica Bold Oblique (sans-serif, bold weight, oblique style). HelveticaBoldOblique FontName = "Helvetica-BoldOblique" )
Standard 14 fonts - Sans-serif family (Helvetica).
const ( // Courier is Courier (monospace, regular weight, normal style). Courier FontName = "Courier" // CourierBold is Courier Bold (monospace, bold weight, normal style). CourierBold FontName = "Courier-Bold" // CourierOblique is Courier Oblique (monospace, regular weight, oblique style). CourierOblique FontName = "Courier-Oblique" // CourierBoldOblique is Courier Bold Oblique (monospace, bold weight, oblique style). CourierBoldOblique FontName = "Courier-BoldOblique" )
Standard 14 fonts - Monospace family (Courier).
type FooterFunc ¶
type FooterFunc func(args FooterFunctionArgs)
FooterFunc is the function signature for footer rendering.
The function receives a FooterFunctionArgs struct containing page information and a Block to draw the footer content into. The function should add any desired content to the Block using Draw() or DrawAt().
Example:
var footerFunc FooterFunc = func(args FooterFunctionArgs) {
text := fmt.Sprintf("Page %d of %d", args.PageNum, args.TotalPages)
p := NewParagraph(text)
p.SetAlignment(AlignCenter)
args.Block.Draw(p)
}
type FooterFunctionArgs ¶
type FooterFunctionArgs struct {
PageNum int
// This is known because footers are rendered after all content is generated.
TotalPages int
PageWidth float64
PageHeight float64
// The block is positioned at the bottom of the page within the margins.
Block *Block
}
FooterFunctionArgs contains information passed to the footer function.
This struct provides context about the current page and a Block to draw the footer content into. The footer function is called once for each page.
Example:
c.SetFooterFunc(func(args FooterFunctionArgs) {
p := NewParagraph(fmt.Sprintf("Page %d", args.PageNum))
p.SetAlignment(AlignCenter)
args.Block.Draw(p)
})
type Gradient ¶
type Gradient struct {
// Type is the gradient type (linear or radial).
Type GradientType
// ColorStops define the color transitions (minimum 2 required).
// Stops must be sorted by Position (0.0 to 1.0).
ColorStops []ColorStop
// Linear gradient fields (Type == GradientTypeLinear)
// Coordinates define the gradient axis from (X1, Y1) to (X2, Y2).
X1, Y1 float64 // Start point
X2, Y2 float64 // End point
// Radial gradient fields (Type == GradientTypeRadial)
// Coordinates define two circles: (X0, Y0, R0) and (X1, Y1, R1).
// Gradient transitions from inner circle to outer circle.
X0, Y0, R0 float64 // Starting circle (center + radius)
// X1, Y1 already defined above (reused for radial end center)
R1 float64 // Ending radius
// Extend flags control what happens outside the gradient domain.
// If true, colors extend beyond the gradient boundaries.
ExtendStart bool // Extend before the first color stop
ExtendEnd bool // Extend after the last color stop
}
Gradient represents a color gradient (linear or radial).
Gradients can be used to fill shapes with smooth color transitions. Two types are supported:
- Linear (axial): Color transitions along a straight line
- Radial: Color radiates from a center point
Gradients are defined by color stops at specific positions. The PDF renderer interpolates colors between stops.
func NewLinearGradient ¶
NewLinearGradient creates a new linear (axial) gradient.
The gradient transitions along a line from (x1, y1) to (x2, y2). Color stops must be added separately using AddColorStop().
Parameters:
- x1, y1: Start point of gradient axis
- x2, y2: End point of gradient axis
Example:
grad := creator.NewLinearGradient(0, 0, 100, 0) // Horizontal gradient grad.AddColorStop(0, creator.Red) grad.AddColorStop(1, creator.Blue)
PDF Reference: ShadingType 2 (Axial Shading).
func NewRadialGradient ¶
NewRadialGradient creates a new radial gradient.
The gradient radiates from an inner circle (x0, y0, r0) to an outer circle (x1, y1, r1). For a simple radial gradient from center outward, use same center for both circles and set r0 = 0.
Parameters:
- x0, y0, r0: Center and radius of starting circle
- x1, y1, r1: Center and radius of ending circle
Example:
// Simple radial gradient from center grad := creator.NewRadialGradient(150, 550, 0, 150, 550, 50) grad.AddColorStop(0, creator.White) // Center: white grad.AddColorStop(1, creator.Blue) // Edge: blue
PDF Reference: ShadingType 3 (Radial Shading).
func (*Gradient) AddColorStop ¶
AddColorStop adds a color stop to the gradient.
Color stops define the color at specific positions along the gradient. Position must be in range [0.0, 1.0] where 0 is start and 1 is end.
Stops can be added in any order; they will be sorted automatically.
Parameters:
- position: Position in gradient (0.0 = start, 1.0 = end)
- color: RGB color at this position
Example:
grad := creator.NewLinearGradient(0, 0, 100, 0) grad.AddColorStop(0.0, creator.Red) grad.AddColorStop(0.5, creator.Yellow) grad.AddColorStop(1.0, creator.Green)
type GradientType ¶
type GradientType int
GradientType represents the type of gradient.
const ( // GradientTypeLinear represents an axial (linear) gradient. // PDF ShadingType 2: gradient along a straight line from start to end point. GradientTypeLinear GradientType = 2 // GradientTypeRadial represents a radial gradient. // PDF ShadingType 3: gradient radiating from center point. GradientTypeRadial GradientType = 3 )
type GraphicsOpType ¶
type GraphicsOpType int
GraphicsOpType represents the type of graphics operation.
const ( // GraphicsOpLine draws a line from (X,Y) to (X2,Y2). GraphicsOpLine GraphicsOpType = iota // GraphicsOpRect draws a rectangle (stroke only, fill only, or both). GraphicsOpRect // GraphicsOpCircle draws a circle at center (X,Y) with Radius. GraphicsOpCircle // GraphicsOpImage draws an image at (X,Y) with Width,Height. GraphicsOpImage // GraphicsOpWatermark draws a text watermark at (X,Y) with rotation and opacity. GraphicsOpWatermark // GraphicsOpPolygon draws a closed polygon through N vertices. GraphicsOpPolygon // GraphicsOpPolyline draws an open path through N vertices. GraphicsOpPolyline // GraphicsOpEllipse draws an ellipse at center (X,Y) with radii RX and RY. GraphicsOpEllipse // GraphicsOpBezier draws a complex curve composed of Bézier segments. GraphicsOpBezier // GraphicsOpBeginClip begins a rectangular clipping region. // All subsequent drawing is clipped to the rectangle (X, Y, Width, Height). // Must be followed by GraphicsOpEndClip to restore the previous clipping state. GraphicsOpBeginClip GraphicsOpType = 20 // GraphicsOpEndClip ends a clipping region started by GraphicsOpBeginClip. GraphicsOpEndClip GraphicsOpType = 21 // GraphicsOpTextBlock renders text inline with graphics operations. // Used for clipped text where ordering matters. GraphicsOpTextBlock GraphicsOpType = 22 )
type GraphicsOperation ¶
type GraphicsOperation struct {
// Type is the graphics operation type.
Type GraphicsOpType
// X is the x-coordinate (start point for line, lower-left for rect/image, center for circle/ellipse).
X float64
// Y is the y-coordinate (start point for line, lower-left for rect/image, center for circle/ellipse).
Y float64
// X2 is the end x-coordinate (only for line).
X2 float64
// Y2 is the end y-coordinate (only for line).
Y2 float64
// Width is the rectangle/image width (only for rect/image).
Width float64
// Height is the rectangle/image height (only for rect/image).
Height float64
// Radius is the circle radius (only for circle).
Radius float64
// RX is the horizontal radius (only for ellipse).
RX float64
// RY is the vertical radius (only for ellipse).
RY float64
// Vertices is the array of points (only for polygon/polyline).
Vertices []Point
// BezierSegs is the array of Bézier segments (only for bezier).
BezierSegs []BezierSegment
// LineOpts are line options (only for line).
LineOpts *LineOptions
// RectOpts are rectangle options (only for rect).
RectOpts *RectOptions
// CircleOpts are circle options (only for circle).
CircleOpts *CircleOptions
// PolygonOpts are polygon options (only for polygon).
PolygonOpts *PolygonOptions
// PolylineOpts are polyline options (only for polyline).
PolylineOpts *PolylineOptions
// EllipseOpts are ellipse options (only for ellipse).
EllipseOpts *EllipseOptions
// BezierOpts are Bézier curve options (only for bezier).
BezierOpts *BezierOptions
// Image is the image to draw (only for image).
Image *Image
// WatermarkOp is the watermark operation (only for watermark).
WatermarkOp *TextWatermark
// TextBlock fields (only for GraphicsOpTextBlock).
Text string // Text content
TextFont *CustomFont // Custom font for text
TextSize float64 // Font size
TextColor *Color // Text color (RGB)
}
GraphicsOperation represents a graphics drawing operation.
The fields used depend on the Type: - GraphicsOpLine: X, Y, X2, Y2, LineOpts. - GraphicsOpRect: X, Y, Width, Height, RectOpts. - GraphicsOpCircle: X, Y, Radius, CircleOpts. - GraphicsOpImage: X, Y, Width, Height, Image. - GraphicsOpWatermark: X, Y, WatermarkOp. - GraphicsOpPolygon: Vertices, PolygonOpts. - GraphicsOpPolyline: Vertices, PolylineOpts. - GraphicsOpEllipse: X, Y, RX, RY, EllipseOpts. - GraphicsOpBezier: BezierSegs, BezierOpts.
type GraphicsState ¶ added in v0.2.0
type GraphicsState struct {
// Transform is the current transformation matrix (CTM).
Transform Transform
// Opacity is the overall transparency (0.0 = invisible, 1.0 = opaque).
// This affects both fill and stroke operations.
Opacity float64
// BlendMode controls how colors blend with the background.
BlendMode BlendMode
// ClipPath is the active clipping path (nil = no clipping).
// Drawing operations are clipped to this path.
ClipPath *Path
// ClipRule is the fill rule for the clipping path.
// Only used when ClipPath is not nil.
ClipRule FillRule
// Fill is the current fill configuration.
Fill *Fill
// Stroke is the current stroke configuration.
Stroke *Stroke
}
GraphicsState represents the complete graphics state at a point in time.
This includes transformation, opacity, blend mode, clipping path, fill, and stroke. The state is saved/restored using the PDF graphics state stack (q/Q operators).
func NewGraphicsState ¶ added in v0.2.0
func NewGraphicsState() GraphicsState
NewGraphicsState creates a new graphics state with default values.
func (GraphicsState) Clone ¶ added in v0.2.0
func (g GraphicsState) Clone() GraphicsState
Clone creates a copy of the graphics state.
This is used when pushing state onto the stack. Fill, Stroke, and ClipPath pointers are copied (shallow copy), so modifications to the pointed-to objects will affect both states. However, replacing the pointer (e.g., SetFill) only affects the current state.
type HeaderFunc ¶
type HeaderFunc func(args HeaderFunctionArgs)
HeaderFunc is the function signature for header rendering.
The function receives a HeaderFunctionArgs struct containing page information and a Block to draw the header content into. The function should add any desired content to the Block using Draw() or DrawAt().
Example:
var headerFunc HeaderFunc = func(args HeaderFunctionArgs) {
p := NewParagraph("Company Name")
p.SetFont(HelveticaBold, 10)
args.Block.Draw(p)
}
type HeaderFunctionArgs ¶
type HeaderFunctionArgs struct {
// PageNum is the current page number (1-based).
PageNum int
// TotalPages is the total number of pages in the document.
// This is known because headers are rendered after all content is generated.
TotalPages int
// PageWidth is the page width in points.
PageWidth float64
// PageHeight is the page height in points.
PageHeight float64
// Block is the block to draw header content into.
// The block is positioned at the top of the page within the margins.
Block *Block
}
HeaderFunctionArgs contains information passed to the header function.
This struct provides context about the current page and a Block to draw the header content into. The header function is called once for each page.
Example:
c.SetHeaderFunc(func(args HeaderFunctionArgs) {
p := NewParagraph(fmt.Sprintf("Page %d of %d", args.PageNum, args.TotalPages))
p.SetAlignment(AlignRight)
args.Block.Draw(p)
})
type HighlightAnnotation ¶
type HighlightAnnotation struct {
// contains filtered or unexported fields
}
HighlightAnnotation represents a highlight markup annotation.
Highlight annotations mark text with a colored overlay (typically yellow).
Example:
highlight := creator.NewHighlightAnnotation(100, 650, 300, 670)
highlight.SetColor(creator.Yellow)
highlight.SetAuthor("John Doe")
page.AddHighlightAnnotation(highlight)
func NewHighlightAnnotation ¶
func NewHighlightAnnotation(x1, y1, x2, y2 float64) *HighlightAnnotation
NewHighlightAnnotation creates a new highlight annotation.
The highlight covers the rectangular area from (x1, y1) to (x2, y2).
Parameters:
- x1: Left X coordinate (from left edge)
- y1: Bottom Y coordinate (from bottom edge)
- x2: Right X coordinate (from left edge)
- y2: Top Y coordinate (from bottom edge)
Example:
// Highlight text from (100, 650) to (300, 670) highlight := creator.NewHighlightAnnotation(100, 650, 300, 670) highlight.SetColor(creator.Yellow)
func (*HighlightAnnotation) SetAuthor ¶
func (a *HighlightAnnotation) SetAuthor(author string) *HighlightAnnotation
SetAuthor sets the author name.
Example:
highlight.SetAuthor("John Doe")
func (*HighlightAnnotation) SetColor ¶
func (a *HighlightAnnotation) SetColor(color Color) *HighlightAnnotation
SetColor sets the highlight color.
Common highlight colors:
- Yellow (default)
- Cyan (informational)
- Magenta (important)
- Green (approved)
Example:
highlight.SetColor(creator.Yellow)
func (*HighlightAnnotation) SetNote ¶
func (a *HighlightAnnotation) SetNote(note string) *HighlightAnnotation
SetNote sets an optional note text.
This text appears when the user hovers over or clicks the highlight.
Example:
highlight.SetNote("Important point")
type Image ¶
type Image struct {
// contains filtered or unexported fields
}
Image represents an image that can be embedded in a PDF document.
Currently supports:
- JPEG images (RGB and CMYK color spaces)
- PNG images (RGB, RGBA, grayscale, paletted)
The image data is stored as:
- JPEG: Raw JPEG bytes (DCTDecode)
- PNG: Raw pixel data compressed with FlateDecode
For RGBA PNG with transparency, the alpha channel is stored separately as an SMask (soft mask) for proper PDF rendering.
Example:
img, err := creator.LoadImage("photo.jpg") // or "photo.png"
if err != nil {
return err
}
page.DrawImage(img, 100, 500, 200, 150)
func LoadImage ¶
LoadImage loads an image from a file.
Supported formats: JPEG, PNG. For JPEG: RGB and CMYK color spaces. For PNG: RGB, RGBA (with alpha mask), grayscale, paletted.
Example:
img, err := creator.LoadImage("photo.jpg") // or "photo.png"
if err != nil {
return err
}
func LoadImageFromReader ¶
LoadImageFromReader loads an image from an io.Reader.
Supported formats: JPEG, PNG. This allows loading images from various sources (files, HTTP responses, etc.).
Example:
resp, _ := http.Get("https://example.com/image.png")
defer resp.Body.Close()
img, _ := creator.LoadImageFromReader(resp.Body)
func (*Image) AlphaMask ¶
AlphaMask returns the alpha mask data (nil if no transparency).
For RGBA PNG images with transparency, this contains the compressed alpha channel data used for the SMask (soft mask) in PDF.
func (*Image) BitsPerComponent ¶
BitsPerComponent returns the bits per component (typically 8).
func (*Image) ColorSpace ¶
func (img *Image) ColorSpace() ColorSpace
ColorSpace returns the image color space.
func (*Image) Components ¶
Components returns the number of color components.
Returns:
- 1 for grayscale
- 3 for RGB
- 4 for CMYK
func (*Image) Data ¶
Data returns the raw JPEG data.
This is used internally by the PDF writer to embed the image.
type LayoutContext ¶
type LayoutContext struct {
// Page dimensions (in points).
PageWidth float64
PageHeight float64
// Page margins (in points).
Margins Margins
// CursorX is the current horizontal position (from left edge).
CursorX float64
// CursorY is the current vertical position from top of content area.
// 0 = top of content area (below top margin)
// Increases downward.
CursorY float64
}
LayoutContext provides positioning information for layout operations.
It tracks the current cursor position and available space within the page margins. The cursor Y is measured from the top of the content area (intuitive "document flow" model).
Example:
ctx := page.GetLayoutContext() paragraph.Draw(ctx, page) // Draws at cursor position // Cursor automatically advances after drawing
func (*LayoutContext) AvailableHeight ¶
func (ctx *LayoutContext) AvailableHeight() float64
AvailableHeight returns the height remaining from cursor to bottom margin.
func (*LayoutContext) AvailableWidth ¶
func (ctx *LayoutContext) AvailableWidth() float64
AvailableWidth returns the width available for content (excluding margins).
func (*LayoutContext) CanFit ¶
func (ctx *LayoutContext) CanFit(height float64) bool
CanFit checks if an element of the given height fits in the remaining space.
func (*LayoutContext) ContentBottom ¶
func (ctx *LayoutContext) ContentBottom() float64
ContentBottom returns the Y coordinate (PDF coordinates) of the bottom content edge.
func (*LayoutContext) ContentLeft ¶
func (ctx *LayoutContext) ContentLeft() float64
ContentLeft returns the X coordinate of the left content edge.
func (*LayoutContext) ContentRight ¶
func (ctx *LayoutContext) ContentRight() float64
ContentRight returns the X coordinate of the right content edge.
func (*LayoutContext) ContentTop ¶
func (ctx *LayoutContext) ContentTop() float64
ContentTop returns the Y coordinate (PDF coordinates) of the top content edge.
func (*LayoutContext) CurrentPDFY ¶
func (ctx *LayoutContext) CurrentPDFY() float64
CurrentPDFY converts the cursor Y (from top) to PDF Y coordinate (from bottom).
func (*LayoutContext) MoveCursor ¶
func (ctx *LayoutContext) MoveCursor(dx, dy float64)
MoveCursor moves the cursor by the specified delta values.
Positive dx moves right, positive dy moves down.
func (*LayoutContext) NewLine ¶
func (ctx *LayoutContext) NewLine(lineHeight float64)
NewLine moves the cursor to the start of the next line.
The cursor X is reset to the left content edge. The cursor Y advances by the specified line height.
func (*LayoutContext) ResetX ¶
func (ctx *LayoutContext) ResetX()
ResetX moves the cursor X back to the left content edge.
func (*LayoutContext) SetCursor ¶
func (ctx *LayoutContext) SetCursor(x, y float64)
SetCursor sets the cursor to specific coordinates.
x is measured from the left edge of the page. y is measured from the top of the content area (below top margin).
type LineCap ¶ added in v0.2.0
type LineCap int
LineCap defines how line ends are rendered.
PDF supports three line cap styles. Reference: PDF 1.7 Specification, Section 8.4.3.3 (Line Cap Style).
const ( // LineCapButt ends exactly at the endpoint. // // The line terminates squarely at the endpoint. // PDF value: 0 LineCapButt LineCap = iota // LineCapRound adds a semicircular cap. // // A semicircle with diameter equal to line width is added. // PDF value: 1 LineCapRound // LineCapSquare adds a square cap extending past the endpoint. // // A square extending half the line width beyond the endpoint. // PDF value: 2 LineCapSquare )
type LineJoin ¶ added in v0.2.0
type LineJoin int
LineJoin defines how corners are rendered.
PDF supports three line join styles. Reference: PDF 1.7 Specification, Section 8.4.3.4 (Line Join Style).
const ( // LineJoinMiter extends lines to form a sharp corner. // // Lines are extended until they meet at an angle. // If miter length exceeds MiterLimit, a bevel is used. // PDF value: 0 LineJoinMiter LineJoin = iota // LineJoinRound rounds the corner. // // A circular arc with radius equal to half line width. // PDF value: 1 LineJoinRound // LineJoinBevel cuts off the corner. // // A straight line connects the outer endpoints. // PDF value: 2 LineJoinBevel )
type LineOptions ¶
type LineOptions struct {
// Color is the line color (RGB, 0.0 to 1.0 range).
// If ColorCMYK is set, this field is ignored.
Color Color
// ColorCMYK is the line color in CMYK color space (optional).
// If set, this takes precedence over Color (RGB).
ColorCMYK *ColorCMYK
// Width is the line width in points (default: 1.0).
Width float64
// Dashed enables dashed line rendering.
Dashed bool
// DashArray defines the dash pattern (e.g., [3, 1] for "3 on, 1 off").
// Only used when Dashed is true.
DashArray []float64
// DashPhase is the starting offset into the dash pattern.
// Only used when Dashed is true.
DashPhase float64
// Opacity is the line opacity (0.0 = transparent, 1.0 = opaque).
// Optional. If set, applies transparency via ExtGState.
// Range: [0.0, 1.0]
Opacity *float64
}
LineOptions configures line drawing.
type LinkStyle ¶
type LinkStyle struct {
// Font to use for the link text.
Font FontName
// Size of the font in points.
Size float64
// Color of the link text (RGB, 0.0 to 1.0 range).
Color Color
// Underline indicates whether to draw a line under the link text.
// Default: true (like web browsers).
Underline bool
}
LinkStyle defines the visual style for a link.
This controls how clickable links appear in the PDF. By default, links are displayed in blue with underline (like in web browsers).
Example:
// Default style (blue, underlined)
style := DefaultLinkStyle()
// Custom style (red, bold, no underline)
custom := LinkStyle{
Font: HelveticaBold,
Size: 14,
Color: Red,
Underline: false,
}
func DefaultLinkStyle ¶
func DefaultLinkStyle() LinkStyle
DefaultLinkStyle returns the default link style.
Default style:
- Font: Helvetica
- Size: 12pt
- Color: Blue (0, 0, 1)
- Underline: true
This matches the typical appearance of links in web browsers.
Example:
style := DefaultLinkStyle()
page.AddLinkStyled("Click here", "https://example.com", 100, 700, style)
type List ¶
type List struct {
// contains filtered or unexported fields
}
List represents a bullet or numbered list.
Lists support nested sublists, custom markers, and automatic text wrapping.
Example:
list := NewList()
list.SetBulletChar("•")
list.Add("First item")
list.Add("Second item with long text that will wrap")
page.Draw(list)
func NewList ¶
func NewList() *List
NewList creates a new bullet list with default settings.
Default settings:
- Marker: Bullet ("•")
- Font: Helvetica, 12pt
- Color: Black
- Line spacing: 1.2 (120%)
- Indent: 20pt per level
- Marker indent: 10pt
- Start number: 1
func NewNumberedList ¶
func NewNumberedList() *List
NewNumberedList creates a new numbered list with default settings.
Default settings:
- Marker: Number (1. 2. 3.)
- Font: Helvetica, 12pt
- Color: Black
- Line spacing: 1.2 (120%)
- Indent: 20pt per level
- Marker indent: 10pt
- Start number: 1
func (*List) AddSubList ¶
AddSubList adds a nested sublist as the last item. Returns the list for method chaining.
func (*List) Draw ¶
func (l *List) Draw(ctx *LayoutContext, page *Page) error
Draw renders the list on the page at the current cursor position.
func (*List) Height ¶
func (l *List) Height(ctx *LayoutContext) float64
Height calculates the total height of the list when rendered.
func (*List) SetBulletChar ¶
SetBulletChar sets the bullet character for bullet lists. Returns the list for method chaining.
func (*List) SetFont ¶
SetFont sets the font and size for the list. Returns the list for method chaining.
func (*List) SetIndent ¶
SetIndent sets the indentation per nesting level. Returns the list for method chaining.
func (*List) SetLineSpacing ¶
SetLineSpacing sets the line spacing multiplier. 1.0 = single spacing, 1.5 = 150% spacing, 2.0 = double spacing. Returns the list for method chaining.
func (*List) SetMarkerIndent ¶
SetMarkerIndent sets the space between marker and text. Returns the list for method chaining.
func (*List) SetMarkerType ¶
func (l *List) SetMarkerType(t MarkerType) *List
SetMarkerType sets the marker type (bullet or number). Returns the list for method chaining.
func (*List) SetNumberFormat ¶
func (l *List) SetNumberFormat(f NumberFormat) *List
SetNumberFormat sets the numbering format for numbered lists. Returns the list for method chaining.
func (*List) SetStartNumber ¶
SetStartNumber sets the starting number for numbered lists. Returns the list for method chaining.
type ListItem ¶
type ListItem struct {
// contains filtered or unexported fields
}
ListItem represents a single item in a list.
func NewListItem ¶
NewListItem creates a new list item with the given text.
func NewListItemWithSubList ¶
NewListItemWithSubList creates a new list item with a nested list.
type MarkerType ¶
type MarkerType int
MarkerType defines the type of list marker.
const ( // BulletMarker represents a bullet list (•, -, *, etc.). BulletMarker MarkerType = iota // NumberMarker represents a numbered list (1., 2., 3. or a), b), c) etc.). NumberMarker )
type Merger ¶
type Merger struct {
// contains filtered or unexported fields
}
Merger provides flexible page selection when merging PDFs.
Use Merger when you need fine-grained control over which pages to include in the merged output.
Example - Merge specific pages:
merger := creator.NewMerger()
merger.AddPages("file1.pdf", 1, 2, 3) // Pages 1-3
merger.AddPages("file2.pdf", 5, 10) // Pages 5-10
merger.AddAllPages("file3.pdf") // All pages
err := merger.Write("output.pdf")
Example - Merge with page range:
merger := creator.NewMerger()
merger.AddPageRange("input.pdf", 1, 5) // Pages 1-5
err := merger.Write("output.pdf")
func NewMerger ¶
func NewMerger() *Merger
NewMerger creates a new Merger instance.
Example:
merger := creator.NewMerger()
// Add pages...
merger.Write("output.pdf")
func (*Merger) AddAllPages ¶
AddAllPages adds all pages from a PDF file.
Parameters:
- path: Path to the PDF file
Returns an error if file cannot be opened.
Example:
merger.AddAllPages("input.pdf") // Add all pages
func (*Merger) AddPageRange ¶
AddPageRange adds a range of pages from a PDF file.
Page numbers are 1-based and inclusive (start and end are both included).
Parameters:
- path: Path to the PDF file
- start: First page number (1-based, inclusive)
- end: Last page number (1-based, inclusive)
Returns an error if:
- File cannot be opened
- Range is invalid (start > end, or out of bounds)
Example:
merger.AddPageRange("input.pdf", 1, 5) // Add pages 1-5
func (*Merger) AddPages ¶
AddPages adds specific pages from a PDF file.
Page numbers are 1-based (1 = first page, 2 = second page, etc.). Pages are added in the order specified.
Parameters:
- path: Path to the PDF file
- pageNums: Page numbers to add (1-based)
Returns an error if:
- File cannot be opened
- Any page number is invalid (< 1 or > page count)
Example:
merger.AddPages("input.pdf", 1, 3, 5) // Add pages 1, 3, 5
func (*Merger) Close ¶
Close closes all opened PDF readers and releases resources.
This is automatically called by Write(), but can be called manually if you need to release resources before writing.
func (*Merger) Write ¶
Write writes the merged PDF to a file.
This copies all selected pages to the output document and writes it.
Parameters:
- path: Path to the output PDF file
Returns an error if:
- No pages have been added
- Page content cannot be copied
- Output file cannot be created or written
Example:
err := merger.Write("output.pdf")
func (*Merger) WriteContext ¶
WriteContext writes the merged PDF with context support.
This allows cancellation and timeout control.
Example:
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() err := merger.WriteContext(ctx, "output.pdf")
type NumberFormat ¶
type NumberFormat int
NumberFormat defines the numbering style.
const ( // NumberFormatArabic uses Arabic numerals (1. 2. 3.). NumberFormatArabic NumberFormat = iota // NumberFormatLowerAlpha uses lowercase letters (a. b. c.). NumberFormatLowerAlpha // NumberFormatUpperAlpha uses uppercase letters (A. B. C.). NumberFormatUpperAlpha // NumberFormatLowerRoman uses lowercase Roman numerals (i. ii. iii.). NumberFormatLowerRoman // NumberFormatUpperRoman uses uppercase Roman numerals (I. II. III.). NumberFormatUpperRoman )
type Orientation ¶ added in v0.4.0
type Orientation int
Orientation represents page orientation (portrait or landscape).
Use as an optional parameter to Creator.NewPageWithSize to control page orientation. Portrait is the default — width < height. Landscape swaps width and height so that the page is wider than it is tall.
This uses the industry-standard swapped-MediaBox approach (not /Rotate), so content coordinates remain natural: (0,0) is bottom-left of the page.
Note: Presentation sizes (Slide16x9, Slide4x3) are already landscape-oriented (width > height). Passing Landscape to Creator.NewPageWithSize with these sizes will swap them to portrait orientation, which is rarely desired for slides.
const ( // Portrait is the default page orientation (taller than wide). Portrait Orientation = iota // Landscape rotates the page so it is wider than tall. // Internally this swaps MediaBox width and height — no /Rotate entry is used, // so content coordinates remain natural. Landscape )
type Page ¶
type Page struct {
// contains filtered or unexported fields
}
Page represents a page in the PDF document being created.
This is a high-level wrapper around the domain Page entity, providing a simplified API for adding content.
Example:
page := creator.NewPage() // Add text, images, etc. to page...
func (*Page) AddField ¶
AddField adds a form field to the page.
Form fields allow user input and interaction in PDF documents. This is part of the AcroForm (Interactive Forms) system.
Supported field types:
- TextField: Single-line or multi-line text input
- (Future: CheckBox, RadioButton, ComboBox, ListBox, PushButton)
Example:
field := forms.NewTextField("username", 100, 700, 200, 20)
field.SetValue("John Doe").SetRequired(true)
page.AddField(field)
func (*Page) AddHighlightAnnotation ¶
func (p *Page) AddHighlightAnnotation(annotation *HighlightAnnotation) error
AddHighlightAnnotation adds a highlight annotation to the page.
The highlight marks text with a colored overlay.
Example:
highlight := creator.NewHighlightAnnotation(100, 650, 300, 670)
highlight.SetColor(creator.Yellow).SetAuthor("Bob")
page.AddHighlightAnnotation(highlight)
func (*Page) AddInternalLink ¶
func (p *Page) AddInternalLink(text string, destPage int, x, y float64, font FontName, size float64) error
AddInternalLink adds a link to another page in the document.
The destPage parameter is 0-based (0 = first page, 1 = second page, etc.).
Parameters:
- text: The link text to display
- destPage: Target page number (0-based)
- x: Horizontal position in points (from left edge)
- y: Vertical position in points (from bottom edge)
- font: Font to use for the link text
- size: Font size in points
Example:
page.AddInternalLink("See page 3", 2, 100, 600, creator.Helvetica, 12)
func (*Page) AddLink ¶
AddLink adds a clickable URL link with default styling (blue, underlined).
The text is rendered at the specified position and made clickable. A clickable annotation is created that covers the text area.
Parameters:
- text: The link text to display
- url: The target URL (e.g., "https://example.com")
- x: Horizontal position in points (from left edge)
- y: Vertical position in points (from bottom edge)
- font: Font to use for the link text
- size: Font size in points
Example:
page.AddLink("Visit Google", "https://google.com", 100, 700, creator.Helvetica, 12)
func (*Page) AddLinkStyled ¶
AddLinkStyled adds a clickable URL link with custom styling.
This gives full control over the link appearance (font, size, color, underline).
Parameters:
- text: The link text to display
- url: The target URL (e.g., "https://example.com")
- x: Horizontal position in points (from left edge)
- y: Vertical position in points (from bottom edge)
- style: Visual style for the link
Example:
style := creator.LinkStyle{
Font: creator.HelveticaBold,
Size: 14,
Color: creator.Red,
Underline: false,
}
page.AddLinkStyled("Click here", "https://example.com", 100, 700, style)
func (*Page) AddStampAnnotation ¶
func (p *Page) AddStampAnnotation(annotation *StampAnnotation) error
AddStampAnnotation adds a stamp annotation to the page.
The stamp displays predefined text like "Approved", "Draft", etc.
Example:
stamp := creator.NewStampAnnotation(300, 700, 100, 50, creator.StampApproved)
stamp.SetColor(creator.Green).SetAuthor("Manager")
page.AddStampAnnotation(stamp)
func (*Page) AddStrikeOutAnnotation ¶
func (p *Page) AddStrikeOutAnnotation(annotation *StrikeOutAnnotation) error
AddStrikeOutAnnotation adds a strikeout annotation to the page.
The strikeout draws a line through text.
Example:
strikeout := creator.NewStrikeOutAnnotation(100, 650, 300, 670) strikeout.SetColor(creator.Red) page.AddStrikeOutAnnotation(strikeout)
func (*Page) AddText ¶
AddText adds text to the page at the specified position with default black color.
Parameters:
- text: The string to display
- x: Horizontal position in points (from left edge)
- y: Vertical position in points (from bottom edge)
- font: Font to use (one of the Standard 14 fonts)
- size: Font size in points
Example:
err := page.AddText("Hello World", 100, 700, creator.Helvetica, 24)
func (*Page) AddTextAnnotation ¶
func (p *Page) AddTextAnnotation(annotation *TextAnnotation) error
AddTextAnnotation adds a text (sticky note) annotation to the page.
The annotation appears as a small icon at the specified position. When clicked, it displays the contents in a pop-up.
Example:
note := creator.NewTextAnnotation(100, 700, "Review this section")
note.SetAuthor("Alice").SetColor(creator.Yellow)
page.AddTextAnnotation(note)
func (*Page) AddTextColor ¶
func (p *Page) AddTextColor(text string, x, y float64, font FontName, size float64, color Color) error
AddTextColor adds colored text to the page at the specified position.
Parameters:
- text: The string to display
- x: Horizontal position in points (from left edge)
- y: Vertical position in points (from bottom edge)
- font: Font to use (one of the Standard 14 fonts)
- size: Font size in points
- color: Text color (RGB, 0.0 to 1.0 range)
Example:
err := page.AddTextColor("Error!", 100, 700, creator.HelveticaBold, 18, creator.Red)
func (*Page) AddTextColorAlpha ¶ added in v0.5.0
func (p *Page) AddTextColorAlpha(text string, x, y float64, font FontName, size float64, color Color, opacity float64) error
AddTextColorAlpha adds colored text with opacity to the page.
Opacity controls the transparency level of the text (ISO 32000 §11.6.4.4):
- 1.0 = fully opaque (default)
- 0.5 = 50% transparent
- 0.0 = fully transparent
The opacity is implemented via an ExtGState resource with /ca (fill alpha) and /CA (stroke alpha) keys. Values are clamped to [0.0, 1.0].
Parameters:
- text: The string to display
- x: Horizontal position in points (from left edge)
- y: Vertical position in points (from bottom edge)
- font: Font to use (one of the Standard 14 fonts)
- size: Font size in points
- color: Text color (RGB, 0.0 to 1.0 range)
- opacity: Transparency level (0.0 to 1.0)
Example:
// Semi-transparent watermark text
err := page.AddTextColorAlpha("DRAFT", 200, 400, creator.HelveticaBold, 48, creator.Gray, 0.3)
func (*Page) AddTextColorCMYK ¶
func (p *Page) AddTextColorCMYK(text string, x, y float64, font FontName, size float64, color ColorCMYK) error
AddTextColorCMYK adds CMYK-colored text to the page at the specified position.
CMYK (Cyan, Magenta, Yellow, blacK) is a subtractive color model used in professional printing. This method should be used when precise color control is needed for print production.
Parameters:
- text: The string to display
- x: Horizontal position in points (from left edge)
- y: Vertical position in points (from bottom edge)
- font: Font to use (one of the Standard 14 fonts)
- size: Font size in points
- color: Text color (CMYK, 0.0 to 1.0 range)
Example:
// Pure cyan for printing
cyan := creator.NewColorCMYK(1.0, 0.0, 0.0, 0.0)
err := page.AddTextColorCMYK("Print-ready text", 100, 700, creator.Helvetica, 12, cyan)
func (*Page) AddTextColorRotated ¶ added in v0.4.0
func (p *Page) AddTextColorRotated(text string, x, y float64, font FontName, size float64, color Color, rotation float64) error
AddTextColorRotated adds colored rotated text to the page at the specified position.
Rotation follows the PDF/PostScript mathematical convention (ISO 32000 §8.3): positive angles rotate counter-clockwise, negative angles rotate clockwise. Angles are normalized to [0, 360) internally — for example, -90 and 270 produce identical output. Fractional angles are fully supported.
Parameters:
- text: The string to display
- x: Horizontal position in points (from left edge) — also the rotation pivot
- y: Vertical position in points (from bottom edge) — also the rotation pivot
- font: Font to use (one of the Standard 14 fonts)
- size: Font size in points
- color: Text color (RGB, 0.0 to 1.0 range)
- rotation: Rotation angle in degrees (counter-clockwise positive)
Example:
// Diagonal red label at 45 degrees
err := page.AddTextColorRotated("DRAFT", 300, 400, creator.HelveticaBold, 48, creator.Red, 45)
func (*Page) AddTextColorRotatedAlpha ¶ added in v0.5.0
func (p *Page) AddTextColorRotatedAlpha(text string, x, y float64, font FontName, size float64, color Color, rotation, opacity float64) error
AddTextColorRotatedAlpha adds colored rotated text with opacity to the page.
Combines rotation (ISO 32000 §8.3) and opacity (ISO 32000 §11.6.4.4). Rotation angles are normalized to [0, 360). Opacity is clamped to [0.0, 1.0].
Parameters:
- text: The string to display
- x: Horizontal position in points (from left edge) — also the rotation pivot
- y: Vertical position in points (from bottom edge) — also the rotation pivot
- font: Font to use (one of the Standard 14 fonts)
- size: Font size in points
- color: Text color (RGB, 0.0 to 1.0 range)
- rotation: Rotation angle in degrees (counter-clockwise positive)
- opacity: Transparency level (0.0 to 1.0)
Example:
// Diagonal semi-transparent watermark
err := page.AddTextColorRotatedAlpha("CONFIDENTIAL", 300, 400, creator.HelveticaBold, 36, creator.Red, 45, 0.2)
func (*Page) AddTextCustomFont ¶ added in v0.1.1
AddTextCustomFont adds text using an embedded TrueType/OpenType font.
This method supports Unicode text including Cyrillic, CJK, Arabic, and symbols. The font is automatically subset to include only the glyphs used in the document.
Parameters:
- text: The string to display (supports Unicode)
- x: Horizontal position in points (from left edge)
- y: Vertical position in points (from bottom edge)
- font: Custom font loaded via LoadFont()
- size: Font size in points
Example:
font, _ := creator.LoadFont("fonts/OpenSans-Regular.ttf")
err := page.AddTextCustomFont("Привет мир! 你好世界!", 100, 700, font, 24)
func (*Page) AddTextCustomFontColor ¶ added in v0.1.1
func (p *Page) AddTextCustomFontColor(text string, x, y float64, font *CustomFont, size float64, color Color) error
AddTextCustomFontColor adds colored text using an embedded TrueType/OpenType font.
This method supports Unicode text including Cyrillic, CJK, Arabic, and symbols. The font is automatically subset to include only the glyphs used in the document.
Parameters:
- text: The string to display (supports Unicode)
- x: Horizontal position in points (from left edge)
- y: Vertical position in points (from bottom edge)
- font: Custom font loaded via LoadFont()
- size: Font size in points
- color: Text color (RGB, 0.0 to 1.0 range)
Example:
font, _ := creator.LoadFont("fonts/OpenSans-Bold.ttf")
err := page.AddTextCustomFontColor("重要!", 100, 700, font, 24, creator.Red)
func (*Page) AddTextCustomFontColorAlpha ¶ added in v0.5.0
func (p *Page) AddTextCustomFontColorAlpha(text string, x, y float64, font *CustomFont, size float64, color Color, opacity float64) error
AddTextCustomFontColorAlpha adds colored text with opacity using an embedded TrueType/OpenType font.
Supports Unicode text (Cyrillic, CJK, Arabic, symbols) with transparency. Opacity is implemented via ExtGState (ISO 32000 §11.6.4.4).
Parameters:
- text: The string to display (supports Unicode)
- x: Horizontal position in points (from left edge)
- y: Vertical position in points (from bottom edge)
- font: Custom font loaded via LoadFont()
- size: Font size in points
- color: Text color (RGB, 0.0 to 1.0 range)
- opacity: Transparency level (0.0 to 1.0)
Example:
font, _ := creator.LoadFont("fonts/OpenSans-Regular.ttf")
err := page.AddTextCustomFontColorAlpha("Полупрозрачный", 100, 700, font, 24, creator.Blue, 0.5)
func (*Page) AddTextCustomFontColorRotated ¶ added in v0.4.0
func (p *Page) AddTextCustomFontColorRotated(text string, x, y float64, font *CustomFont, size float64, color Color, rotation float64) error
AddTextCustomFontColorRotated adds colored rotated text using an embedded TrueType/OpenType font.
Rotation follows the PDF/PostScript mathematical convention (ISO 32000 §8.3): positive angles rotate counter-clockwise, negative angles rotate clockwise. Angles are normalized to [0, 360) internally. Fractional angles are supported. This is the custom font equivalent of Page.AddTextColorRotated.
Example:
err := page.AddTextCustomFontColorRotated("DRAFT", 300, 400, font, 48, creator.Red, 45)
func (*Page) AddTextCustomFontColorRotatedAlpha ¶ added in v0.5.0
func (p *Page) AddTextCustomFontColorRotatedAlpha(text string, x, y float64, font *CustomFont, size float64, color Color, rotation, opacity float64) error
AddTextCustomFontColorRotatedAlpha adds colored rotated text with opacity using an embedded font.
Combines custom font support, rotation, and opacity. This is the most flexible text method, supporting Unicode, rotation (ISO 32000 §8.3), and transparency (ISO 32000 §11.6.4.4) simultaneously.
Parameters:
- text: The string to display (supports Unicode)
- x: Horizontal position in points (from left edge) — also the rotation pivot
- y: Vertical position in points (from bottom edge) — also the rotation pivot
- font: Custom font loaded via LoadFont()
- size: Font size in points
- color: Text color (RGB, 0.0 to 1.0 range)
- rotation: Rotation angle in degrees (counter-clockwise positive)
- opacity: Transparency level (0.0 to 1.0)
Example:
font, _ := creator.LoadFont("fonts/OpenSans-Bold.ttf")
err := page.AddTextCustomFontColorRotatedAlpha("DRAFT", 300, 400, font, 48, creator.Red, 45, 0.3)
func (*Page) AddTextCustomFontRotated ¶ added in v0.4.0
func (p *Page) AddTextCustomFontRotated(text string, x, y float64, font *CustomFont, size float64, rotation float64) error
AddTextCustomFontRotated adds rotated text using an embedded TrueType/OpenType font.
Rotation follows the PDF/PostScript mathematical convention (ISO 32000 §8.3): positive angles rotate counter-clockwise, negative angles rotate clockwise. Angles are normalized to [0, 360) internally. Fractional angles are supported. This is the custom font equivalent of Page.AddTextRotated.
Example:
err := page.AddTextCustomFontRotated("Sidebar", 50, 400, font, 14, 90)
func (*Page) AddTextRotated ¶ added in v0.4.0
func (p *Page) AddTextRotated(text string, x, y float64, font FontName, size float64, rotation float64) error
AddTextRotated adds rotated text to the page at the specified position with default black color.
Rotation follows the PDF/PostScript mathematical convention (ISO 32000 §8.3): positive angles rotate counter-clockwise, negative angles rotate clockwise. Angles are normalized to [0, 360) internally — for example, -90 and 270 produce identical output.
Common angles:
- 90: vertical text running bottom-to-top
- 270 (or -90): vertical text running top-to-bottom
- 180: upside-down text
- 45: diagonal text
Fractional angles (e.g. 22.5, 33.3) are fully supported.
Parameters:
- text: The string to display
- x: Horizontal position in points (from left edge) — also the rotation pivot
- y: Vertical position in points (from bottom edge) — also the rotation pivot
- font: Font to use (one of the Standard 14 fonts)
- size: Font size in points
- rotation: Rotation angle in degrees (counter-clockwise positive)
Example:
// Vertical text running bottom-to-top
err := page.AddTextRotated("Sideways", 100, 400, creator.Helvetica, 14, 90)
func (*Page) AddUnderlineAnnotation ¶
func (p *Page) AddUnderlineAnnotation(annotation *UnderlineAnnotation) error
AddUnderlineAnnotation adds an underline annotation to the page.
The underline draws a line under text.
Example:
underline := creator.NewUnderlineAnnotation(100, 650, 300, 670) underline.SetColor(creator.Blue) page.AddUnderlineAnnotation(underline)
func (*Page) BeginClipRect ¶ added in v0.1.1
BeginClipRect begins a rectangular clipping region.
All subsequent drawing operations (shapes, text, images) will be clipped to the specified rectangle. Content outside the rectangle will not be visible.
This is useful for tables where text should not overflow cell boundaries.
You MUST call EndClip() after drawing the clipped content to restore the previous graphics state. Clipping regions can be nested.
Parameters:
- x, y: Lower-left corner of the clipping rectangle
- width, height: Size of the clipping rectangle
Example:
// Clip text to a cell boundary
page.BeginClipRect(100, 500, 200, 30)
page.AddText("Very long text that would overflow...", 105, 510, opts)
page.EndClip()
func (*Page) ContentHeight ¶
ContentHeight returns the usable height (page height minus top and bottom margins).
func (*Page) ContentWidth ¶
ContentWidth returns the usable width (page width minus left and right margins).
func (*Page) Draw ¶
Draw renders a Drawable element on the page.
This uses the page's layout context and automatically positions the element. The cursor advances after drawing.
Example:
p := NewParagraph("Hello World")
page.Draw(p)
func (*Page) DrawAt ¶
DrawAt renders a Drawable element at a specific position.
x is measured from the left edge of the page. y is measured from the top of the content area (below top margin).
Example:
p := NewParagraph("Hello World")
page.DrawAt(p, 100, 50) // 100 points from left, 50 from top
func (*Page) DrawBezierCurve ¶
func (p *Page) DrawBezierCurve(segments []BezierSegment, opts *BezierOptions) error
DrawBezierCurve draws a complex curve composed of one or more cubic Bézier segments.
A Bézier curve provides smooth, flowing curves that are widely used in vector graphics. Multiple segments can be connected to create complex paths.
Parameters:
- segments: Array of Bézier curve segments (minimum 1 segment)
- opts: Curve options (color, width, dash pattern, closed path)
Example (simple S-curve):
opts := &creator.BezierOptions{
Color: creator.Blue,
Width: 2.0,
}
segments := []creator.BezierSegment{
{
Start: creator.Point{X: 100, Y: 100},
C1: creator.Point{X: 150, Y: 200},
C2: creator.Point{X: 200, Y: 200},
End: creator.Point{X: 250, Y: 100},
},
}
err := page.DrawBezierCurve(segments, opts)
Example (closed filled shape):
opts := &creator.BezierOptions{
Color: creator.Black,
Width: 1.0,
Closed: true,
FillColor: &creator.Yellow,
}
segments := []creator.BezierSegment{
// ... multiple segments forming a closed shape
}
err := page.DrawBezierCurve(segments, opts)
func (*Page) DrawCircle ¶
func (p *Page) DrawCircle(cx, cy, radius float64, opts *CircleOptions) error
DrawCircle draws a circle at center (cx,cy) with given radius.
The circle can be stroked, filled, or both, depending on the options. The circle is approximated using 4 cubic Bézier curves.
Parameters:
- cx, cy: Center coordinates
- radius: Circle radius
- opts: Circle options (stroke color, fill color, stroke width)
Example:
opts := &creator.CircleOptions{
StrokeColor: &creator.Red,
StrokeWidth: 2.0,
FillColor: &creator.Yellow,
}
err := page.DrawCircle(300, 400, 50, opts)
func (*Page) DrawEllipse ¶
func (p *Page) DrawEllipse(cx, cy, rx, ry float64, opts *EllipseOptions) error
DrawEllipse draws an ellipse at center (cx, cy) with horizontal radius rx and vertical radius ry.
An ellipse is approximated using 4 cubic Bézier curves. For a circle, set rx = ry.
The ellipse can be stroked, filled, or both, depending on the options.
Parameters:
- cx, cy: Center coordinates
- rx: Horizontal radius (half-width)
- ry: Vertical radius (half-height)
- opts: Ellipse options (stroke color, fill color, stroke width)
Example:
opts := &creator.EllipseOptions{
StrokeColor: &creator.Black,
StrokeWidth: 2.0,
FillColor: &creator.Green,
}
err := page.DrawEllipse(150, 200, 100, 50, opts) // Horizontal ellipse
func (*Page) DrawImage ¶
DrawImage draws an image at the specified position and size.
The image is scaled to fit the specified width and height. No aspect ratio preservation - the image is stretched to fit.
Parameters:
- img: The image to draw
- x: Horizontal position in points (from left edge)
- y: Vertical position in points (from bottom edge)
- width: Display width in points
- height: Display height in points
Example:
img, _ := creator.LoadImage("photo.jpg")
page.DrawImage(img, 100, 500, 200, 150)
func (*Page) DrawImageFit ¶
DrawImageFit draws an image scaled to fit within the specified dimensions.
The image is scaled to fit within the width/height while maintaining its aspect ratio. The image is centered in the available space.
Parameters:
- img: The image to draw
- x: Horizontal position in points (from left edge)
- y: Vertical position in points (from bottom edge)
- maxWidth: Maximum width in points
- maxHeight: Maximum height in points
Example:
img, _ := creator.LoadImage("photo.jpg")
page.DrawImageFit(img, 100, 500, 200, 200) // Fit in 200x200 box
func (*Page) DrawLine ¶
func (p *Page) DrawLine(x1, y1, x2, y2 float64, opts *LineOptions) error
DrawLine draws a line from (x1,y1) to (x2,y2).
Parameters:
- x1, y1: Starting point coordinates
- x2, y2: Ending point coordinates
- opts: Line options (color, width, dash pattern)
Example:
opts := &creator.LineOptions{
Color: creator.Black,
Width: 2.0,
}
err := page.DrawLine(100, 700, 500, 700, opts)
func (*Page) DrawPolygon ¶
func (p *Page) DrawPolygon(vertices []Point, opts *PolygonOptions) error
DrawPolygon draws a closed polygon through the specified vertices.
A polygon is a closed shape with N vertices. The path automatically closes from the last vertex back to the first.
The polygon can be stroked, filled, or both, depending on the options.
Parameters:
- vertices: Array of points defining the polygon vertices (minimum 3 points)
- opts: Polygon options (stroke color, fill color, width, dash pattern)
Example:
opts := &creator.PolygonOptions{
StrokeColor: &creator.Black,
StrokeWidth: 2.0,
FillColor: &creator.Blue,
}
vertices := []creator.Point{
{X: 100, Y: 100},
{X: 150, Y: 50},
{X: 200, Y: 100},
{X: 175, Y: 150},
{X: 125, Y: 150},
}
err := page.DrawPolygon(vertices, opts)
func (*Page) DrawPolyline ¶
func (p *Page) DrawPolyline(vertices []Point, opts *PolylineOptions) error
DrawPolyline draws an open path through the specified vertices.
A polyline is an open path (not closed) that connects N vertices. Unlike a polygon, the path does NOT automatically close back to the first point.
Parameters:
- vertices: Array of points defining the polyline path (minimum 2 points)
- opts: Polyline options (color, width, dash pattern)
Example:
opts := &creator.PolylineOptions{
Color: creator.Red,
Width: 2.0,
}
vertices := []creator.Point{
{X: 100, Y: 100},
{X: 150, Y: 50},
{X: 200, Y: 100},
{X: 250, Y: 75},
}
err := page.DrawPolyline(vertices, opts)
func (*Page) DrawQuadBezierCurve ¶ added in v0.5.0
func (p *Page) DrawQuadBezierCurve(segments []QuadBezierSegment, opts *BezierOptions) error
DrawQuadBezierCurve draws a curve composed of one or more quadratic Bézier segments.
Quadratic Bézier curves are defined by a single control point per segment (compared to two control points for cubic Bézier curves). They are the curve primitive used in TrueType font outlines and the SVG "Q" command.
Because the PDF specification (ISO 32000, section 8.5.2) only supports cubic Bézier curves via the "c" content-stream operator, each quadratic segment is converted to an exact cubic equivalent using degree elevation before writing to the PDF. The conversion is lossless — the rendered curve is identical to the original quadratic specification.
Multiple segments are connected end-to-end to form a compound path. Each segment's Start point must match the previous segment's End point (within a floating-point epsilon of 0.001). This mirrors the continuity requirement of [DrawBezierCurve].
All BezierOptions apply equally to quadratic and cubic curves: stroke color, width, dash patterns, closed paths, fill colors, and opacity.
Parameters:
- segments: One or more quadratic Bézier segments (minimum 1).
- opts: Curve drawing options (must not be nil).
Example (simple quadratic arc):
opts := &creator.BezierOptions{
Color: creator.Blue,
Width: 2.0,
}
segments := []creator.QuadBezierSegment{
{
Start: creator.Point{X: 100, Y: 100},
Control: creator.Point{X: 175, Y: 200},
End: creator.Point{X: 250, Y: 100},
},
}
err := page.DrawQuadBezierCurve(segments, opts)
Example (multi-segment wave):
segments := []creator.QuadBezierSegment{
{Start: creator.Point{X: 50, Y: 100}, Control: creator.Point{X: 100, Y: 150}, End: creator.Point{X: 150, Y: 100}},
{Start: creator.Point{X: 150, Y: 100}, Control: creator.Point{X: 200, Y: 50}, End: creator.Point{X: 250, Y: 100}},
}
err := page.DrawQuadBezierCurve(segments, opts)
func (*Page) DrawRect ¶
func (p *Page) DrawRect(x, y, width, height float64, opts *RectOptions) error
DrawRect draws a rectangle at (x,y) with given width and height.
The rectangle can be stroked, filled, or both, depending on the options.
Parameters:
- x, y: Lower-left corner coordinates
- width, height: Rectangle dimensions
- opts: Rectangle options (stroke color, fill color, width, dash pattern)
Example:
opts := &creator.RectOptions{
StrokeColor: &creator.Black,
StrokeWidth: 1.0,
FillColor: &creator.LightGray,
}
err := page.DrawRect(100, 600, 200, 100, opts)
func (*Page) DrawRectFilled ¶
DrawRectFilled draws a filled rectangle (convenience method).
This is a shorthand for DrawRect with only fill color.
Parameters:
- x, y: Lower-left corner coordinates
- width, height: Rectangle dimensions
- fillColor: Fill color
Example:
err := page.DrawRectFilled(100, 600, 200, 100, creator.LightGray)
func (*Page) DrawTextClipped ¶ added in v0.1.1
func (p *Page) DrawTextClipped(text string, textX, textY, clipX, clipY, clipW, clipH float64, font *CustomFont, fontSize float64, color Color) error
DrawTextClipped draws text that is clipped to a rectangular region.
This is useful for table cells where text should not overflow the cell boundary. Text that extends beyond the clipping rectangle will be cut off (not visible).
Parameters:
- text: The text to render
- textX, textY: Position of the text baseline
- clipX, clipY, clipW, clipH: Clipping rectangle (text outside is hidden)
- font: Custom font to use
- fontSize: Font size in points
- color: Text color
Example:
// Draw text clipped to a 100pt wide cell
page.DrawTextClipped("Very long text...", 55, 510, 50, 500, 100, 30, font, 10, Black)
func (*Page) DrawWatermark ¶
func (p *Page) DrawWatermark(wm *TextWatermark) error
DrawWatermark applies a text watermark to the page.
The watermark is rendered as semi-transparent text positioned according to the watermark's settings.
Example:
wm := creator.NewTextWatermark("CONFIDENTIAL")
wm.SetOpacity(0.3)
page.DrawWatermark(wm)
func (*Page) EndClip ¶ added in v0.1.1
EndClip ends a clipping region started by BeginClipRect.
This restores the graphics state to what it was before BeginClipRect was called. Every BeginClipRect MUST have a matching EndClip.
func (*Page) GetLayoutContext ¶
func (p *Page) GetLayoutContext() *LayoutContext
GetLayoutContext creates a LayoutContext for this page.
The context is initialized with the cursor at the top-left of the content area (inside margins).
Example:
ctx := page.GetLayoutContext()
paragraph := NewParagraph("Hello World")
paragraph.Draw(ctx, page)
func (*Page) GraphicsOperations ¶
func (p *Page) GraphicsOperations() []GraphicsOperation
GraphicsOperations returns all graphics operations for this page.
This is used by the writer infrastructure to generate the content stream.
func (*Page) Height ¶
Height returns the page height in points.
If the page is rotated 90 or 270 degrees, width and height are swapped.
func (*Page) MoveCursor ¶
MoveCursor moves the page's layout cursor to the specified position.
This affects subsequent Draw() calls that use the default layout context. Note: This creates a new context each time, so for multiple sequential draws, use GetLayoutContext() and pass it to Draw() on the Drawable directly.
x is measured from the left edge of the page. y is measured from the top of the content area (below top margin).
func (*Page) Rotate ¶
Rotate rotates the page by the specified degrees (clockwise).
Valid values are 0, 90, 180, and 270 degrees. This method sets the absolute rotation, not cumulative.
This is an alias for Page.SetRotation for API convenience. For true landscape pages, prefer Creator.NewPageWithSize with Landscape.
Example:
page.Rotate(90) // viewer rotates 90° clockwise page.Rotate(180) // upside down page.Rotate(270) // viewer rotates 270° clockwise
func (*Page) SetMargins ¶
SetMargins sets page-specific margins.
This overrides the default margins from the Creator.
Example:
page.SetMargins(36, 36, 36, 36) // 0.5 inch margins
func (*Page) SetRotation ¶
SetRotation sets the page /Rotate entry.
Valid values are 0, 90, 180, and 270 degrees (clockwise). This writes a /Rotate key into the page dictionary, which tells the viewer to rotate the rendered page. Content coordinates are NOT affected — text placed at (100, 700) will still appear at (100, 700) in the unrotated coordinate system.
For true landscape pages (swapped width/height, natural coordinates), use Creator.NewPageWithSize with Landscape instead.
Example:
page.SetRotation(90) // viewer rotates the page 90° clockwise
func (*Page) Surface ¶ added in v0.2.0
Surface creates a new drawing surface for this page.
Surface provides Skia-like Push/Pop semantics for graphics state management. This allows composable transformations, opacity, blend modes, and clipping.
Example:
surface := page.Surface() surface.PushTransform(Rotate(45)) surface.PushOpacity(0.5) // ... draw operations ... surface.Pop() surface.Pop()
func (*Page) TextOperations ¶
func (p *Page) TextOperations() []TextOperation
TextOperations returns all text operations for this page.
This is used by the writer infrastructure to generate the content stream.
type PageRange ¶
type PageRange struct {
Start int // First page (1-based, inclusive)
End int // Last page (1-based, inclusive)
Output string // Output file path
}
PageRange defines a range of pages to extract.
Page numbers are 1-based (1 = first page). Start and End are inclusive.
type PageSize ¶
type PageSize int
PageSize represents standard PDF page sizes.
Common page sizes are provided as constants (A4, Letter, etc.). For custom dimensions use NewPageWithDimensions on the Creator.
The iota values mirror document.PageSize exactly so that casting between creator.PageSize and document.PageSize is always valid.
const ( // A4 paper size (210 × 297 mm or 595 × 842 points). // This is the most common paper size worldwide. A4 PageSize = iota // A3 paper size (297 × 420 mm or 842 × 1191 points). // Twice the size of A4. A3 // A5 paper size (148 × 210 mm or 420 × 595 points). // Half the size of A4. A5 // B4 paper size (250 × 353 mm or 709 × 1001 points). B4 // B5 paper size (176 × 250 mm or 499 × 709 points). B5 // Letter paper size (8.5 × 11 inches or 612 × 792 points). // This is the standard size in North America. Letter // Legal paper size (8.5 × 14 inches or 612 × 1008 points). Legal // Tabloid paper size (11 × 17 inches or 792 × 1224 points). // Also known as Ledger when in landscape orientation. Tabloid // A0 paper size (841 × 1189 mm or 2384 × 3370 points). // Largest common A-series size. A0 // A1 paper size (594 × 841 mm or 1684 × 2384 points). A1 // A2 paper size (420 × 594 mm or 1191 × 1684 points). A2 // A6 paper size (105 × 148 mm or 298 × 420 points). Postcard size. A6 // A7 paper size (74 × 105 mm or 210 × 298 points). A7 // A8 paper size (52 × 74 mm or 147 × 210 points). A8 // B0 paper size (1000 × 1414 mm or 2835 × 4008 points). B0 // B1 paper size (707 × 1000 mm or 2004 × 2835 points). B1 // B2 paper size (500 × 707 mm or 1417 × 2004 points). B2 // B3 paper size (353 × 500 mm or 1001 × 1417 points). B3 // B6 paper size (125 × 176 mm or 354 × 499 points). B6 // C4 envelope (229 × 324 mm or 649 × 918 points). Fits A4 unfolded. C4 // C5 envelope (162 × 229 mm or 459 × 649 points). Fits A5 unfolded or A4 folded in half. C5 // C6 envelope (114 × 162 mm or 323 × 459 points). Fits A6 unfolded or A4 folded in quarters. C6 // DL envelope (110 × 220 mm or 312 × 624 points). Fits A4 folded in thirds. DL // Executive paper size (7.25 × 10.5 inches or 522 × 756 points). Executive // HalfLetter paper size (5.5 × 8.5 inches or 396 × 612 points). HalfLetter // ANSIC engineering drawing (17 × 22 inches or 1224 × 1584 points). ANSIC // ANSID engineering drawing (22 × 34 inches or 1584 × 2448 points). ANSID // ANSIE engineering drawing (34 × 44 inches or 2448 × 3168 points). ANSIE // Photo4x6 is a standard 4 × 6 inch photo (288 × 432 points). Photo4x6 // Photo5x7 is a standard 5 × 7 inch photo (360 × 504 points). Photo5x7 // Photo8x10 is a standard 8 × 10 inch photo (576 × 720 points). Photo8x10 // Digest is digest magazine size (5.5 × 8.5 inches or 396 × 612 points). Digest // USTradeBook is standard US trade book size (6 × 9 inches or 432 × 648 points). USTradeBook // Slide16x9 is a widescreen presentation slide at 16:9 aspect ratio (960 × 540 points). // Equivalent to 13.33 × 7.5 inches — matches PowerPoint/Keynote widescreen default. // This size is already landscape-oriented (width > height). // When exported at 2× DPI (144 dpi), this produces a 1920 × 1080 pixel image. Slide16x9 // Slide4x3 is a standard presentation slide at 4:3 aspect ratio (720 × 540 points). // Equivalent to 10 × 7.5 inches — matches the traditional slide format. // This size is already landscape-oriented (width > height). Slide4x3 // Envelope10 is a #10 commercial envelope (4.125 × 9.5 inches or 297 × 684 points). Envelope10 // JISB4 is Japanese B4 (257 × 364 mm or 729 × 1032 points). JISB4 // JISB5 is Japanese B5 (182 × 257 mm or 516 × 729 points). JISB5 )
type Paint ¶ added in v0.2.0
type Paint interface {
// contains filtered or unexported methods
}
Paint represents a paint source for fill and stroke operations.
Paint can be a solid color, a gradient, or a pattern (future). This interface allows uniform handling of different paint types.
Implemented by:
- Color (RGB solid color)
- ColorRGBA (RGB with alpha)
- ColorCMYK (CMYK solid color)
- Gradient (linear/radial gradient)
Example:
var paint Paint paint = Red // Solid color paint = NewColorRGBA(1, 0, 0, 0.5) // Transparent red paint = NewLinearGradient(0, 0, 100, 0) // Gradient
type Paragraph ¶
type Paragraph struct {
// contains filtered or unexported fields
}
Paragraph represents a block of text with automatic word wrapping.
Paragraphs automatically wrap text based on the available width, handle alignment, and track their height for layout purposes.
Example:
p := NewParagraph("This is a long text that will be wrapped automatically.")
p.SetFont(Helvetica, 12)
p.SetAlignment(AlignJustify)
page.Draw(p)
func NewParagraph ¶
NewParagraph creates a new paragraph with the given text.
Default settings:
- Font: Helvetica, 12pt
- Color: Black
- Alignment: Left
- Line spacing: 1.2 (120%)
func (*Paragraph) Draw ¶
func (p *Paragraph) Draw(ctx *LayoutContext, page *Page) error
Draw renders the paragraph on the page at the current cursor position.
func (*Paragraph) Height ¶
func (p *Paragraph) Height(ctx *LayoutContext) float64
Height calculates the total height of the paragraph when rendered.
func (*Paragraph) LineSpacing ¶
LineSpacing returns the current line spacing multiplier.
func (*Paragraph) SetAlignment ¶
SetAlignment sets the text alignment. Returns the paragraph for method chaining.
func (*Paragraph) SetColor ¶
SetColor sets the text color. Returns the paragraph for method chaining.
func (*Paragraph) SetFont ¶
SetFont sets the font and size for the paragraph. Returns the paragraph for method chaining.
func (*Paragraph) SetLineSpacing ¶
SetLineSpacing sets the line spacing multiplier. 1.0 = single spacing, 1.5 = 150% spacing, 2.0 = double spacing. Returns the paragraph for method chaining.
func (*Paragraph) SetText ¶
SetText sets the paragraph text. Returns the paragraph for method chaining.
func (*Paragraph) WrapTextLines ¶
WrapTextLines returns the lines after wrapping (for testing/debugging).
type Path ¶ added in v0.2.0
type Path struct {
// contains filtered or unexported fields
}
Path represents a vector path for drawing, filling, and clipping.
A Path consists of one or more subpaths, where each subpath is a sequence of connected lines and curves. Subpaths can be open or closed.
Path uses a fluent builder API for easy construction:
path := NewPath().
MoveTo(100, 100).
LineTo(200, 100).
QuadraticTo(250, 150, 200, 200).
CubicTo(150, 250, 100, 250, 100, 200).
Close()
Shape helpers provide shortcuts for common shapes:
circle := NewPath().AddCircle(Point{150, 150}, 50)
rect := NewPath().AddRect(Rect{X: 10, Y: 10, Width: 100, Height: 50})
Reference: PDF 1.7 Specification, Section 8.5 (Path Construction).
func NewPath ¶ added in v0.2.0
func NewPath() *Path
NewPath creates a new empty path.
The path starts with no current point. Use MoveTo to start a new subpath.
Example:
path := NewPath() path.MoveTo(100, 100) path.LineTo(200, 200)
func (*Path) AddArc ¶ added in v0.2.0
AddArc adds a circular arc to the path.
The arc is centered at 'center' with the specified radius. It spans from startAngle to endAngle (in degrees). Angles are measured counterclockwise from the positive X axis.
If there is a current point, a line is drawn from the current point to the arc start. Otherwise, MoveTo is used to start at the arc.
Parameters:
- center: Arc center point
- radius: Arc radius (must be positive)
- startAngle: Starting angle in degrees (0 = right, 90 = top)
- endAngle: Ending angle in degrees
Example:
// Quarter circle arc (90 degrees)
path := NewPath().
MoveTo(150, 150).
AddArc(Point{150, 150}, 50, 0, 90)
func (*Path) AddCircle ¶ added in v0.2.0
AddCircle adds a circle to the path.
The circle is approximated using 4 cubic Bézier curves. This provides a very accurate approximation (error < 0.06% of radius).
Parameters:
- center: Circle center point
- radius: Circle radius (must be positive)
Example:
path := NewPath().AddCircle(Point{150, 150}, 50)
func (*Path) AddEllipse ¶ added in v0.2.0
AddEllipse adds an ellipse to the path.
The ellipse is inscribed in the specified rectangle. It is approximated using 4 cubic Bézier curves.
Parameters:
- rect: Bounding rectangle of the ellipse
Example:
// Horizontal ellipse
path := NewPath().AddEllipse(Rect{X: 10, Y: 10, Width: 200, Height: 100})
func (*Path) AddRect ¶ added in v0.2.0
AddRect adds a rectangle to the path.
This is a convenience method that adds a closed rectangular subpath. The rectangle is drawn counterclockwise (for NonZero fill rule).
PDF operator: x y width height re
Parameters:
- rect: Rectangle to add
Example:
path := NewPath().
AddRect(Rect{X: 10, Y: 10, Width: 100, Height: 50}).
AddRect(Rect{X: 150, Y: 10, Width: 100, Height: 50})
func (*Path) AddRoundedRect ¶ added in v0.2.0
AddRoundedRect adds a rounded rectangle to the path.
The rectangle has rounded corners with the specified radius. Corners are drawn as quarter-circle arcs.
Parameters:
- rect: Rectangle bounds
- radius: Corner radius (must be non-negative)
Example:
// Rounded rectangle with 10-unit radius corners
path := NewPath().AddRoundedRect(
Rect{X: 10, Y: 10, Width: 100, Height: 50},
10,
)
func (*Path) Bounds ¶ added in v0.2.0
Bounds returns the bounding box of the path.
The bounding box is the smallest rectangle that contains all points in the path. This includes line endpoints and Bézier curve control points (which may be outside the actual curve).
Returns a zero Rect if the path is empty.
Example:
path := NewPath().
MoveTo(10, 10).
LineTo(100, 50).
LineTo(10, 90)
bounds := path.Bounds() // Rect{X: 10, Y: 10, Width: 90, Height: 80}
func (*Path) Clone ¶ added in v0.2.0
Clone creates a deep copy of the path.
The cloned path is independent of the original.
Example:
original := NewPath().MoveTo(0, 0).LineTo(100, 100) clone := original.Clone() clone.LineTo(200, 0) // Does not affect original
func (*Path) Close ¶ added in v0.2.0
Close closes the current subpath.
A straight line is appended from the current point to the subpath start. The subpath is marked as closed for filling purposes.
PDF operator: h
After Close(), there is no current point (call MoveTo to start a new subpath).
Example:
// Closed triangle
path := NewPath().
MoveTo(100, 100).
LineTo(200, 100).
LineTo(150, 200).
Close()
func (*Path) CubicTo ¶ added in v0.2.0
CubicTo appends a cubic Bézier curve to the path.
The curve goes from the current point to (x, y) using (c1x, c1y) and (c2x, c2y) as control points.
PDF operator: c1x c1y c2x c2y x y c
Panics if there is no current point (call MoveTo first).
Parameters:
- c1x, c1y: First control point
- c2x, c2y: Second control point
- x, y: Endpoint of the curve
Example:
// Smooth S-curve
path := NewPath().
MoveTo(100, 100).
CubicTo(150, 50, 200, 150, 250, 100)
func (*Path) IsEmpty ¶ added in v0.2.0
IsEmpty returns true if the path has no commands.
Example:
path := NewPath() fmt.Println(path.IsEmpty()) // true path.MoveTo(0, 0) fmt.Println(path.IsEmpty()) // false
func (*Path) LineTo ¶ added in v0.2.0
LineTo appends a straight line to the path.
The line goes from the current point to the specified point. The specified point becomes the new current point.
PDF operator: x y l
Panics if there is no current point (call MoveTo first).
Parameters:
- x, y: Coordinates of the line endpoint
Example:
path := NewPath().
MoveTo(100, 100).
LineTo(200, 100).
LineTo(200, 200)
func (*Path) MoveTo ¶ added in v0.2.0
MoveTo starts a new subpath at the specified point.
If there is a current subpath, it is left open (not closed). The specified point becomes the current point and the subpath start.
PDF operator: x y m
Parameters:
- x, y: Coordinates of the new subpath start
Example:
path := NewPath().MoveTo(100, 100)
func (*Path) QuadraticTo ¶ added in v0.2.0
QuadraticTo appends a quadratic Bézier curve to the path.
The curve goes from the current point to (x, y) using (cx, cy) as the control point.
PDF does not support quadratic Bézier curves directly, so this method converts the quadratic curve to a cubic curve using the standard algorithm:
CP1 = P0 + 2/3 * (CP - P0) CP2 = P1 + 2/3 * (CP - P1)
Where P0 is the current point, CP is (cx, cy), and P1 is (x, y).
Panics if there is no current point (call MoveTo first).
Parameters:
- cx, cy: Control point
- x, y: Endpoint of the curve
Example:
// Smooth parabolic curve
path := NewPath().
MoveTo(100, 100).
QuadraticTo(150, 50, 200, 100)
Reference: Converting between quadratic and cubic curves.
type Permission ¶
type Permission = security.Permission
Permission represents PDF document permissions.
Multiple permissions can be combined using the OR operator (|).
Example:
perms := PermissionPrint | PermissionCopy
type Point ¶
type Point struct {
X float64 // Horizontal position (points from left)
Y float64 // Vertical position (points from bottom)
}
Point represents a 2D point in PDF coordinate space.
type PolygonOptions ¶
type PolygonOptions struct {
// StrokeColor is the border color (nil = no stroke).
// If StrokeColorCMYK is set, this field is ignored.
StrokeColor *Color
// StrokeColorCMYK is the border color in CMYK (nil = no stroke).
// If set, this takes precedence over StrokeColor (RGB).
StrokeColorCMYK *ColorCMYK
// StrokeWidth is the border width in points (default: 1.0).
StrokeWidth float64
// FillColor is the fill color (nil = no fill).
// Mutually exclusive with FillGradient and FillColorCMYK.
// If FillColorCMYK is set, this field is ignored.
FillColor *Color
// FillColorCMYK is the fill color in CMYK (nil = no fill).
// If set, this takes precedence over FillColor (RGB).
// Mutually exclusive with FillGradient.
FillColorCMYK *ColorCMYK
// FillGradient is the gradient fill (nil = no gradient fill).
// Mutually exclusive with FillColor and FillColorCMYK.
FillGradient *Gradient
// Dashed enables dashed border rendering.
Dashed bool
// DashArray defines the dash pattern for the border.
// Only used when Dashed is true.
DashArray []float64
// DashPhase is the starting offset into the dash pattern.
// Only used when Dashed is true.
DashPhase float64
// Opacity is the polygon opacity (0.0 = transparent, 1.0 = opaque).
// Optional. If set, applies transparency via ExtGState.
// Affects both fill and stroke.
// Range: [0.0, 1.0]
Opacity *float64
}
PolygonOptions configures polygon drawing.
type PolylineOptions ¶
type PolylineOptions struct {
// Color is the line color (RGB, 0.0 to 1.0 range).
// If ColorCMYK is set, this field is ignored.
Color Color
// ColorCMYK is the line color in CMYK color space (optional).
// If set, this takes precedence over Color (RGB).
ColorCMYK *ColorCMYK
// Width is the line width in points (default: 1.0).
Width float64
// Dashed enables dashed line rendering.
Dashed bool
// DashArray defines the dash pattern (e.g., [3, 1] for "3 on, 1 off").
// Only used when Dashed is true.
DashArray []float64
// DashPhase is the starting offset into the dash pattern.
// Only used when Dashed is true.
DashPhase float64
// Opacity is the polyline opacity (0.0 = transparent, 1.0 = opaque).
// Optional. If set, applies transparency via ExtGState.
// Range: [0.0, 1.0]
Opacity *float64
}
PolylineOptions configures polyline drawing.
type QuadBezierSegment ¶ added in v0.5.0
type QuadBezierSegment struct {
// Start is the starting anchor point (P0).
// For the first segment this is the curve's entry point.
// For subsequent segments this should match the previous segment's End point.
Start Point
// Control is the single quadratic control point (P1).
// The curve does not pass through this point; it is attracted toward it.
Control Point
// End is the ending anchor point (P2).
End Point
}
QuadBezierSegment represents a quadratic Bézier curve segment.
A quadratic Bézier curve is defined by three points:
- Start point (P0): the curve's starting anchor
- Control point (P1): the single control point that shapes the curve
- End point (P2): the curve's ending anchor
Quadratic Bézier curves are the native curve primitive of TrueType font outlines and the SVG "Q" command. They offer one fewer degree of freedom than cubic Bézier curves and are therefore simpler to parameterize.
Because the PDF specification (ISO 32000) only supports cubic Bézier curves (the "c" operator), GxPDF converts each quadratic segment to an equivalent cubic segment using exact degree elevation via QuadBezierSegment.ToCubic. The conversion is mathematically exact — it is not an approximation.
func (QuadBezierSegment) ToCubic ¶ added in v0.5.0
func (q QuadBezierSegment) ToCubic() BezierSegment
ToCubic converts the quadratic Bézier segment to an equivalent cubic Bézier segment using degree elevation.
The conversion formula (exact, not an approximation) is:
Q0 = P0 Q1 = P0 + (2/3) * (P1 - P0) Q2 = P2 + (2/3) * (P1 - P2) Q3 = P2
where P0, P1, P2 are the quadratic start, control, and end points and Q0..Q3 are the resulting cubic start, first control, second control, and end points.
This identity is derived from the de Casteljau algorithm: a degree-n polynomial can always be expressed exactly as a degree-(n+1) polynomial by splitting its control polygon in the ratio 2:1 from each endpoint.
Reference: Farin, "Curves and Surfaces for CAGD", §5.2 — Degree Elevation.
type Rect ¶ added in v0.2.0
type Rect struct {
X float64 // Left edge
Y float64 // Bottom edge
Width float64 // Width
Height float64 // Height
}
Rect represents a rectangle in user space.
type RectOptions ¶
type RectOptions struct {
// StrokeColor is the border color (nil = no stroke).
// If StrokeColorCMYK is set, this field is ignored.
StrokeColor *Color
// StrokeColorCMYK is the border color in CMYK (nil = no stroke).
// If set, this takes precedence over StrokeColor (RGB).
StrokeColorCMYK *ColorCMYK
// StrokeWidth is the border width in points (default: 1.0).
StrokeWidth float64
// FillColor is the fill color (nil = no fill).
// Mutually exclusive with FillGradient and FillColorCMYK.
// If FillColorCMYK is set, this field is ignored.
FillColor *Color
// FillColorCMYK is the fill color in CMYK (nil = no fill).
// If set, this takes precedence over FillColor (RGB).
// Mutually exclusive with FillGradient.
FillColorCMYK *ColorCMYK
// FillGradient is the gradient fill (nil = no gradient fill).
// Mutually exclusive with FillColor and FillColorCMYK.
FillGradient *Gradient
// Dashed enables dashed border rendering.
Dashed bool
// DashArray defines the dash pattern for the border.
// Only used when Dashed is true.
DashArray []float64
// DashPhase is the starting offset into the dash pattern.
// Only used when Dashed is true.
DashPhase float64
// Opacity is the rectangle opacity (0.0 = transparent, 1.0 = opaque).
// Optional. If set, applies transparency via ExtGState.
// Affects both fill and stroke.
// Range: [0.0, 1.0]
Opacity *float64
}
RectOptions configures rectangle drawing.
type Splitter ¶
type Splitter struct {
// contains filtered or unexported fields
}
Splitter provides functionality to split PDF files into smaller parts.
Use Splitter when you need to: - Split a PDF into individual pages (one file per page) - Split a PDF into multiple files based on page ranges - Extract specific pages into a new document
Example - Split into individual pages:
splitter, _ := creator.NewSplitter("large.pdf")
defer splitter.Close()
splitter.Split("output/") // Creates page_001.pdf, page_002.pdf, etc.
Example - Split by ranges:
splitter, _ := creator.NewSplitter("large.pdf")
defer splitter.Close()
splitter.SplitByRanges(
creator.PageRange{Start: 1, End: 5, Output: "part1.pdf"},
creator.PageRange{Start: 6, End: 10, Output: "part2.pdf"},
)
Example - Extract specific pages:
splitter, _ := creator.NewSplitter("large.pdf")
doc, _ := splitter.ExtractPages(1, 3, 5, 7)
func NewSplitter ¶
NewSplitter creates a new Splitter for the specified PDF file.
Parameters:
- path: Path to the PDF file to split
Returns an error if:
- File cannot be opened
- File is not a valid PDF
Example:
splitter, err := creator.NewSplitter("large.pdf")
if err != nil {
log.Fatal(err)
}
defer splitter.Close()
func (*Splitter) Close ¶
Close closes the splitter and releases resources.
This should be called when done with the splitter (use defer).
func (*Splitter) ExtractPages ¶
ExtractPages extracts specific pages into a new document.
This creates a new in-memory document with only the specified pages. The returned document can be modified or written to a file.
Page numbers are 1-based.
Parameters:
- pages: Page numbers to extract (1-based)
Returns an error if:
- No pages specified
- Any page number is invalid
Example:
doc, err := splitter.ExtractPages(1, 3, 5, 7)
if err != nil {
log.Fatal(err)
}
// Use document...
func (*Splitter) SetFilenamePattern ¶
SetFilenamePattern sets the output filename pattern.
The pattern must contain a single %d or %03d formatter for page number.
Default pattern: "page_%03d.pdf"
Example:
splitter.SetFilenamePattern("output_%04d.pdf")
// Produces: output_0001.pdf, output_0002.pdf, etc.
func (*Splitter) Split ¶
Split splits the PDF into individual page files.
Each page is written to a separate PDF file in the specified directory. Filenames are generated using the filename pattern (default: page_001.pdf).
Parameters:
- outputDir: Directory where individual page files will be written
Returns an error if:
- Output directory cannot be created
- Any page cannot be written
Example:
splitter.Split("output/") // Creates page_001.pdf, page_002.pdf, etc.
func (*Splitter) SplitByRanges ¶
SplitByRanges splits the PDF by page ranges.
Each range is written to the specified output file. Page numbers are 1-based and inclusive.
Parameters:
- ranges: One or more PageRange specifications
Returns an error if:
- No ranges specified
- Any range is invalid
- Any output file cannot be written
Example:
splitter.SplitByRanges(
creator.PageRange{Start: 1, End: 5, Output: "part1.pdf"},
creator.PageRange{Start: 6, End: 10, Output: "part2.pdf"},
)
func (*Splitter) SplitByRangesContext ¶
SplitByRangesContext splits by ranges with context support.
type StampAnnotation ¶
type StampAnnotation struct {
// contains filtered or unexported fields
}
StampAnnotation represents a rubber stamp annotation.
Stamp annotations display predefined stamps like "Approved", "Draft", etc.
Example:
stamp := creator.NewStampAnnotation(300, 700, 100, 50, creator.StampApproved)
stamp.SetColor(creator.Green)
stamp.SetAuthor("John Doe")
page.AddStampAnnotation(stamp)
func NewStampAnnotation ¶
func NewStampAnnotation(x, y, width, height float64, name document.StampName) *StampAnnotation
NewStampAnnotation creates a new stamp annotation.
The stamp appears at (x, y) with the specified width and height.
Parameters:
- x: Horizontal position in points (from left edge)
- y: Vertical position in points (from bottom edge)
- width: Stamp width in points
- height: Stamp height in points
- name: Stamp name (e.g., creator.StampApproved)
Example:
// Create an "Approved" stamp at (300, 700), 100x50 points stamp := creator.NewStampAnnotation(300, 700, 100, 50, creator.StampApproved) stamp.SetColor(creator.Green)
func (*StampAnnotation) SetAuthor ¶
func (a *StampAnnotation) SetAuthor(author string) *StampAnnotation
SetAuthor sets the author name.
Example:
stamp.SetAuthor("John Doe")
func (*StampAnnotation) SetColor ¶
func (a *StampAnnotation) SetColor(color Color) *StampAnnotation
SetColor sets the stamp color.
Common stamp colors:
- Red (default, for important/rejected)
- Green (approved/ok)
- Blue (informational)
- Yellow (warning)
Example:
stamp.SetColor(creator.Green) // Approved
func (*StampAnnotation) SetNote ¶
func (a *StampAnnotation) SetNote(note string) *StampAnnotation
SetNote sets an optional note text.
This text appears when the user hovers over or clicks the stamp.
Example:
stamp.SetNote("Approved on 2025-01-06")
type StrikeOutAnnotation ¶
type StrikeOutAnnotation struct {
// contains filtered or unexported fields
}
StrikeOutAnnotation represents a strikeout markup annotation.
StrikeOut annotations draw a line through text.
Example:
strikeout := creator.NewStrikeOutAnnotation(100, 650, 300, 670) strikeout.SetColor(creator.Red) page.AddStrikeOutAnnotation(strikeout)
func NewStrikeOutAnnotation ¶
func NewStrikeOutAnnotation(x1, y1, x2, y2 float64) *StrikeOutAnnotation
NewStrikeOutAnnotation creates a new strikeout annotation.
The strikeout line is drawn through the rectangular area from (x1, y1) to (x2, y2).
Parameters:
- x1: Left X coordinate (from left edge)
- y1: Bottom Y coordinate (from bottom edge)
- x2: Right X coordinate (from left edge)
- y2: Top Y coordinate (from bottom edge)
Example:
strikeout := creator.NewStrikeOutAnnotation(100, 650, 300, 670) strikeout.SetColor(creator.Red)
func (*StrikeOutAnnotation) SetAuthor ¶
func (a *StrikeOutAnnotation) SetAuthor(author string) *StrikeOutAnnotation
SetAuthor sets the author name.
Example:
strikeout.SetAuthor("John Doe")
func (*StrikeOutAnnotation) SetColor ¶
func (a *StrikeOutAnnotation) SetColor(color Color) *StrikeOutAnnotation
SetColor sets the strikeout color.
Example:
strikeout.SetColor(creator.Red)
func (*StrikeOutAnnotation) SetNote ¶
func (a *StrikeOutAnnotation) SetNote(note string) *StrikeOutAnnotation
SetNote sets an optional note text.
Example:
strikeout.SetNote("Obsolete")
type Stroke ¶ added in v0.2.0
type Stroke struct {
// Paint is the paint source (Color, ColorRGBA, ColorCMYK, or Gradient).
Paint Paint
// Width is the line width in user space units.
// Default: 1.0
Width float64
// LineCap defines how line ends are rendered.
// Default: LineCapButt
LineCap LineCap
// LineJoin defines how corners are rendered.
// Default: LineJoinMiter
LineJoin LineJoin
// MiterLimit is the maximum miter length for LineJoinMiter.
// When miter length exceeds this, a bevel join is used instead.
// Default: 10.0
MiterLimit float64
// DashArray defines the dash pattern.
// Alternating on/off lengths: [on1, off1, on2, off2, ...]
// Empty array = solid line (no dashing).
DashArray []float64
// DashPhase is the offset into the dash pattern.
// Default: 0
DashPhase float64
}
Stroke represents stroke configuration for shapes.
Stroke controls how shape outlines are drawn with paint (color or gradient). It includes the paint source, line width, cap style, join style, and dash pattern.
Example:
// Solid color stroke
stroke := &Stroke{
Paint: Black,
Width: 2.0,
LineCap: LineCapRound,
LineJoin: LineJoinMiter,
MiterLimit: 10.0,
}
// Dashed stroke
stroke := &Stroke{
Paint: Black,
Width: 1.0,
DashArray: []float64{5, 3},
DashPhase: 0,
}
func NewStroke ¶ added in v0.2.0
NewStroke creates a new Stroke with the specified paint.
Default values:
- Width: 1.0
- LineCap: LineCapButt
- LineJoin: LineJoinMiter
- MiterLimit: 10.0
- DashArray: nil (solid line)
- DashPhase: 0
Parameters:
- paint: Paint source (Color, ColorRGBA, ColorCMYK, or Gradient)
Example:
stroke := NewStroke(Black) stroke := NewStroke(NewLinearGradient(0, 0, 100, 0))
func (*Stroke) Validate ¶ added in v0.2.0
Validate validates the stroke configuration.
Checks:
- Paint is not nil
- Width is positive
- MiterLimit is >= 1.0
- DashArray values are all positive
- If paint is a Gradient, validate gradient
Returns an error if validation fails.
func (*Stroke) WithDash ¶ added in v0.2.0
WithDash returns a new Stroke with the specified dash pattern.
Parameters:
- dashArray: Alternating on/off lengths
- dashPhase: Offset into the dash pattern
Example:
// Dash: 5 on, 3 off
stroke := NewStroke(Black).WithDash([]float64{5, 3}, 0)
// Dash: 10 on, 5 off, 2 on, 5 off
stroke := NewStroke(Black).WithDash([]float64{10, 5, 2, 5}, 0)
func (*Stroke) WithLineCap ¶ added in v0.2.0
WithLineCap returns a new Stroke with the specified line cap style.
Parameters:
- cap: Line cap style (LineCapButt, LineCapRound, LineCapSquare)
Example:
stroke := NewStroke(Black).WithLineCap(LineCapRound)
func (*Stroke) WithLineJoin ¶ added in v0.2.0
WithLineJoin returns a new Stroke with the specified line join style.
Parameters:
- join: Line join style (LineJoinMiter, LineJoinRound, LineJoinBevel)
Example:
stroke := NewStroke(Black).WithLineJoin(LineJoinRound)
func (*Stroke) WithMiterLimit ¶ added in v0.2.0
WithMiterLimit returns a new Stroke with the specified miter limit.
Parameters:
- limit: Maximum miter length (must be >= 1.0)
Example:
stroke := NewStroke(Black).WithMiterLimit(5.0)
type StyledParagraph ¶
type StyledParagraph struct {
// contains filtered or unexported fields
}
StyledParagraph is a paragraph with multiple text styles.
Unlike a simple Paragraph that has one style for all text, StyledParagraph allows mixing different fonts, sizes, and colors within the same paragraph while maintaining proper text wrapping and alignment.
Example:
sp := NewStyledParagraph()
sp.Append("This is ")
sp.AppendStyled("bold", TextStyle{Font: HelveticaBold, Size: 12, Color: Black})
sp.Append(" and this is ")
sp.AppendStyled("red", TextStyle{Font: Helvetica, Size: 12, Color: Red})
sp.Append(" text.")
sp.SetAlignment(AlignJustify)
page.Draw(sp)
func NewStyledParagraph ¶
func NewStyledParagraph() *StyledParagraph
NewStyledParagraph creates a new styled paragraph.
Default settings:
- Alignment: Left
- Line spacing: 1.2 (120%)
- No text chunks initially
func (*StyledParagraph) Append ¶
func (sp *StyledParagraph) Append(text string) *StyledParagraph
Append adds text using the default style. Returns the paragraph for method chaining.
func (*StyledParagraph) AppendStyled ¶
func (sp *StyledParagraph) AppendStyled(text string, style TextStyle) *StyledParagraph
AppendStyled adds text with a specific style. Returns the paragraph for method chaining.
func (*StyledParagraph) Draw ¶
func (sp *StyledParagraph) Draw(ctx *LayoutContext, page *Page) error
Draw renders the styled paragraph on the page at the current cursor position.
func (*StyledParagraph) Height ¶
func (sp *StyledParagraph) Height(ctx *LayoutContext) float64
Height calculates the total height of the styled paragraph when rendered.
func (*StyledParagraph) SetAlignment ¶
func (sp *StyledParagraph) SetAlignment(a Alignment) *StyledParagraph
SetAlignment sets the text alignment. Returns the paragraph for method chaining.
func (*StyledParagraph) SetLineSpacing ¶
func (sp *StyledParagraph) SetLineSpacing(spacing float64) *StyledParagraph
SetLineSpacing sets the line spacing multiplier. 1.0 = single spacing, 1.5 = 150% spacing, 2.0 = double spacing. Returns the paragraph for method chaining.
type Surface ¶ added in v0.2.0
type Surface struct {
// contains filtered or unexported fields
}
Surface represents a drawing surface with a graphics state stack.
Surface provides Skia-like Push/Pop semantics for graphics state management. This allows composable transformations, opacity, blend modes, and clipping.
Example:
surface := page.Surface() // Draw with transform and opacity surface.PushTransform(Rotate(45)) surface.PushOpacity(0.5) surface.DrawRect(rect) surface.Pop() // Restore opacity surface.Pop() // Restore transform
func NewSurface ¶ added in v0.2.0
NewSurface creates a new drawing surface for a page.
The surface starts with an empty state stack and default graphics state.
func (*Surface) CurrentBlendMode ¶ added in v0.2.0
CurrentBlendMode returns the current blend mode.
func (*Surface) CurrentClipPath ¶ added in v0.2.0
CurrentClipPath returns the current clipping path (nil if no clipping).
func (*Surface) CurrentFill ¶ added in v0.2.0
CurrentFill returns the current fill configuration.
func (*Surface) CurrentOpacity ¶ added in v0.2.0
CurrentOpacity returns the current opacity value.
func (*Surface) CurrentStroke ¶ added in v0.2.0
CurrentStroke returns the current stroke configuration.
func (*Surface) CurrentTransform ¶ added in v0.2.0
CurrentTransform returns the current transformation matrix.
func (*Surface) DrawPath ¶ added in v0.2.0
DrawPath draws a path with the current fill and stroke.
The path is drawn using the current graphics state. If both fill and stroke are set, the path is filled then stroked (B operator). If only fill is set, the path is filled (f operator). If only stroke is set, the path is stroked (S operator). If neither is set, no drawing occurs (but path is constructed).
Parameters:
- path: Path to draw
Example:
path := NewPath() path.MoveTo(0, 0) path.LineTo(100, 0) path.LineTo(50, 100) path.Close() surface.SetFill(NewFill(Red)) surface.SetStroke(NewStroke(Black).WithWidth(2)) surface.DrawPath(path)
func (*Surface) DrawRect ¶ added in v0.2.0
DrawRect draws a rectangle with the current fill and stroke.
The rectangle is drawn using the current graphics state. If both fill and stroke are set, the rectangle is filled then stroked.
Parameters:
- rect: Rectangle to draw
Example:
surface.SetFill(NewFill(Red))
surface.SetStroke(NewStroke(Black).WithWidth(2))
surface.DrawRect(Rect{X: 50, Y: 50, Width: 100, Height: 100})
func (*Surface) FillPath ¶ added in v0.2.0
FillPath fills a path using the current fill configuration.
The path is filled using the current fill color/gradient and fill rule. Stroke configuration is ignored (even if set).
PDF operators: f (NonZero) or f* (EvenOdd)
Parameters:
- path: Path to fill
Example:
path := NewPath().
AddCircle(Point{150, 150}, 50)
surface.SetFill(NewFill(Red))
surface.FillPath(path)
func (*Surface) Pop ¶ added in v0.2.0
func (s *Surface) Pop()
Pop restores the previous graphics state.
Each Pop must match a previous Push* call. Panics if Pop is called more times than Push.
Example:
surface.PushOpacity(0.5) surface.DrawRect(rect) surface.Pop() // OK surface.Pop() // PANIC: no matching Push
func (*Surface) PushBlendMode ¶ added in v0.2.0
PushBlendMode saves the current state and applies a blend mode.
The blend mode controls how colors blend with the background. Call Pop() to restore the previous blend mode.
Example:
surface.PushBlendMode(BlendModeMultiply) surface.DrawRect(rect) surface.Pop()
func (*Surface) PushClipCircle ¶ added in v0.2.0
PushClipCircle saves the current state and clips to a circle.
This is a convenience method equivalent to:
path := NewPath().AddCircle(center, radius) surface.PushClipPath(path, FillRuleNonZero)
Parameters:
- center: Circle center point
- radius: Circle radius (must be positive)
Example:
surface.PushClipCircle(Point{150, 150}, 50)
surface.DrawRect(Rect{X: 100, Y: 100, Width: 100, Height: 100}) // Circle-clipped
surface.Pop()
func (*Surface) PushClipEllipse ¶ added in v0.2.0
PushClipEllipse saves the current state and clips to an ellipse.
The ellipse is inscribed in the specified rectangle.
Parameters:
- rect: Bounding rectangle of the ellipse
Example:
surface.PushClipEllipse(Rect{X: 50, Y: 50, Width: 200, Height: 100})
surface.DrawRect(Rect{X: 0, Y: 0, Width: 300, Height: 200}) // Ellipse-clipped
surface.Pop()
func (*Surface) PushClipPath ¶ added in v0.2.0
PushClipPath saves the current state and applies a clipping path.
All subsequent drawing is clipped to the path. The fill rule determines which areas are "inside" the path:
- FillRuleNonZero: Non-zero winding rule (default)
- FillRuleEvenOdd: Even-odd rule
Clipping paths are intersected with any existing clip path. Call Pop() to restore the previous clipping state.
PDF operators:
- W (clip with NonZero rule)
- W* (clip with EvenOdd rule)
- n (end path without painting)
Example:
path := NewPath() path.MoveTo(0, 0) path.LineTo(100, 0) path.LineTo(100, 100) path.Close() surface.PushClipPath(path, FillRuleNonZero) surface.DrawRect(rect) // Clipped to triangle surface.Pop()
Reference: PDF 1.7 Specification, Section 8.5.4 (Clipping Path).
func (*Surface) PushClipRect ¶ added in v0.2.0
PushClipRect saves the current state and clips to a rectangle.
This is a convenience method equivalent to:
path := NewPath().AddRect(rect) surface.PushClipPath(path, FillRuleNonZero)
Parameters:
- rect: Rectangle to clip to
Example:
surface.PushClipRect(Rect{X: 10, Y: 10, Width: 100, Height: 100})
surface.DrawRect(Rect{X: 0, Y: 0, Width: 200, Height: 200}) // Only 10-110 visible
surface.Pop()
func (*Surface) PushOpacity ¶ added in v0.2.0
PushOpacity saves the current state and applies an opacity.
The opacity is multiplicative with the current opacity. Call Pop() to restore the previous opacity.
Example:
surface.PushOpacity(0.5) surface.PushOpacity(0.5) // Combined opacity = 0.25 surface.DrawRect(rect) surface.Pop() // opacity = 0.5 surface.Pop() // opacity = 1.0
func (*Surface) PushTransform ¶ added in v0.2.0
PushTransform saves the current state and applies a transformation.
The transformation is applied to all subsequent drawing operations. Call Pop() to restore the previous state.
Example:
surface.PushTransform(Rotate(45)) surface.DrawRect(rect) // Drawn rotated surface.Pop() // Restore rotation
func (*Surface) SetFill ¶ added in v0.2.0
SetFill sets the current fill configuration.
All subsequent drawing operations will use this fill. Pass nil to disable filling.
Example:
fill := NewFill(Red).WithOpacity(0.8) surface.SetFill(fill) surface.DrawRect(rect) // Filled with red at 80% opacity
func (*Surface) SetStroke ¶ added in v0.2.0
SetStroke sets the current stroke configuration.
All subsequent drawing operations will use this stroke. Pass nil to disable stroking.
Example:
stroke := NewStroke(Black).WithWidth(2.0) surface.SetStroke(stroke) surface.DrawRect(rect) // Stroked with black 2pt line
func (*Surface) StackDepth ¶ added in v0.2.0
StackDepth returns the number of saved states on the stack.
This is useful for debugging and ensuring Push/Pop are balanced.
func (*Surface) StrokePath ¶ added in v0.2.0
StrokePath strokes a path using the current stroke configuration.
The path is stroked using the current stroke color/gradient, line width, cap style, join style, and dash pattern. Fill configuration is ignored (even if set).
PDF operator: S
Parameters:
- path: Path to stroke
Example:
path := NewPath().
MoveTo(50, 50).
LineTo(150, 50).
LineTo(100, 150).
Close()
stroke := NewStroke(Black).
WithWidth(3.0).
WithLineCap(LineCapRound).
WithLineJoin(LineJoinRound)
surface.SetStroke(stroke)
surface.StrokePath(path)
type TOC ¶
type TOC struct {
// contains filtered or unexported fields
}
TOC represents a Table of Contents for the document.
The TOC is automatically generated from document chapters and includes clickable links to each chapter/section.
Example:
c := creator.New()
c.EnableTOC()
// Add chapters...
c.WriteToFile("document.pdf") // TOC is automatically generated
func NewTOC ¶
func NewTOC() *TOC
NewTOC creates a new Table of Contents.
The TOC will be populated with chapters when the document is rendered.
Example:
toc := NewTOC()
toc.SetTitle("Contents")
func (*TOC) Draw ¶
func (t *TOC) Draw(ctx *LayoutContext, page *Page) error
Draw renders the Table of Contents.
func (*TOC) GetEntries ¶
GetEntries returns all TOC entries in document order.
This is useful for custom TOC rendering or testing.
func (*TOC) Height ¶
func (t *TOC) Height(ctx *LayoutContext) float64
Height calculates the total height needed for the TOC.
func (*TOC) SetLeader ¶
SetLeader sets the leader character (default: ".").
Example:
toc.SetLeader(".") // Introduction .............. 1
toc.SetLeader("-") // Introduction ------------- 1
func (*TOC) SetShowPageNumbers ¶
SetShowPageNumbers enables/disables page number display.
func (*TOC) ShowPageNumbers ¶
ShowPageNumbers returns whether page numbers are displayed.
type TOCEntry ¶
type TOCEntry struct {
// Title of the chapter/section
Title string
// Number of the chapter (e.g., "1.2.3")
Number string
// Level of nesting (0 = top-level)
Level int
// PageIndex where the chapter starts (0-based)
PageIndex int
}
TOCEntry represents a single entry in the Table of Contents.
This is used internally for rendering and testing.
type TOCStyle ¶
type TOCStyle struct {
// TitleFont for the "Table of Contents" heading
TitleFont FontName
// TitleSize for the heading
TitleSize float64
// TitleColor for the heading
TitleColor Color
// EntryFont for TOC entries
EntryFont FontName
// EntrySize for TOC entries (base size, reduced for sub-levels)
EntrySize float64
// EntryColor for TOC entries
EntryColor Color
// IndentPerLevel is the indentation in points for each sub-level
IndentPerLevel float64
// LineSpacing between TOC entries
LineSpacing float64
// SpaceAfterTitle is the space after the TOC heading
SpaceAfterTitle float64
// LeaderFont for the leader dots (...)
LeaderFont FontName
// LeaderSize for the leader dots
LeaderSize float64
// LeaderColor for the leader dots
LeaderColor Color
}
TOCStyle defines the visual style for the Table of Contents.
func DefaultTOCStyle ¶
func DefaultTOCStyle() TOCStyle
DefaultTOCStyle returns the default TOC style.
Default style:
- TitleFont: HelveticaBold, 24pt, Black
- EntryFont: Helvetica, 12pt, Black
- IndentPerLevel: 20pt
- LineSpacing: 1.5
- SpaceAfterTitle: 20pt
- LeaderFont: Helvetica, 12pt, Gray
type TableCell ¶
type TableCell struct {
// Content is the text content of the cell.
Content string
// Font is the font for the cell content.
Font FontName
// FontSize is the font size in points.
FontSize float64
// Color is the text color.
Color Color
// Align is the horizontal alignment within the cell.
Align Alignment
// ColSpan is the number of columns this cell spans (future use).
ColSpan int
}
TableCell represents a cell in a table.
func NewTableCell ¶
NewTableCell creates a new table cell with text content and default styling.
type TableLayout ¶
type TableLayout struct {
// contains filtered or unexported fields
}
TableLayout represents a table that can be drawn on a page.
Tables support automatic column width calculation, borders, and header rows with bold styling.
Example:
table := NewTableLayout(3)
table.SetBorder(0.5, Black)
table.AddHeaderRow("Name", "Age", "City")
table.AddRow("Alice", "30", "New York")
table.AddRow("Bob", "25", "Los Angeles")
page.Draw(table)
func NewTableLayout ¶
func NewTableLayout(columns int) *TableLayout
NewTableLayout creates a new table with the specified number of columns.
func (*TableLayout) AddHeaderRow ¶
func (t *TableLayout) AddHeaderRow(cells ...string) *TableLayout
AddHeaderRow adds a header row with the given cell texts. Header rows use bold font by default. Returns the table for method chaining.
func (*TableLayout) AddRow ¶
func (t *TableLayout) AddRow(cells ...string) *TableLayout
AddRow adds a row with the given cell texts using default styling. Returns the table for method chaining.
func (*TableLayout) AddRowCells ¶
func (t *TableLayout) AddRowCells(cells ...TableCell) *TableLayout
AddRowCells adds a row with fully-configured cells. Returns the table for method chaining.
func (*TableLayout) ColumnCount ¶
func (t *TableLayout) ColumnCount() int
ColumnCount returns the number of columns.
func (*TableLayout) Draw ¶
func (t *TableLayout) Draw(ctx *LayoutContext, page *Page) error
Draw renders the table on the page at the current cursor position.
func (*TableLayout) HeaderRowCount ¶
func (t *TableLayout) HeaderRowCount() int
HeaderRowCount returns the number of header rows.
func (*TableLayout) Height ¶
func (t *TableLayout) Height(_ *LayoutContext) float64
Height calculates the total height of the table when rendered.
func (*TableLayout) RowCount ¶
func (t *TableLayout) RowCount() int
RowCount returns the number of rows (including header rows).
func (*TableLayout) SetBorder ¶
func (t *TableLayout) SetBorder(width float64, color Color) *TableLayout
SetBorder enables table borders with the specified width and color. Returns the table for method chaining.
func (*TableLayout) SetCellPadding ¶
func (t *TableLayout) SetCellPadding(padding float64) *TableLayout
SetCellPadding sets the padding inside cells. Returns the table for method chaining.
func (*TableLayout) SetColumnWidths ¶
func (t *TableLayout) SetColumnWidths(widths ...float64) *TableLayout
SetColumnWidths sets explicit widths for each column. If not all widths are provided, remaining columns use auto width. Returns the table for method chaining.
type TextAnnotation ¶
type TextAnnotation struct {
// contains filtered or unexported fields
}
TextAnnotation represents a sticky note annotation in the Creator API.
Text annotations appear as icons (sticky notes) on PDF pages. When clicked, they display pop-up text.
Example:
note := creator.NewTextAnnotation(100, 700, "This is a comment")
note.SetAuthor("John Doe")
note.SetColor(creator.Yellow)
note.SetOpen(true)
page.AddTextAnnotation(note)
func NewTextAnnotation ¶
func NewTextAnnotation(x, y float64, contents string) *TextAnnotation
NewTextAnnotation creates a new text annotation (sticky note).
The annotation appears as a small icon (typically 20x20 points) at (x, y). When clicked, it displays the contents text in a pop-up.
Parameters:
- x: Horizontal position in points (from left edge)
- y: Vertical position in points (from bottom edge)
- contents: Text to display in the pop-up
Example:
note := creator.NewTextAnnotation(100, 700, "Review this section")
note.SetAuthor("Alice")
note.SetColor(creator.Yellow)
func (*TextAnnotation) SetAuthor ¶
func (a *TextAnnotation) SetAuthor(author string) *TextAnnotation
SetAuthor sets the author name for the annotation.
This appears in the annotation properties and can be used to track who added the comment.
Example:
note.SetAuthor("John Doe")
func (*TextAnnotation) SetColor ¶
func (a *TextAnnotation) SetColor(color Color) *TextAnnotation
SetColor sets the annotation color.
Common colors for sticky notes:
- Yellow (default)
- Red (important)
- Green (ok/approved)
- Blue (informational)
Example:
note.SetColor(creator.Red) // Mark as important
func (*TextAnnotation) SetOpen ¶
func (a *TextAnnotation) SetOpen(open bool) *TextAnnotation
SetOpen sets whether the pop-up should be open by default.
If true, the pop-up is visible when the PDF is opened. If false, the user must click the icon to see the text.
Example:
note.SetOpen(true) // Show immediately
type TextChunk ¶
type TextChunk struct {
// Text is the text content.
Text string
// Style is the styling to apply to this chunk.
Style TextStyle
}
TextChunk represents a piece of text with specific styling.
TextChunks are combined to create a StyledParagraph with multiple text styles within the same paragraph.
Example:
chunk := TextChunk{
Text: "Hello World",
Style: DefaultTextStyle(),
}
type TextOperation ¶
type TextOperation struct {
// Text is the string to display.
Text string
// X is the horizontal position in points (from left edge of page).
X float64
// Y is the vertical position in points (from bottom edge of page).
Y float64
// Font is the font to use (one of the Standard 14 fonts).
// Ignored if CustomFont is set.
Font FontName
// CustomFont is an embedded TrueType/OpenType font (optional).
// When set, this takes precedence over Font field.
// Use for Unicode text (Cyrillic, CJK, symbols, etc.).
CustomFont *CustomFont
// Size is the font size in points.
Size float64
// Color is the text color (RGB, 0.0 to 1.0 range).
// If ColorCMYK is set, this field is ignored.
Color Color
// ColorCMYK is the text color in CMYK color space (optional).
// If set, this takes precedence over Color (RGB).
// Used for professional printing workflows.
ColorCMYK *ColorCMYK
// Opacity is the text opacity (0.0 = transparent, 1.0 = opaque).
// Optional. If set, applies transparency via ExtGState.
// Works with both Color and ColorCMYK.
// Range: [0.0, 1.0]
Opacity *float64
// Rotation is the text rotation in degrees, counter-clockwise.
// The rotation pivot is the text origin point (X, Y).
// Zero means no rotation (default horizontal text).
// Positive values rotate counter-clockwise; negative values rotate clockwise.
//
// Example: 90 degrees rotates text to read bottom-to-top.
Rotation float64
}
TextOperation represents a text drawing operation to be added to a page.
Each TextOperation describes how to render a single text string at a specific position with a specific font, size, and color.
Example:
op := TextOperation{
Text: "Hello World",
X: 100,
Y: 700,
Font: Helvetica,
Size: 24,
Color: Black,
}
type TextStyle ¶
type TextStyle struct {
// Font is the font to use (one of the Standard 14 fonts).
Font FontName
// Size is the font size in points.
Size float64
// Color is the text color (RGB, 0.0 to 1.0 range).
Color Color
}
TextStyle defines styling for a text chunk.
TextStyle combines font, size, and color into a single style definition that can be applied to text chunks in a StyledParagraph.
Example:
boldRed := TextStyle{
Font: HelveticaBold,
Size: 14,
Color: Red,
}
func DefaultTextStyle ¶
func DefaultTextStyle() TextStyle
DefaultTextStyle returns the default text style.
Default style:
- Font: Helvetica
- Size: 12pt
- Color: Black
type TextWatermark ¶
type TextWatermark struct {
// contains filtered or unexported fields
}
TextWatermark represents a text watermark to be applied to PDF pages.
A watermark is semi-transparent text (typically "CONFIDENTIAL", "DRAFT", etc.) rendered on a page, often rotated diagonally.
Example:
wm := creator.NewTextWatermark("CONFIDENTIAL")
wm.SetFont(creator.HelveticaBold, 72)
wm.SetColor(creator.Gray)
wm.SetOpacity(0.3)
wm.SetRotation(45)
page.DrawWatermark(wm)
func NewTextWatermark ¶
func NewTextWatermark(text string) *TextWatermark
NewTextWatermark creates a new text watermark with default settings.
Default settings:
- Font: HelveticaBold
- Font size: 48 points
- Color: Gray (0.5, 0.5, 0.5)
- Opacity: 0.5 (50% transparent)
- Rotation: 45 degrees (diagonal)
- Position: Center
Example:
wm := creator.NewTextWatermark("DRAFT")
func (*TextWatermark) Color ¶
func (w *TextWatermark) Color() Color
Color returns the watermark color.
func (*TextWatermark) Font ¶
func (w *TextWatermark) Font() FontName
Font returns the watermark font.
func (*TextWatermark) FontSize ¶
func (w *TextWatermark) FontSize() float64
FontSize returns the watermark font size.
func (*TextWatermark) Opacity ¶
func (w *TextWatermark) Opacity() float64
Opacity returns the watermark opacity.
func (*TextWatermark) Position ¶
func (w *TextWatermark) Position() WatermarkPosition
Position returns the watermark position.
func (*TextWatermark) Rotation ¶
func (w *TextWatermark) Rotation() float64
Rotation returns the watermark rotation in degrees.
func (*TextWatermark) SetColor ¶
func (w *TextWatermark) SetColor(color Color) error
SetColor sets the watermark text color.
Color components must be in the range [0.0, 1.0].
Example:
wm.SetColor(creator.Red)
wm.SetColor(creator.Color{R: 0.8, G: 0.0, B: 0.0})
func (*TextWatermark) SetFont ¶
func (w *TextWatermark) SetFont(font FontName, size float64) error
SetFont sets the watermark font and size.
Parameters:
- font: Font name (one of the Standard 14 fonts)
- size: Font size in points (must be > 0)
Example:
wm.SetFont(creator.HelveticaBold, 72)
func (*TextWatermark) SetOpacity ¶
func (w *TextWatermark) SetOpacity(opacity float64) error
SetOpacity sets the watermark transparency.
Opacity must be in the range [0.0, 1.0]:
- 0.0 = fully transparent (invisible)
- 1.0 = fully opaque (no transparency)
- 0.3-0.5 = typical watermark range
Example:
wm.SetOpacity(0.3) // 30% opaque, 70% transparent
func (*TextWatermark) SetPosition ¶
func (w *TextWatermark) SetPosition(position WatermarkPosition) error
SetPosition sets the watermark position on the page.
Example:
wm.SetPosition(creator.WatermarkCenter) wm.SetPosition(creator.WatermarkTopRight)
func (*TextWatermark) SetRotation ¶
func (w *TextWatermark) SetRotation(degrees float64) error
SetRotation sets the watermark rotation angle in degrees (clockwise).
Common values:
- 0 = horizontal
- 45 = diagonal (typical for "CONFIDENTIAL")
- 90 = vertical
Example:
wm.SetRotation(45) // Diagonal
type Transform ¶ added in v0.2.0
type Transform struct {
A, B, C, D, E, F float64
}
Transform represents a 2D affine transformation matrix.
PDF uses column-major matrix notation:
[ a b 0 ] [ c d 0 ] [ e f 1 ]
Where:
a, d: Scale b, c: Skew/Rotation e, f: Translation
func Identity ¶ added in v0.2.0
func Identity() Transform
Identity returns the identity transformation (no change).
func Rotate ¶ added in v0.2.0
Rotate returns a rotation transformation.
The angle is in degrees, clockwise.
Example:
t := Rotate(45) // Rotate 45° clockwise t := Rotate(-90) // Rotate 90° counter-clockwise
func RotateAround ¶ added in v0.2.0
RotateAround returns a rotation transformation around a specific point.
Example:
t := RotateAround(45, 100, 200) // Rotate 45° around point (100, 200)
func Scale ¶ added in v0.2.0
Scale returns a scaling transformation.
Example:
t := Scale(2, 2) // Double size t := Scale(1, -1) // Flip vertically
func Skew ¶ added in v0.2.0
Skew returns a skew transformation.
Example:
t := Skew(15, 0) // Skew horizontally by 15°
func Translate ¶ added in v0.2.0
Translate returns a translation transformation.
Example:
t := Translate(100, 200) // Move right 100, up 200
func (Transform) Then ¶ added in v0.2.0
Then combines this transformation with another.
The result is equivalent to applying this transform first, then the other.
Example:
t := Translate(100, 0).Then(Rotate(45)) // Move, then rotate
func (Transform) ToPDFMatrix ¶ added in v0.2.0
ToPDFMatrix returns the transformation as a PDF CTM (Current Transformation Matrix).
Returns 6 values: [a b c d e f]
type UnderlineAnnotation ¶
type UnderlineAnnotation struct {
// contains filtered or unexported fields
}
UnderlineAnnotation represents an underline markup annotation.
Underline annotations draw a line under text.
Example:
underline := creator.NewUnderlineAnnotation(100, 650, 300, 670) underline.SetColor(creator.Blue) page.AddUnderlineAnnotation(underline)
func NewUnderlineAnnotation ¶
func NewUnderlineAnnotation(x1, y1, x2, y2 float64) *UnderlineAnnotation
NewUnderlineAnnotation creates a new underline annotation.
The underline is drawn under the rectangular area from (x1, y1) to (x2, y2).
Parameters:
- x1: Left X coordinate (from left edge)
- y1: Bottom Y coordinate (from bottom edge)
- x2: Right X coordinate (from left edge)
- y2: Top Y coordinate (from bottom edge)
Example:
underline := creator.NewUnderlineAnnotation(100, 650, 300, 670) underline.SetColor(creator.Blue)
func (*UnderlineAnnotation) SetAuthor ¶
func (a *UnderlineAnnotation) SetAuthor(author string) *UnderlineAnnotation
SetAuthor sets the author name.
Example:
underline.SetAuthor("John Doe")
func (*UnderlineAnnotation) SetColor ¶
func (a *UnderlineAnnotation) SetColor(color Color) *UnderlineAnnotation
SetColor sets the underline color.
Example:
underline.SetColor(creator.Blue)
func (*UnderlineAnnotation) SetNote ¶
func (a *UnderlineAnnotation) SetNote(note string) *UnderlineAnnotation
SetNote sets an optional note text.
Example:
underline.SetNote("Check this")
type WatermarkPosition ¶
type WatermarkPosition int
WatermarkPosition defines the position of a watermark on a page.
const ( // WatermarkCenter positions the watermark at the page center. WatermarkCenter WatermarkPosition = iota // WatermarkTopLeft positions the watermark at the top-left corner. WatermarkTopLeft // WatermarkTopRight positions the watermark at the top-right corner. WatermarkTopRight // WatermarkBottomLeft positions the watermark at the bottom-left corner. WatermarkBottomLeft // WatermarkBottomRight positions the watermark at the bottom-right corner. WatermarkBottomRight )
Source Files
¶
- annotation.go
- appender.go
- bezier.go
- block.go
- bookmarks.go
- chapter.go
- creator.go
- custom_font.go
- division.go
- ellipse.go
- encryption.go
- fill.go
- forms_convert.go
- gradient.go
- graphics.go
- graphics_state.go
- header_footer.go
- highlight.go
- image.go
- layout.go
- link.go
- list.go
- merger.go
- page.go
- page_size.go
- paint.go
- paragraph.go
- path.go
- polygon.go
- polyline.go
- splitter.go
- stamp.go
- stroke.go
- styled_paragraph.go
- surface.go
- table_layout.go
- text.go
- text_style.go
- toc.go
- transform.go
- watermark.go