creator

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 7, 2026 License: MIT Imports: 22 Imported by: 0

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 := c.NewPage(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

Examples

Constants

View Source
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.

View Source
const (
	// DefaultHeaderHeight is the default height for headers (50 points).
	DefaultHeaderHeight = 50.0

	// DefaultFooterHeight is the default height for footers (30 points).
	DefaultFooterHeight = 30.0
)

Default header and footer heights in points.

View Source
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

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
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.

Functions

func Merge

func Merge(output string, inputs ...string) error

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

func MergeDocuments(output string, docs ...*document.Document) error

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)

Types

type Alignment

type Alignment int

Alignment represents text alignment within a block.

const (
	// AlignLeft aligns text to the left edge.
	AlignLeft Alignment = iota

	// AlignCenter centers text horizontally.
	AlignCenter

	// AlignRight aligns text to the right edge.
	AlignRight

	// AlignJustify stretches text to fill the full width.
	AlignJustify
)

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

func NewAppender(path string) (*Appender, error)

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

func (a *Appender) AddPage(size PageSize) (*Page, error)

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) Close

func (a *Appender) Close() error

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

func (a *Appender) Document() *document.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) GetPage

func (a *Appender) GetPage(index int) (*Page, error)

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

func (a *Appender) GetParserReader() *parser.Reader

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) PageCount

func (a *Appender) PageCount() int

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) SetKeywords

func (a *Appender) SetKeywords(keywords ...string)

SetKeywords sets document keywords for search/indexing.

Example:

app.SetKeywords("modified", "watermarked", "confidential")

func (*Appender) SetMetadata

func (a *Appender) SetMetadata(title, author, subject string)

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

func (a *Appender) WriteToFile(path string) error

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

func (a *Appender) WriteToFileContext(ctx context.Context, path string) error

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
}

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 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

func NewBlock(width, height float64) *Block

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) Clear

func (b *Block) Clear()

Clear removes all drawables from the block.

func (*Block) ContentHeight

func (b *Block) ContentHeight() float64

ContentHeight returns the usable height inside the block (height minus margins).

func (*Block) ContentWidth

func (b *Block) ContentWidth() float64

ContentWidth returns the usable width inside the block (width minus margins).

func (*Block) Draw

func (b *Block) Draw(d Drawable) error

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

func (b *Block) DrawAt(d Drawable, x, y float64) error

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) Height

func (b *Block) Height() float64

Height returns the block height in points.

func (*Block) Margins

func (b *Block) Margins() Margins

Margins returns the block margins.

func (*Block) MoveCursor

func (b *Block) MoveCursor(dx, dy float64)

MoveCursor moves the current drawing position by the specified delta.

func (*Block) SetCursor

func (b *Block) SetCursor(x, y float64)

SetCursor sets the current drawing position within the block.

This affects subsequent Draw() calls.

func (*Block) SetHeight

func (b *Block) SetHeight(height float64)

SetHeight sets the block height in points.

func (*Block) SetMargins

func (b *Block) SetMargins(m Margins)

SetMargins sets the block margins.

Margins define the padding inside the block, reducing the available drawing area.

func (*Block) SetWidth

func (b *Block) SetWidth(width float64)

SetWidth sets the block width in points.

func (*Block) Width

func (b *Block) Width() float64

Width returns the block width in points.

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

func NewChapter(title string) *Chapter

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

func (c *Chapter) Add(d Drawable) error

Add adds a content element (paragraph, table, etc.) to the chapter.

Example:

ch.Add(NewParagraph("This is the introduction..."))
ch.Add(NewTable())

func (*Chapter) Content

func (c *Chapter) Content() []Drawable

Content returns all content elements in the chapter.

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

func (c *Chapter) FullTitle() string

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

func (c *Chapter) GetAllChapters() []*Chapter

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

func (c *Chapter) Level() int

Level returns the nesting level of the chapter.

Top-level chapters return 0, sub-chapters return 1, etc.

func (*Chapter) NewSubChapter

func (c *Chapter) NewSubChapter(title string) *Chapter

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

func (c *Chapter) Number() []int

Number returns the chapter number components.

For example, section 1.2.3 returns []int{1, 2, 3}.

func (*Chapter) NumberString

func (c *Chapter) NumberString() string

NumberString returns the formatted chapter number.

For example: "1", "1.2", "1.2.3".

func (*Chapter) PageIndex

func (c *Chapter) PageIndex() int

PageIndex returns the page index where the chapter starts.

Returns -1 if not yet rendered.

func (*Chapter) Parent

func (c *Chapter) Parent() *Chapter

Parent returns the parent chapter (nil for top-level).

func (*Chapter) SetStyle

func (c *Chapter) SetStyle(style ChapterStyle)

SetStyle sets the chapter heading style.

func (*Chapter) SetTitle

func (c *Chapter) SetTitle(title string)

SetTitle sets the chapter title.

func (*Chapter) Style

func (c *Chapter) Style() ChapterStyle

Style returns the current chapter heading style.

func (*Chapter) SubChapters

func (c *Chapter) SubChapters() []*Chapter

SubChapters returns all sub-chapters.

func (*Chapter) Title

func (c *Chapter) Title() string

Title returns the chapter title.

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
}

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 (Color) ToCMYK

func (c Color) ToCMYK() ColorCMYK

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

func NewColorCMYK(c, m, y, k float64) ColorCMYK

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

func (c ColorCMYK) ToRGB() Color

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 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

func (c *Creator) AddBookmark(title string, pageIndex int, level int) error

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

func (c *Creator) AddChapter(ch *Chapter) error

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

func (c *Creator) Bookmarks() []Bookmark

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) Chapters

func (c *Creator) Chapters() []*Chapter

Chapters returns all top-level chapters in the document.

func (*Creator) DisableTOC

func (c *Creator) DisableTOC()

DisableTOC disables automatic Table of Contents generation.

func (*Creator) Document

func (c *Creator) Document() *document.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

func (c *Creator) FooterHeight() float64

FooterHeight returns the current footer height in points.

func (*Creator) HeaderHeight

func (c *Creator) HeaderHeight() float64

HeaderHeight returns the current header height in points.

func (*Creator) NewPage

func (c *Creator) NewPage() (*Page, error)

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) NewPageWithSize

func (c *Creator) NewPageWithSize(size PageSize) (*Page, error)

NewPageWithSize adds a new page with a specific size.

This overrides the default page size for this specific page.

Example:

page := c.NewPageWithSize(creator.Letter)

func (*Creator) PageCount

func (c *Creator) PageCount() int

PageCount returns the number of pages in the document.

func (*Creator) SetAuthor

func (c *Creator) SetAuthor(author string)

SetAuthor sets the document author.

Example:

c.SetAuthor("John Doe")

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

func (c *Creator) SetFooterHeight(h float64)

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

func (c *Creator) SetHeaderHeight(h float64)

SetHeaderHeight sets the height reserved for headers in points.

Default: 50 points.

Example:

c.SetHeaderHeight(40)  // 40 points for header

func (*Creator) SetKeywords

func (c *Creator) SetKeywords(keywords ...string)

SetKeywords sets document keywords for search/indexing.

Example:

c.SetKeywords("report", "2025", "finance", "annual")

func (*Creator) SetMargins

func (c *Creator) SetMargins(top, right, bottom, left float64) error

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

func (c *Creator) SetMetadata(title, author, subject string)

SetMetadata sets all document metadata at once.

Example:

c.SetMetadata("My Document", "John Doe", "Annual Report")

func (*Creator) SetPageSize

func (c *Creator) SetPageSize(size PageSize)

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

func (c *Creator) SetSkipFooterOnFirstPage(skip bool)

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

func (c *Creator) SetSkipHeaderOnFirstPage(skip bool)

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

func (c *Creator) SetSubject(subject string)

SetSubject sets the document subject.

Example:

c.SetSubject("Financial Report")

func (*Creator) SetTitle

func (c *Creator) SetTitle(title string)

SetTitle sets the document title.

Example:

c.SetTitle("Annual Report 2025")

func (*Creator) SkipFooterOnFirstPage

func (c *Creator) SkipFooterOnFirstPage() bool

SkipFooterOnFirstPage returns whether footers are skipped on the first page.

func (*Creator) SkipHeaderOnFirstPage

func (c *Creator) SkipHeaderOnFirstPage() bool

SkipHeaderOnFirstPage returns whether headers are skipped on the first page.

func (*Creator) TOC

func (c *Creator) TOC() *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

func (c *Creator) TOCEnabled() bool

TOCEnabled returns whether TOC generation is enabled.

func (*Creator) Validate

func (c *Creator) Validate() error

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) WriteToFile

func (c *Creator) WriteToFile(path string) error

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

func (c *Creator) WriteToFileContext(ctx context.Context, path string) error

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) 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

func (d *Division) Add(drawable Drawable) *Division

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

func (d *Division) Background() *Color

Background returns the background color, or nil if transparent.

func (*Division) Clear

func (d *Division) Clear() *Division

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

func (d *Division) Drawables() []Drawable

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) Padding

func (d *Division) Padding() Margins

Padding returns the padding margins.

func (*Division) SetBackground

func (d *Division) SetBackground(c Color) *Division

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

func (d *Division) SetBorder(b Border) *Division

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

func (d *Division) SetBorderBottom(b Border) *Division

SetBorderBottom sets the bottom border, overriding the default border.

Example:

div.SetBorderBottom(Border{Width: 3, Color: Red})

func (*Division) SetBorderLeft

func (d *Division) SetBorderLeft(b Border) *Division

SetBorderLeft sets the left border, overriding the default border.

Example:

div.SetBorderLeft(Border{Width: 4, Color: Blue})

func (*Division) SetBorderRight

func (d *Division) SetBorderRight(b Border) *Division

SetBorderRight sets the right border, overriding the default border.

Example:

div.SetBorderRight(Border{Width: 1, Color: Gray})

func (*Division) SetBorderTop

func (d *Division) SetBorderTop(b Border) *Division

SetBorderTop sets the top border, overriding the default border.

Example:

div.SetBorderTop(Border{Width: 3, Color: Red})

func (*Division) SetMargins

func (d *Division) SetMargins(m Margins) *Division

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

func (d *Division) SetMinHeight(h float64) *Division

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

func (d *Division) SetPadding(top, right, bottom, left float64) *Division

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

func (d *Division) SetPaddingAll(p float64) *Division

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

func (*Division) SetWidth

func (d *Division) SetWidth(w float64) *Division

SetWidth sets an explicit width for the division.

If width is 0, the division uses the full available width.

Example:

div.SetWidth(300) // 300 points wide

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

type DrawablePosition struct {
	Drawable Drawable
	X        float64
	Y        float64
}

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
}

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 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).

const (
	// Symbol is Symbol font (symbolic characters, mathematical symbols).
	Symbol FontName = "Symbol"

	// ZapfDingbats is ZapfDingbats font (symbolic characters, dingbats).
	ZapfDingbats FontName = "ZapfDingbats"
)

Standard 14 fonts - Symbolic fonts.

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 is the current page number (1-based).
	PageNum int

	// TotalPages is the total number of pages in the document.
	// This is known because footers 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 footer content into.
	// 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

func NewLinearGradient(x1, y1, x2, y2 float64) *Gradient

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

func NewRadialGradient(x0, y0, r0, x1, y1, r1 float64) *Gradient

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

func (g *Gradient) AddColorStop(position float64, color Color) error

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)

func (*Gradient) Validate

func (g *Gradient) Validate() error

Validate validates the gradient configuration.

Checks:

  • At least 2 color stops are defined
  • Color stops are in range [0, 1]
  • For linear gradients: start and end points are different
  • For radial gradients: radii are non-negative

Returns an error if validation fails.

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
)

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
}

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 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

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

func LoadImage(path string) (*Image, error)

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

func LoadImageFromReader(r io.Reader) (*Image, error)

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

func (img *Image) AlphaMask() []byte

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

func (img *Image) BitsPerComponent() int

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

func (img *Image) Components() int

Components returns the number of color components.

Returns:

  • 1 for grayscale
  • 3 for RGB
  • 4 for CMYK

func (*Image) Data

func (img *Image) Data() []byte

Data returns the raw JPEG data.

This is used internally by the PDF writer to embed the image.

func (*Image) Format

func (img *Image) Format() string

Format returns the image format (jpeg or png).

func (*Image) HasAlpha

func (img *Image) HasAlpha() bool

HasAlpha returns true if the image has transparency data.

func (*Image) Height

func (img *Image) Height() int

Height returns the image height in pixels.

func (*Image) Width

func (img *Image) Width() int

Width returns the image width in pixels.

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 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
}

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) Add

func (l *List) Add(text string) *List

Add adds a text item to the list. Returns the list for method chaining.

func (*List) AddItem

func (l *List) AddItem(item ListItem) *List

AddItem adds a ListItem to the list. Returns the list for method chaining.

func (*List) AddSubList

func (l *List) AddSubList(subList *List) *List

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

func (l *List) SetBulletChar(char string) *List

SetBulletChar sets the bullet character for bullet lists. Returns the list for method chaining.

func (*List) SetColor

func (l *List) SetColor(c Color) *List

SetColor sets the text color. Returns the list for method chaining.

func (*List) SetFont

func (l *List) SetFont(font FontName, size float64) *List

SetFont sets the font and size for the list. Returns the list for method chaining.

func (*List) SetIndent

func (l *List) SetIndent(indent float64) *List

SetIndent sets the indentation per nesting level. Returns the list for method chaining.

func (*List) SetLineSpacing

func (l *List) SetLineSpacing(spacing float64) *List

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

func (l *List) SetMarkerIndent(indent float64) *List

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

func (l *List) SetStartNumber(n int) *List

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

func NewListItem(text string) ListItem

NewListItem creates a new list item with the given text.

func NewListItemWithSubList

func NewListItemWithSubList(text string, subList *List) ListItem

NewListItemWithSubList creates a new list item with a nested list.

type Margins

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

Margins represents page margins in points (1 point = 1/72 inch).

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

func (m *Merger) AddAllPages(path string) error

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

func (m *Merger) AddPageRange(path string, start, end int) error

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

func (m *Merger) AddPages(path string, pageNums ...int) error

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

func (m *Merger) Close() error

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

func (m *Merger) Write(path string) error

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

func (m *Merger) WriteContext(ctx context.Context, path string) error

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 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

func (p *Page) AddField(field interface{}) error

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 (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 (p *Page) AddLink(text, url string, x, y float64, font FontName, size float64) error

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

func (p *Page) AddLinkStyled(text, url string, x, y float64, style LinkStyle) error

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

func (p *Page) AddText(text string, x, y float64, font FontName, size float64) error

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) 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) 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) ContentHeight

func (p *Page) ContentHeight() float64

ContentHeight returns the usable height (page height minus top and bottom margins).

func (*Page) ContentWidth

func (p *Page) ContentWidth() float64

ContentWidth returns the usable width (page width minus left and right margins).

func (*Page) Draw

func (p *Page) Draw(d Drawable) error

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

func (p *Page) DrawAt(d Drawable, x, y float64) error

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

func (p *Page) DrawImage(img *Image, x, y, width, height float64) error

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

func (p *Page) DrawImageFit(img *Image, x, y, maxWidth, maxHeight float64) error

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) 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

func (p *Page) DrawRectFilled(x, y, width, height float64, fillColor Color) error

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) 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) 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

func (p *Page) Height() float64

Height returns the page height in points.

If the page is rotated 90 or 270 degrees, width and height are swapped.

func (*Page) Margins

func (p *Page) Margins() Margins

Margins returns the page margins.

func (*Page) MoveCursor

func (p *Page) MoveCursor(x, y float64)

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

func (p *Page) Rotate(degrees int) error

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 SetRotation() for API convenience.

Example:

page.Rotate(90)  // Landscape
page.Rotate(180) // Upside down
page.Rotate(270) // Landscape (counter-clockwise)

func (*Page) Rotation

func (p *Page) Rotation() int

Rotation returns the current page rotation in degrees.

func (*Page) SetMargins

func (p *Page) SetMargins(top, right, bottom, left float64) error

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

func (p *Page) SetRotation(degrees int) error

SetRotation sets the page rotation.

Valid values are 0, 90, 180, and 270 degrees (clockwise).

Example:

page.SetRotation(90) // Landscape

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.

func (*Page) Width

func (p *Page) Width() float64

Width returns the page width in points.

If the page is rotated 90 or 270 degrees, width and height are swapped.

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.). Custom sizes can be created using the CustomSize function.

const (
	// A4 paper size (210 × 297 mm or 595 × 842 points).
	// This is the most common paper size worldwide.
	A4 PageSize = iota

	// 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

	// 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
)

func (PageSize) String

func (ps PageSize) String() string

String returns the name of the page size.

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

func NewParagraph(text string) *Paragraph

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) Alignment

func (p *Paragraph) Alignment() Alignment

Alignment returns the current text alignment.

func (*Paragraph) Color

func (p *Paragraph) Color() Color

Color returns the current text color.

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) Font

func (p *Paragraph) Font() FontName

Font returns the current font name.

func (*Paragraph) FontSize

func (p *Paragraph) FontSize() float64

FontSize returns the current font size.

func (*Paragraph) Height

func (p *Paragraph) Height(ctx *LayoutContext) float64

Height calculates the total height of the paragraph when rendered.

func (*Paragraph) LineSpacing

func (p *Paragraph) LineSpacing() float64

LineSpacing returns the current line spacing multiplier.

func (*Paragraph) SetAlignment

func (p *Paragraph) SetAlignment(a Alignment) *Paragraph

SetAlignment sets the text alignment. Returns the paragraph for method chaining.

func (*Paragraph) SetColor

func (p *Paragraph) SetColor(c Color) *Paragraph

SetColor sets the text color. Returns the paragraph for method chaining.

func (*Paragraph) SetFont

func (p *Paragraph) SetFont(font FontName, size float64) *Paragraph

SetFont sets the font and size for the paragraph. Returns the paragraph for method chaining.

func (*Paragraph) SetLineSpacing

func (p *Paragraph) SetLineSpacing(spacing float64) *Paragraph

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

func (p *Paragraph) SetText(text string) *Paragraph

SetText sets the paragraph text. Returns the paragraph for method chaining.

func (*Paragraph) Text

func (p *Paragraph) Text() string

Text returns the paragraph text.

func (*Paragraph) WrapTextLines

func (p *Paragraph) WrapTextLines(availableWidth float64) []string

WrapTextLines returns the lines after wrapping (for testing/debugging).

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
}

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
}

PolylineOptions configures polyline drawing.

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
}

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

func NewSplitter(path string) (*Splitter, error)

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

func (s *Splitter) Close() error

Close closes the splitter and releases resources.

This should be called when done with the splitter (use defer).

func (*Splitter) ExtractPages

func (s *Splitter) ExtractPages(pages ...int) (*document.Document, error)

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

func (s *Splitter) SetFilenamePattern(pattern string)

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

func (s *Splitter) Split(outputDir string) error

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

func (s *Splitter) SplitByRanges(ranges ...PageRange) error

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

func (s *Splitter) SplitByRangesContext(ctx context.Context, ranges ...PageRange) error

SplitByRangesContext splits by ranges with context support.

func (*Splitter) SplitContext

func (s *Splitter) SplitContext(ctx context.Context, outputDir string) error

SplitContext splits with context support.

Example:

ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
splitter.SplitContext(ctx, "output/")

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

SetNote sets an optional note text.

Example:

strikeout.SetNote("Obsolete")

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 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

func (t *TOC) GetEntries() []TOCEntry

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) Leader

func (t *TOC) Leader() string

Leader returns the current leader character.

func (*TOC) SetLeader

func (t *TOC) SetLeader(leader string)

SetLeader sets the leader character (default: ".").

Example:

toc.SetLeader(".")  // Introduction .............. 1
toc.SetLeader("-")  // Introduction ------------- 1

func (*TOC) SetShowPageNumbers

func (t *TOC) SetShowPageNumbers(show bool)

SetShowPageNumbers enables/disables page number display.

func (*TOC) SetStyle

func (t *TOC) SetStyle(style TOCStyle)

SetStyle sets the TOC visual style.

func (*TOC) SetTitle

func (t *TOC) SetTitle(title string)

SetTitle sets the TOC heading title.

func (*TOC) ShowPageNumbers

func (t *TOC) ShowPageNumbers() bool

ShowPageNumbers returns whether page numbers are displayed.

func (*TOC) Style

func (t *TOC) Style() TOCStyle

Style returns the current TOC style.

func (*TOC) Title

func (t *TOC) Title() string

Title returns the TOC heading title.

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

func NewTableCell(content string) TableCell

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 TableRow

type TableRow struct {
	Cells []TableCell
}

TableRow represents a row in a table.

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).
	Font FontName

	// 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
}

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

func (*TextWatermark) Text

func (w *TextWatermark) Text() string

Text returns the watermark text.

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

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
)

Directories

Path Synopsis
Package forms provides interactive form field support for PDF documents.
Package forms provides interactive form field support for PDF documents.

Jump to

Keyboard shortcuts

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