asposepdf

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 21, 2026 License: MIT Imports: 27 Imported by: 22

README

Aspose.PDF FOSS for Go

test Go Reference Go Version

A pure Go library for PDF manipulation — split, merge, rotate, extract text and images, read and write metadata, encrypt with RC4-128 / AES-128 / AES-256, fill and build AcroForms, attach and render annotations, create bookmark trees, draw text and apply watermarks, place images, and validate document structure. No external dependencies — standard library only.

Spec references throughout follow ISO 32000-1 (PDF 1.7) and ISO 32000-2 (PDF 2.0). API shape mirrors Aspose.PDF for .NET where natural for migrants.

Install

go get github.com/aspose-pdf-foss/aspose-pdf-foss-for-go

Requires Go 1.24 or newer. Standard library only — no transitive dependencies.

Quick Start

import pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"

// Open a PDF
doc, err := pdf.Open("input.pdf")

// Split into individual page documents
pages, err := doc.Split()
for i, p := range pages {
    p.Save(fmt.Sprintf("page%03d.pdf", i+1))
}

// Merge multiple PDFs into one (Append mutates doc in place)
doc2, _ := pdf.Open("file2.pdf")
doc.Append(doc2)
doc.Save("merged.pdf")

Features

  • Split — split a document into individual pages
  • Extract — build a new Document from selected page ranges without mutating the source
  • Merge — combine multiple PDFs into a single document
  • Rotate — rotate pages by 90°, 180°, or 270°
  • Page info — read page count, dimensions, all PDF boxes (MediaBox, CropBox, TrimBox, BleedBox, ArtBox), and page labels
  • Metadata — read and write document Info (title, author, subject, keywords, creator, producer, creation/mod dates, plus arbitrary custom entries)
  • Encrypt — password-protect PDFs with AES-128 (default, ISO 32000-1 §7.6.3.2 V=4 R=4 /CFM /AESV2), AES-256 (ISO 32000-2 §7.6.4 V=5 R=6 /CFM /AESV3, PDF 2.0), or RC4-128 (legacy V=2 R=3); Standard Security Handler with user + owner passwords and granular viewer permissions (print, copy, modify, annotate, form fill, accessibility, assembly, high-res print). Round-trip preserves AcroForm fields, annotations, and embedded files
  • Outlines (bookmarks) — read, create, and edit hierarchical bookmarks via OutlineItemCollection. Recursive tree model 1:1 with Aspose.PDF for .NET. All 8 destination types (XYZ/Fit/FitH/FitV/FitR/FitB/FitBH/FitBV) per ISO 32000-1 §12.3.2.2. Style attributes (Bold, Italic, Color), expand/collapse state, and Action attachment all roundtrip. Named destinations (Document.NamedDestinations()) integrate as the 9th destination type with forward-reference support; reads both legacy /Catalog/Dests and modern /Catalog/Names/Dests, writes modern only with automatic migration. Works alongside encryption + AcroForm + annotations
  • Tables — pdf.NewTable() builds a Table/Row/Cell tree with Aspose.PDF for .NET-parity naming (BorderInfo, MarginInfo, ColumnWidths). (*Page).AddTable(t, rect) renders inside a Rectangle (same paradigm as AddText/AddImage). Per-cell borders (bitmask sides), padding, text style, alignment, background fill. Auto-fit row heights or Row.SetHeight explicit. Cell text reuses the full AddText machinery (word-wrap, alignment, font embedding, Unicode). Multi-page overflow with automatic page append; repeating header rows via Table.SetRepeatingRowsCount; cell merging via Cell.SetColSpan / SetRowSpan. Image cells via Cell.SetImage; row-level styling via Row.SetBackground / SetTextStyle / SetBorder / SetMargin; batch Table.AddRows; border edge de-duplication for cleaner identical-style adjacent borders
  • Vector graphics — (*Page).DrawLine / DrawRectangle / DrawRoundedRectangle / DrawCircle / DrawEllipse / DrawPolyline / DrawPolygon / DrawPath for first-class vector content on PDF pages. Path fluent builder with MoveTo / LineTo / CurveTo / QuadTo / Arc / Close. LineStyle + ShapeStyle (color, width, dash pattern, line caps, line joins, alpha). Mirrors Aspose.PDF for .NET's Graph/Shape model but exposed directly on Page (no container) and Go-idiomatic
  • Validate — check structural integrity of a PDF file
  • Text extraction — extract text from pages in visual reading order with full layout info (coordinates, font, bold/italic, color, sub/superscript)
  • Image extraction — extract images as JPEG (passthrough) or PNG with position, dimensions, and color space metadata; supports DeviceRGB, DeviceGray, DeviceCMYK, Indexed, ICCBased color spaces, soft masks (alpha), inline images, and Form XObjects
  • Add images — place JPEG or PNG images onto existing pages with precise positioning via PDF rectangles
  • Image to PDF — convert standalone images to single-page PDFs with DPI-aware sizing, configurable page dimensions and margins
  • Replace images — swap image data on existing pages while preserving position and size
  • Remove images — delete images from pages, cleaning up resources and content stream operators
  • Remove unused objects — clean up orphaned objects after modifications to reduce file size
  • Optimize images — reduce file size by downscaling images above a target DPI and converting opaque PNGs to JPEG
  • Create blank documents — create single-page blank PDFs with custom dimensions or predefined page formats (A4, Letter, Legal, A3)
  • Add blank pages — append or insert blank pages into existing documents at any position
  • Add text — draw text on pages with font selection, alignment, word wrap, color, background, underline, strikethrough, rotation, and behind-content mode
  • Text watermarks — apply text watermarks to all or selected pages with full styling control
  • Stream I/O — open PDFs from any io.Reader via OpenStream/OpenStreamWithPassword; serialize to any io.Writer via Document.WriteTo (implements io.WriterTo)
  • Forms (AcroForm) — read, fill, and build from scratch all standard field types (text, checkbox, radio, combo box, list box, push button); programmatic field creation with AddTextField/AddCheckbox/AddRadioGroup/AddComboBox/AddListBox/AddPushButton; RemoveField; non-ASCII values encoded as UTF-16BE; viewers regenerate appearances via auto /NeedAppearances=true
  • Annotations — Link (with /A actions: GoToURI, GoTo, Named, SubmitForm, ResetForm, JavaScript), Highlight, Underline, StrikeOut, Squiggly. Page-scoped collection API (Page.Annotations() with Add/At/Delete/DeleteAt); existing form widgets surface as read-only WidgetAnnotation. Drawing primitives (Square/Circle/Line/Ink) with full ISO 32000-1 border styles (Solid/Dashed/Beveled/Inset/Underline) and 10 line-ending styles. Text-bearing types (Text sticky note, FreeText with callout/typewriter/cloudy-border modes, Stamp with 14 predefined visuals + custom image override). FileAttachment with file embedding (path/stream + MIME detection); Redact with mark/apply modes (irreversible content removal of text glyphs, images, and paths via Document.ApplyRedactions()); NewJavaScriptAction public constructor with security warning. /AP appearance streams generated automatically — annotations render natively in any spec-conforming viewer

API Reference

*Document methods mutate the receiver in place. Split and Extract return fresh, fully-independent documents; all other operations (rotation, reorder, metadata, passwords, etc.) modify the document they are called on.

Opening documents
// From a file path
doc, err := pdf.Open("input.pdf")

// From an io.Reader (stream, HTTP response, etc.)
doc, err = pdf.OpenStream(r)

// Encrypted files: returns ErrEncrypted from plain Open; supply a password
doc, err = pdf.Open("locked.pdf")
if errors.Is(err, pdf.ErrEncrypted) {
    doc, err = pdf.OpenWithPassword("locked.pdf", "secret")
}

// OpenWithPassword also works on plain PDFs (password is silently ignored),
// so it's a safe drop-in for code that doesn't know up front whether the
// input is encrypted. The password is tried as both user and owner.
doc, err = pdf.OpenWithPassword("maybe-encrypted.pdf", "secret")
Splitting
doc, err := pdf.Open("input.pdf")

// Split into individual page documents
pages, err := doc.Split()
for i, p := range pages {
    p.Save(fmt.Sprintf("page%03d.pdf", i+1))
}
Extracting page ranges
doc, err := pdf.Open("input.pdf")

// Build a new document with pages 1–3 and 7–9 (doc is not mutated)
extracted, err := doc.Extract(
    pdf.PageRange{From: 1, To: 3},
    pdf.PageRange{From: 7, To: 9},
)
extracted.Save("output.pdf")
Page info
doc, _ := pdf.Open("input.pdf")

// Total page count
fmt.Println(doc.PageCount())

// Dimensions of every page (width and height in points, 1/72 inch)
sizes, err := pdf.PageSizes("input.pdf")
for i, s := range sizes {
    fmt.Printf("Page %d: %.1f x %.1f pt\n", i+1, s.Width, s.Height)
}
Metadata
// Read
doc, _ := pdf.Open("input.pdf")
meta, _ := doc.Metadata()
fmt.Println(meta.Title, meta.Author, meta.CreationDate)

// Write (full replacement — unset fields are omitted from the PDF)
doc.SetMetadata(pdf.Metadata{
    Title:  "My Document",
    Author: "Jane Smith",
    Custom: map[string]string{"Department": "Legal"},
})
doc.Save("output.pdf")

// Update a single field: read → modify → write
meta, _ = doc.Metadata()
meta.Title = "Updated Title"
doc.SetMetadata(meta)

// Strip all metadata
doc.ClearMetadata()
doc.Save("clean.pdf")
Encryption
// Standalone function — encrypts with default all-allow permissions
err := pdf.Encrypt("input.pdf", "output.pdf", "userpass", "ownerpass")

// Simple case on a Document (applied on Save/WriteTo)
doc, _ := pdf.Open("input.pdf")
doc.SetPassword("userpass", "ownerpass")
err = doc.Save("output.pdf")

// Granular permissions (RC4-128, Standard Security Handler R=3).
// Fields omitted from Permissions{} are denied; if SetPermissions is not
// called at all, every operation is allowed (backward compatible default).
doc.SetPermissions(pdf.Permissions{
    AllowPrint:         true,
    AllowCopy:          true,
    AllowAccessibility: true,
})
doc.Save("restricted.pdf")

// One-call unified API via options — equivalent to SetPassword + SetPermissions
// in a single struct; replaces any prior encryption config on the document.
// Algorithm defaults to AES-128 (ISO 32000-1 V=4 R=4 /CFM /AESV2). Pass
// pdf.EncryptionAlgRC4_128 for legacy RC4-128 V=2 R=3 output, or
// pdf.EncryptionAlgAES256 for AES-256 V=5 R=6 (ISO 32000-2; output uses
// %PDF-2.0 header and requires Acrobat DC or another PDF 2.0 viewer).
doc.SetEncryption(pdf.EncryptionOptions{
    UserPassword:  "userpass",
    OwnerPassword: "ownerpass",
    Permissions:   &pdf.Permissions{AllowPrint: true, AllowCopy: true},
    // Algorithm:  pdf.EncryptionAlgAES128, // default
    // Algorithm:  pdf.EncryptionAlgAES256, // ISO 32000-2; produces %PDF-2.0
    // Algorithm:  pdf.EncryptionAlgRC4_128, // legacy
})
doc.Save("restricted.pdf")

// Reading permissions from an encrypted file (works after OpenWithPassword)
doc, _ = pdf.OpenWithPassword("restricted.pdf", "userpass")
perms, ok := doc.Permissions()
if ok {
    fmt.Printf("can print: %v, can copy: %v\n", perms.AllowPrint, perms.AllowCopy)
}

// Edit-in-place: OpenWithPassword preserves the password, so a plain Save
// re-encrypts with the same password. To produce a plaintext copy, call
// RemoveEncryption explicitly before Save.
doc, _ = pdf.OpenWithPassword("restricted.pdf", "userpass")
doc.AddTextWatermark("APPROVED", pdf.TextStyle{Size: 48})
doc.Save("restricted_signed.pdf")          // still encrypted
doc.RemoveEncryption()
doc.Save("decrypted_copy.pdf")             // plaintext

Permissions fields map to ISO 32000-1 §7.6.3.2 Table 22 bits 3, 4, 5, 6, 9, 10, 11, 12. The library encodes them with the Adobe convention (reserved bits 7-8 and 13-32 set high). Permissions are enforced by PDF viewers — the library itself is not a DRM mechanism.

In EncryptionOptions, Permissions is a pointer so that nil (omitted) means "grant all", distinguishing the default from an explicit &Permissions{} which denies everything.

Forms (AcroForm)
doc, _ := pdf.Open("template.pdf")

// Iterate every form field
for _, f := range doc.Form().Fields() {
    fmt.Printf("%s = %q (type %v)\n", f.FullName(), f.Value(), pdf.FieldType(f))
}

// Set values by type
text := doc.Form().Field("name").(*pdf.TextBoxField)
text.SetValue("Jane Doe")

check := doc.Form().Field("subscribe").(*pdf.CheckboxField)
check.SetChecked(true)

radio := doc.Form().Field("plan").(*pdf.RadioButtonField)
radio.Options()[1].SetSelected(true)

combo := doc.Form().Field("country").(*pdf.ComboBoxField)
combo.SetSelected(0) // by index into combo.Options()

list := doc.Form().Field("interests").(*pdf.ListBoxField)
if list.MultiSelect() {
    list.SetSelected(0, 2, 3)
} else {
    list.SetSelected(1)
}

// Save — viewers regenerate appearances on open via auto /NeedAppearances=true
doc.Save("filled.pdf")

Field values containing non-ASCII characters (e.g. Cyrillic) are encoded as UTF-16BE with a BOM so any spec-conforming viewer reads them back correctly.

Building forms from scratch
doc := pdf.NewDocument(595, 842)
form := doc.Form()

// Single-widget fields
tf, _ := form.AddTextField(1, pdf.Rectangle{LLX: 50, LLY: 700, URX: 545, URY: 725}, "name")
tf.SetMaxLen(50)
tf.SetValue("Jane Doe")

cb, _ := form.AddCheckbox(1, pdf.Rectangle{LLX: 50, LLY: 660, URX: 70, URY: 680}, "subscribe")
cb.SetChecked(true)

combo, _ := form.AddComboBox(1, pdf.Rectangle{LLX: 50, LLY: 600, URX: 250, URY: 625}, "country",
    []pdf.ChoiceOption{{Value: "USA"}, {Value: "Canada"}})
combo.SetSelected(0)

// Radio group: widgets can span multiple pages
rb, _ := form.AddRadioGroup("plan", []pdf.RadioItem{
    {PageNum: 1, Rect: pdf.Rectangle{LLX: 50, LLY: 540, URX: 70, URY: 560}, Export: "basic"},
    {PageNum: 1, Rect: pdf.Rectangle{LLX: 50, LLY: 510, URX: 70, URY: 530}, Export: "premium"},
})
rb.Options()[0].SetSelected(true)

form.AddPushButton(1, pdf.Rectangle{LLX: 50, LLY: 460, URX: 200, URY: 490}, "submit", "Submit")

// Remove a field by name
form.RemoveField("subscribe")

doc.Save("form.pdf")

/AcroForm/NeedAppearances is auto-set on every Add or structural mutation, so any standards-compliant viewer regenerates the field appearances at display time.

Out of scope for this release: self-rendered /AP appearances (separate epic — /NeedAppearances=true covers most viewers), and form flattening.

Outlines (Bookmarks)
doc, _ := pdf.Open("input.pdf")
page, _ := doc.Page(1)

// Top-level bookmark with style + destination
chapter := pdf.NewOutlineItemCollection(doc)
chapter.SetTitle("Chapter 1")
chapter.SetBold(true)
chapter.SetColor(&pdf.Color{R: 0, G: 0, B: 0.8, A: 1})
chapter.SetDestination(pdf.NewDestinationXYZ(page, 0, 800, 1.0))
doc.Outlines().Add(chapter)

// Nested child
section := pdf.NewOutlineItemCollection(doc)
section.SetTitle("Section 1.1")
section.SetDestination(pdf.NewDestinationFit(page))
chapter.Add(section)

doc.Save("with_bookmarks.pdf")

API mirrors Aspose.PDF for .NET's OutlineItemCollection 1:1 — Document.Outlines() is the root collection, NewOutlineItemCollection(doc) constructs an unattached entry, and the same IList<T>-equivalent surface (Add/Insert/Remove/RemoveAt/At/Count/All) lives on every entry for managing children. All 8 PDF destination types are supported (XYZ, Fit, FitH, FitV, FitR, FitB, FitBH, FitBV); the XYZ, FitH, FitV, FitBH, FitBV flavors also have NewDestinationXxxUnchanged variants for leaving specific coordinates as "current viewer state". Action and Destination may both be set per ISO 32000-1 §12.3.3 — viewers honor /Dest first.

// Named destinations — define once, reuse from outlines and links
doc.NamedDestinations().Add("intro",    pdf.NewDestinationFit(page1))
doc.NamedDestinations().Add("appendix", pdf.NewDestinationFitH(page2, 500))

oic := pdf.NewOutlineItemCollection(doc)
oic.SetTitle("Appendix")
oic.SetDestination(pdf.NewNamedDestination(doc, "appendix"))
doc.Outlines().Add(oic)

API mirrors Aspose.PDF for .NET's NamedDestinations collection and NamedDestination class 1:1. Reads both /Catalog/Dests (legacy PDF 1.1) and /Catalog/Names/Dests (modern PDF 1.2+) — legacy auto-migrates to modern on save.

Tables
doc := pdf.NewDocument(595, 842)
page, _ := doc.Page(1)

table := pdf.NewTable().
    SetColumnWidths([]float64{120, 200, 80}).
    SetBorder(pdf.BorderInfo{Sides: pdf.BorderSideAll, Width: 1}).
    SetDefaultCellBorder(pdf.BorderInfo{Sides: pdf.BorderSideAll, Width: 0.5}).
    SetDefaultCellMargin(pdf.MarginInfo{Top: 4, Right: 6, Bottom: 4, Left: 6}).
    SetDefaultCellStyle(pdf.TextStyle{Font: pdf.FontHelvetica, Size: 10})

header := table.AddRow()
header.AddCells("Name", "Description", "Qty")
for _, c := range header.Cells() {
    c.SetBackground(&pdf.Color{R: 0.9, G: 0.9, B: 0.9, A: 1})
    c.SetHAlign(pdf.HAlignCenter)
}

row := table.AddRow()
row.AddCells("Widget", "Standard widget", "5")

pagesAdded, _ := page.AddTable(table, pdf.Rectangle{LLX: 50, LLY: 600, URX: 545, URY: 750})
fmt.Printf("table flowed to %d additional pages\n", pagesAdded)
doc.Save("table.pdf")

For long tables, mark a header row to repeat on every continuation page and use Cell.SetColSpan for summary rows:

table := pdf.NewTable().
    SetColumnWidths([]float64{100, 200, 80, 80}).
    SetBorder(pdf.BorderInfo{Sides: pdf.BorderSideAll, Width: 1}).
    SetRepeatingRowsCount(1)

header := table.AddRow()
header.AddCells("Product", "Description", "Qty", "Total")

for _, item := range invoiceItems {
    row := table.AddRow()
    row.AddCells(item.Name, item.Description, item.Qty, item.Total)
}

// Summary row: "TOTAL" label spans the first 3 columns, amount in column 4.
totals := table.AddRow()
totals.AddCell("TOTAL").SetColSpan(3).SetHAlign(pdf.HAlignRight)
totals.AddCell(fmt.Sprintf("€%.2f", grandTotal))

pagesAdded, _ := page.AddTable(table, pdf.Rectangle{LLX: 50, LLY: 100, URX: 510, URY: 750})
fmt.Printf("table flowed to %d additional pages\n", pagesAdded)

Image cells and row-level styling (alternating row backgrounds, header logo):

table := pdf.NewTable().
    SetColumnWidths([]float64{60, 200, 80, 80}).
    SetRepeatingRowsCount(1)

// Header row with logo image + text headers.
header := table.AddRow().SetBackground(&pdf.Color{R: 0.95, G: 0.95, B: 0.95, A: 1})
header.AddCell("").SetImage("logo.png")
header.AddCell("Product")
header.AddCell("Qty")
header.AddCell("Total")

// Alternating row colors via Row.SetBackground.
rows := table.AddRows([][]string{
    {"", "Widget",   "5", "€25.00"},
    {"", "Gadget",   "2", "€18.00"},
    {"", "Sprocket", "9", "€72.00"},
})
for i, r := range rows {
    if i%2 == 1 {
        r.SetBackground(&pdf.Color{R: 0.97, G: 0.97, B: 0.97, A: 1})
    }
}

page.AddTable(table, pdf.Rectangle{LLX: 50, LLY: 100, URX: 470, URY: 750})

API mirrors Aspose.PDF for .NET's Table / Row / Cell / BorderInfo / MarginInfo 1:1 in type names. Cells inherit DefaultCellBorder / DefaultCellMargin / DefaultCellStyle from the table unless overridden per-cell. Tables are positioned by Rectangle (consistent with AddText and AddImage) instead of paragraph flow-layout.

Vector graphics
doc := pdf.NewDocument(595, 842)
page, _ := doc.Page(1)

// Stroke a dashed red line.
page.DrawLine(
    pdf.Point{X: 50, Y: 700}, pdf.Point{X: 545, Y: 700},
    pdf.LineStyle{
        Color:       &pdf.Color{R: 1, G: 0, B: 0, A: 1},
        Width:       2,
        DashPattern: []float64{6, 3},
    },
)

// Fill a rounded box with semi-transparent blue.
page.DrawRoundedRectangle(
    pdf.Rectangle{LLX: 100, LLY: 500, URX: 400, URY: 600}, 10,
    pdf.ShapeStyle{
        LineStyle: pdf.LineStyle{Width: 1, Color: &pdf.Color{R: 0, G: 0, B: 0.5, A: 1}},
        FillColor: &pdf.Color{R: 0.6, G: 0.8, B: 1, A: 0.5},
    },
)

// Custom path: shape with curve and close.
path := pdf.NewPath().
    MoveTo(200, 300).
    LineTo(400, 300).
    CurveTo(420, 320, 420, 360, 400, 380).
    LineTo(200, 380).
    Close()
page.DrawPath(path, pdf.ShapeStyle{
    LineStyle: pdf.LineStyle{Width: 1.5},
    FillColor: &pdf.Color{R: 1, G: 0.9, B: 0.3, A: 1},
})

doc.Save("shapes.pdf")
Annotations
doc, _ := pdf.Open("input.pdf")
page, _ := doc.Page(1)

// Add a hyperlink
link := pdf.NewLinkAnnotation(page, pdf.Rectangle{LLX: 50, LLY: 700, URX: 200, URY: 720})
link.SetAction(pdf.NewGoToURIAction("https://example.com"))
link.SetColor(&pdf.Color{R: 0, G: 0, B: 1, A: 1})
link.SetHighlight(pdf.LinkHighlightOutline) // /H click feedback: None / Invert (default) / Outline / Push
page.Annotations().Add(link)

// Highlight a passage
hl := pdf.NewHighlightAnnotation(page, pdf.Rectangle{LLX: 50, LLY: 600, URX: 300, URY: 615})
hl.SetColor(&pdf.Color{R: 1, G: 1, B: 0, A: 1})
hl.SetTitle("Reviewer")
hl.SetContents("Important paragraph")
hl.SetQuadPoints([]pdf.QuadPoint{
    {X1: 50, Y1: 615, X2: 300, Y2: 615, X3: 50, Y3: 600, X4: 300, Y4: 600},
})
page.Annotations().Add(hl)

// Iterate and filter
for _, a := range page.Annotations().All() {
    if a.AnnotationType() != pdf.AnnotationTypeLink {
        continue
    }
    if uri, ok := a.(*pdf.LinkAnnotation).Action().(*pdf.GoToURIAction); ok {
        fmt.Println(uri.URI())
    }
}

// Wire a form push button to a server submit
submit := pdf.NewLinkAnnotation(page, pdf.Rectangle{LLX: 50, LLY: 50, URX: 200, URY: 80})
submit.SetAction(pdf.NewSubmitFormAction(
    "https://example.com/api/subscribe",
    []string{"name", "email"},
    pdf.SubmitGetMethod|pdf.SubmitExportFormat,
))
page.Annotations().Add(submit)

doc.Save("with_annotations.pdf")

Supported subtypes: Link, Highlight, Underline, StrikeOut, Squiggly, Square, Circle, Line, Ink, Text, FreeText, Stamp, FileAttachment, Redact. Existing form widgets surface as WidgetAnnotation for read-only inspection — to mutate form fields use the Form API.

Drawing annotations (Square / Circle / Line / Ink)
doc := pdf.NewDocument(595, 842)
page, _ := doc.Page(1)

// Filled rectangle with dashed red border
sq := pdf.NewSquareAnnotation(page, pdf.Rectangle{LLX: 50, LLY: 700, URX: 200, URY: 800})
sq.SetColor(&pdf.Color{R: 1, G: 0, B: 0, A: 1})
sq.SetInteriorColor(&pdf.Color{R: 1, G: 1, B: 0, A: 1})
sq.SetBorderStyle(pdf.BorderDashed)
sq.SetDashPattern([]float64{4, 2})
page.Annotations().Add(sq)

// Blue circle, beveled border
c := pdf.NewCircleAnnotation(page, pdf.Rectangle{LLX: 250, LLY: 700, URX: 400, URY: 800})
c.SetColor(&pdf.Color{R: 0, G: 0, B: 1, A: 1})
c.SetBorderStyle(pdf.BorderBeveled)
c.SetBorderWidth(3)
page.Annotations().Add(c)

// Arrow line with closed-arrow heads on both ends
ln := pdf.NewLineAnnotation(page,
    pdf.Point{X: 50, Y: 600}, pdf.Point{X: 400, Y: 500})
ln.SetStartLineEnding(pdf.LineEndingClosedArrow)
ln.SetEndLineEnding(pdf.LineEndingClosedArrow)
ln.SetInteriorColor(&pdf.Color{R: 1, G: 1, B: 0, A: 1})
page.Annotations().Add(ln)

// Smooth ink stroke (Catmull-Rom smoothing applied automatically for 3+ points)
ink := pdf.NewInkAnnotation(page, [][]pdf.Point{
    {{X: 50, Y: 400}, {X: 100, Y: 450}, {X: 150, Y: 420},
     {X: 200, Y: 460}, {X: 250, Y: 400}},
})
ink.SetColor(&pdf.Color{R: 0, G: 0.5, B: 0, A: 1})
page.Annotations().Add(ink)

doc.Save("drawing.pdf")

Border styles available: BorderSolid, BorderDashed, BorderBeveled, BorderInset, BorderUnderline (per ISO 32000-1 Table 168). Line endings: LineEndingNone, Square, Circle, Diamond, OpenArrow, ClosedArrow, Butt, ROpenArrow, RClosedArrow, Slash (Table 176). Each property setter (SetBorderStyle, SetColor, SetStrokes, etc.) immediately regenerates the annotation's appearance stream so /AP/N is always in sync; no /NeedAppearances=true required, drawing annotations render in any spec-conforming viewer.

Text-bearing annotations (Text / FreeText / Stamp)
doc := pdf.NewDocument(595, 842)
page, _ := doc.Page(1)

// Sticky-note annotation (icon-based, no /AP needed — viewer renders icon)
ta := pdf.NewTextAnnotation(page, pdf.Point{X: 50, Y: 700})
ta.SetIcon(pdf.TextIconComment)
ta.SetTitle("Reviewer")
ta.SetContents("Important comment about this paragraph.")
ta.SetOpen(true)
page.Annotations().Add(ta)

// FreeText — text drawn directly on the page
ft := pdf.NewFreeTextAnnotation(page,
    pdf.Rectangle{LLX: 100, LLY: 600, URX: 400, URY: 660},
    "Highlighted note\nMulti-line supported",
    pdf.TextStyle{
        Font:       pdf.FontHelveticaBold,
        Size:       14,
        Color:      &pdf.Color{R: 0, G: 0, B: 0.5, A: 1},
        Background: &pdf.Color{R: 1, G: 1, B: 0.85, A: 1},
        HAlign:     pdf.HAlignCenter,
        VAlign:     pdf.VAlignMiddle,
    })
ft.SetBorderWidth(2)
ft.SetBorderEffect(pdf.BorderEffectCloudy)
page.Annotations().Add(ft)

// FreeText with callout pointer (Acrobat-style "comment with arrow")
ftc := pdf.NewFreeTextAnnotation(page,
    pdf.Rectangle{LLX: 300, LLY: 500, URX: 500, URY: 570},
    "Callout note",
    pdf.TextStyle{Font: pdf.FontHelvetica, Size: 11})
ftc.SetCalloutPoints([]pdf.Point{
    {X: 250, Y: 530}, // knee
    {X: 200, Y: 480}, // endpoint (arrow tip)
})
ftc.SetEndLineEnding(pdf.LineEndingClosedArrow)
page.Annotations().Add(ftc)

// Stamp — predefined "Approved" with built-in green visual
sap := pdf.NewStampAnnotation(page,
    pdf.Rectangle{LLX: 100, LLY: 400, URX: 300, URY: 470},
    pdf.StampNameApproved)
page.Annotations().Add(sap)

// Stamp with custom image (PNG / JPEG via path or io.Reader)
sci := pdf.NewStampAnnotation(page,
    pdf.Rectangle{LLX: 320, LLY: 400, URX: 500, URY: 470},
    pdf.StampNameDraft) // /Name still set per spec, image overrides /AP
sci.SetCustomImage("logo.png")
page.Annotations().Add(sci)

doc.Save("text_bearing.pdf")

TextAnnotation icon names: TextIconNote (default), Comment, Key, Help, NewParagraph, Paragraph, Insert. FreeTextAnnotation supports three intents — FreeTextIntentFreeText (default), Callout (with arrow), Typewriter (no border/background). Border effects: BorderEffectNone (default) and BorderEffectCloudy (wavy border per ISO 32000-1 §12.5.4 /BE). All 14 stamp names from ISO 32000-1 Table 184 (StampNameApproved through StampNameTopSecret) ship with library-default colored visuals — green for positive (Approved/Final/ForPublicRelease), red for warning (Confidential/Expired/etc.), orange for informational (Draft/AsIs/etc.), gray for neutral (Departmental). Custom images (JPEG / PNG) override the default visual.

Specialised annotations (FileAttachment / Redact / JavaScript actions)
doc := pdf.NewDocument(595, 842)
page, _ := doc.Page(1)

// FileAttachment — embed a file with an icon
fa := pdf.NewFileAttachmentAnnotation(page, pdf.Point{X: 50, Y: 700})
fa.SetIcon(pdf.FileAttachmentIconPushPin)
fa.SetFile("report.pdf")
fa.SetFileDescription("Q3 financial report")
fa.SetTitle("Reviewer")
fa.SetContents("Attached: Q3 report")
page.Annotations().Add(fa)

// Redact — mark for redaction (apply destructively below)
page.AddText("Confidential data here",
    pdf.TextStyle{Font: pdf.FontHelvetica, Size: 14},
    pdf.Rectangle{LLX: 50, LLY: 600, URX: 545, URY: 630})
ra := pdf.NewRedactAnnotation(page,
    pdf.Rectangle{LLX: 50, LLY: 600, URX: 545, URY: 630})
ra.SetInteriorColor(&pdf.Color{R: 0, G: 0, B: 0, A: 1})
ra.SetOverlayText("REDACTED")
page.Annotations().Add(ra)

// Apply destructively — text under /QuadPoints is irreversibly removed
if err := doc.ApplyRedactions(); err != nil {
    log.Fatal(err)
}

// JavaScript action on a Link
link := pdf.NewLinkAnnotation(page,
    pdf.Rectangle{LLX: 50, LLY: 500, URX: 200, URY: 520})
link.SetAction(pdf.NewJavaScriptAction("app.alert('Hello from PDF');"))
page.Annotations().Add(link)

doc.Save("specialised.pdf")

FileAttachmentAnnotation icons: Paperclip (default), Graph, PushPin, Tag. MIME type auto-detected from file extension. After save, viewers display the icon and let users save/open the embedded file. RedactAnnotation operates in two modes: mark mode (annotation alone, decorative — content still extractable) and apply mode (after Document.ApplyRedactions(), page content is rewritten to remove text glyphs, image XObjects, and paths inside /QuadPoints regions; the redact annotation is then deleted). Use ValidateRedactions() first as a pre-flight parseability check. NewJavaScriptAction carries a documented security warning — embedded JavaScript executes in the recipient's viewer.

Validation
report, err := pdf.Validate("input.pdf")
if err != nil {
    log.Fatal(err)
}
if !report.Valid {
    for _, issue := range report.Issues {
        fmt.Println(issue.Code, issue.Message)
    }
}

Issue codes: INVALID_HEADER, XREF_ERROR, OBJECT_ERROR, PAGE_TREE_ERROR, STREAM_ERROR, ENCRYPTED.

Text Extraction
doc, _ := pdf.Open("input.pdf")

// Simple text — one string per page
texts, err := doc.ExtractText()
for i, text := range texts {
    fmt.Printf("=== Page %d ===\n%s\n", i+1, text)
}

// Structured text with layout info
layouts, err := doc.ExtractTextWithLayout()
for _, lines := range layouts {
    for _, line := range lines {
        fmt.Printf("Y=%.1f: %s\n", line.Y, line.Text)
        for _, frag := range line.Fragments {
            fmt.Printf("  [%.1f,%.1f] %q font=%s size=%.1f bold=%v italic=%v\n",
                frag.X, frag.Y, frag.Text, frag.FontName, frag.FontSize,
                frag.Bold, frag.Italic)
        }
    }
}

// Per-page extraction
page, _ := doc.Page(1)
text, err := page.ExtractText()
lines, err := page.ExtractTextWithLayout()
Image Extraction
doc, _ := pdf.Open("input.pdf")

// Extract images from all pages
allImages, err := doc.ExtractImages()
for pageIdx, images := range allImages {
    for imgIdx, img := range images {
        ext := ".png"
        if img.Format == pdf.ImageFormatJPEG {
            ext = ".jpg"
        }
        img.Save(fmt.Sprintf("page%d_img%d%s", pageIdx+1, imgIdx+1, ext))

        fmt.Printf("  %dx%d %s at (%.1f, %.1f)\n",
            img.Width, img.Height, ext, img.X, img.Y)
    }
}

// Per-page extraction
page, _ := doc.Page(1)
images, err := page.ExtractImages()
// List image metadata without decoding (fast)
allInfos, err := doc.ImageInfos()
for pageIdx, infos := range allInfos {
    for _, info := range infos {
        fmt.Printf("page %d: %dx%d %s\n",
            pageIdx+1, info.Width, info.Height, info.Name)
    }
}

// Selectively extract only large images
for _, infos := range allInfos {
    for i, info := range infos {
        if info.Width >= 500 {
            img, _ := infos[i].Extract()
            img.Save(fmt.Sprintf("large_%d.png", i))
        }
    }
}

Images are output as JPEG (passthrough for DCTDecode streams) or PNG (everything else). Supported color spaces: DeviceRGB, DeviceGray, DeviceCMYK (converted to RGB), Indexed (palette expansion), and ICCBased. Soft masks are applied as PNG alpha channels.

Adding Images
doc, _ := pdf.Open("input.pdf")
page, _ := doc.Page(1)

// Add a JPEG image at position (100, 600) with size 200x150
rect := pdf.Rectangle{LLX: 100, LLY: 600, URX: 300, URY: 750}
page.AddImage("logo.jpg", rect)

// Add from stream
f, _ := os.Open("photo.png")
page.AddImageFromStream(f, pdf.Rectangle{LLX: 50, LLY: 50, URX: 250, URY: 250})
f.Close()

doc.Save("output.pdf")
Image to PDF
// Convert an image to a single-page PDF (DPI-aware page sizing)
doc, _ := pdf.ImageToDocument("photo.jpg")
doc.Save("photo.pdf")

// With explicit A4 page size and margins
doc, _ = pdf.ImageToDocument("logo.png", pdf.ImageToDocumentOptions{
    PageWidth:  595, // A4
    PageHeight: 842,
    MarginLeft: 72,  // 1 inch margins
    MarginRight: 72,
    MarginTop:  72,
    MarginBottom: 72,
})
doc.Save("logo_a4.pdf")
Replacing and Removing Images
doc, _ := pdf.Open("input.pdf")
page, _ := doc.Page(1)
infos, _ := page.ImageInfos()

// Replace first image with a new one
infos[0].Replace("new_logo.jpg")

// Replace from stream
f, _ := os.Open("photo.png")
infos[1].ReplaceFromStream(f)
f.Close()

// Remove an image
infos[2].Remove()

doc.Save("output.pdf")
Cleaning Up Unused Objects
doc, _ := pdf.Open("input.pdf")
page, _ := doc.Page(1)
infos, _ := page.ImageInfos()
infos[0].Remove()

removed := doc.RemoveUnusedObjects()
fmt.Printf("removed %d unused objects\n", removed)
doc.Save("output.pdf") // smaller file
Optimizing Images
doc, _ := pdf.Open("large.pdf")
optimized, err := doc.OptimizeImages(pdf.OptimizeImageOptions{
    MaxDPI:           150,
    JPEGQuality:      75,
    ConvertPNGToJPEG: true,
})
fmt.Printf("optimized %d images\n", optimized)
doc.Save("smaller.pdf")
Creating Blank Documents
// From explicit dimensions (in points, 1/72 inch)
doc := pdf.NewDocument(595, 842)
doc.Save("blank.pdf")

// From predefined format
doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
doc.Save("a4.pdf")

// Landscape orientation
doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4.Landscape())
doc.Save("a4_landscape.pdf")
Adding Blank Pages
doc, _ := pdf.Open("input.pdf")

// Append a blank A4 page
doc.AddBlankPageFromFormat(pdf.PageFormatA4)

// Insert a landscape Letter page at position 2
doc.InsertBlankPageFromFormat(2, pdf.PageFormatLetter.Landscape())

doc.Save("output.pdf")
Adding Text
doc, _ := pdf.Open("input.pdf")
page, _ := doc.Page(1)

// Define a reusable text style
title := pdf.TextStyle{
    Font:   pdf.FontHelveticaBold,
    Size:   24,
    Color:  &pdf.Color{R: 0, G: 0, B: 0.8, A: 1},
    HAlign: pdf.HAlignCenter,
}

// Draw text inside a rectangle (word wrap + clipping)
page.AddText("Hello, PDF!", title, pdf.Rectangle{
    LLX: 50, LLY: 700, URX: 545, URY: 750,
})

// Rotated text (e.g. column headers)
page.AddText("Revenue", pdf.TextStyle{
    Font:     pdf.FontHelveticaBold,
    Size:     10,
    Rotation: 45, // degrees counter-clockwise
}, pdf.Rectangle{LLX: 100, LLY: 500, URX: 130, URY: 600})

doc.Save("output.pdf")
Text Watermarks
doc, _ := pdf.Open("input.pdf")

// Add watermark to all pages
doc.AddTextWatermark("CONFIDENTIAL", pdf.TextStyle{
    Font:     pdf.FontHelveticaBold,
    Size:     60,
    Color:    &pdf.Color{R: 0.8, G: 0.8, B: 0.8, A: 0.3},
    Rotation: 45,
    HAlign:   pdf.HAlignCenter,
    VAlign:   pdf.VAlignMiddle,
    Behind:   true, // draw under existing content
})

// Watermark on specific pages only
doc.AddTextWatermark("DRAFT", pdf.TextStyle{
    Font:     pdf.FontHelvetica,
    Size:     48,
    Color:    &pdf.Color{R: 1, G: 0, B: 0, A: 0.2},
    Rotation: -45,
    HAlign:   pdf.HAlignCenter,
    VAlign:   pdf.VAlignMiddle,
    Behind:   true,
}, 1, 3) // pages 1 and 3

doc.Save("output.pdf")
Document API
doc, err := pdf.Open("input.pdf")

fmt.Println(doc.PageCount())   // total pages
fmt.Println(doc.Metadata())    // Info dictionary

// Rotate pages (mutates in place; rotation accumulates)
err = doc.Rotate(pdf.Rotate90, 1, 2)
err = doc.Rotate(pdf.Rotate90, 1, 2) // pages 1 and 2 are now at 180°

// Set absolute rotation (replaces existing rotation)
err = doc.SetRotation(pdf.Rotate90, 1) // page 1 is now exactly 90°
err = doc.SetRotation(pdf.Rotate0)     // reset all pages to 0°

// Reorder pages (pages may be repeated or omitted)
err = doc.Reorder([]int{3, 1, 2})

// Append pages from one or more documents (mutates receiver)
doc2, _ := pdf.Open("part2.pdf")
doc3, _ := pdf.Open("part3.pdf")
doc.Append(doc2, doc3)

// Split into individual page documents (fresh independent Documents)
pages, err := doc.Split()

// Extract page ranges to a new independent Document
sub, err := doc.Extract(pdf.PageRange{From: 1, To: 3})

// Password-protect on save
doc.SetPassword("userpass", "ownerpass")

// Save to file or writer
err = doc.Save("output.pdf")
// or
_, err = doc.WriteTo(w) // implements io.WriterTo
Pages
doc, _ := pdf.Open("input.pdf")
pages := doc.Pages()
for _, p := range pages {
    size, _ := p.Size()
    fmt.Printf("Page %d: %.0fx%.0f pt, rotation %d°, label %q\n",
        p.Number(), size.Width, size.Height, p.Rotation(), p.Label())
}

// PDF boxes — each falls back to the next in the chain if not set:
// ArtBox/TrimBox/BleedBox → CropBox → MediaBox
p, _ := doc.Page(1)
mediaBox, _ := p.Size()
cropBox,  _ := p.CropBox()
trimBox,  _ := p.TrimBox()
bleedBox, _ := p.BleedBox()
artBox,   _ := p.ArtBox()

License

MIT License. See LICENSE for details.

Product Page

Aspose.PDF FOSS for Go — part of the Aspose family of document processing libraries.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	PageFormatA3     = PageFormat{Width: 842, Height: 1191}
	PageFormatA4     = PageFormat{Width: 595, Height: 842}
	PageFormatLetter = PageFormat{Width: 612, Height: 792}
	PageFormatLegal  = PageFormat{Width: 612, Height: 1008}
)

Predefined page formats (portrait orientation).

View Source
var ErrEncrypted = errors.New("PDF is encrypted; use OpenWithPassword")

ErrEncrypted is returned by Open / OpenStream when the input PDF carries an /Encrypt dictionary. Callers should retry with OpenWithPassword or OpenStreamWithPassword to supply a user or owner password.

Functions

func Encrypt

func Encrypt(inputPath, outputPath, userPassword, ownerPassword string) error

Encrypt writes a password-protected copy of inputPath to outputPath. The document is encrypted using RC4-128 (PDF 1.4 Standard Security Handler, revision 3). userPassword is required to open the document; ownerPassword controls permission settings. If ownerPassword is empty, it defaults to userPassword.

Example:

err := asposepdf.Encrypt("input.pdf", "output.pdf", "secret", "")

Types

type Action

type Action interface {
	ActionType() ActionType
	// contains filtered or unexported methods
}

Action is the common interface implemented by every concrete action type. Action values are inline within the parent annotation's /A dict — they are not separately addressable PDF objects.

type ActionType

type ActionType int

ActionType identifies the kind of action attached to an annotation (typically a LinkAnnotation's /A entry).

const (
	ActionTypeUnknown ActionType = iota
	ActionTypeGoToURI
	ActionTypeGoTo
	ActionTypeNamed
	ActionTypeSubmitForm
	ActionTypeResetForm
	ActionTypeJavaScript
)

type Annotation

type Annotation interface {
	AnnotationType() AnnotationType
	Rect() Rectangle
	SetRect(r Rectangle)
	Color() *Color
	SetColor(c *Color)
	Title() string
	SetTitle(s string)
	Contents() string
	SetContents(s string)
	PageIndex() int
	// contains filtered or unexported methods
}

Annotation is the common interface implemented by every concrete annotation type. Page-scoped — annotations belong to a specific page and are managed through that page's AnnotationCollection.

type AnnotationCollection

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

AnnotationCollection is the live, ordered set of annotations attached to a single page. Mutations through Add / Delete propagate to the page dict's /Annots array and to the document's object table; the next Save writes them out.

func (*AnnotationCollection) Add

Add attaches an annotation to this page. Errors if the annotation is already attached to a different page; idempotent same-page Add returns nil. Panics on nil annotation (programmer error).

func (*AnnotationCollection) All

func (c *AnnotationCollection) All() []Annotation

All returns the page's annotations as a slice. Each Annotation in the slice is a live handle: mutations write through to the underlying pdfDict and are visible to callers holding the same handle.

func (*AnnotationCollection) At

func (c *AnnotationCollection) At(index int) Annotation

At returns the annotation at the given index. Panics if out of range.

func (*AnnotationCollection) Count

func (c *AnnotationCollection) Count() int

Count reports how many annotations live on this page.

func (*AnnotationCollection) Delete

func (c *AnnotationCollection) Delete(a Annotation) bool

Delete removes the annotation from this page. Returns true if found, false otherwise. The annotation handle becomes dangling after Delete: mutations through it write to an unlinked dict that is no longer reachable from the document and are silently dropped on next Save.

func (*AnnotationCollection) DeleteAt

func (c *AnnotationCollection) DeleteAt(index int) error

DeleteAt removes the annotation at the given index. Errors on out-of-range index. The annotation handle becomes dangling after DeleteAt — see Delete for the dangling-handle semantics.

type AnnotationType

type AnnotationType int

AnnotationType identifies the kind of annotation. Returned by Annotation.AnnotationType() so callers can switch on type without a type-assertion ladder.

const (
	AnnotationTypeUnknown AnnotationType = iota
	AnnotationTypeLink
	AnnotationTypeHighlight
	AnnotationTypeUnderline
	AnnotationTypeStrikeOut
	AnnotationTypeSquiggly
	AnnotationTypeWidget
	AnnotationTypeSquare
	AnnotationTypeCircle
	AnnotationTypeLine
	AnnotationTypeInk
	AnnotationTypeText
	AnnotationTypeFreeText
	AnnotationTypeStamp
	AnnotationTypeFileAttachment
	AnnotationTypeRedact
)

type BorderEffect

type BorderEffect int

BorderEffect controls the /BE/S entry per ISO 32000-1 §12.5.4 Table 167.

const (
	BorderEffectNone   BorderEffect = iota // /S = /S (default)
	BorderEffectCloudy                     // /S = /C — wavy "cloud" border
)

type BorderInfo

type BorderInfo struct {
	Sides BorderSide
	Width float64 // in points; 0 means no border regardless of Sides
	Color *Color  // nil → black (R:0 G:0 B:0 A:1)
}

BorderInfo describes a border drawn around a table or cell. Mirrors Aspose.PDF for .NET's BorderInfo. Zero value means "no border".

type BorderSide

type BorderSide int

BorderSide is a bitmask selecting which sides of a rectangular border are drawn.

const (
	BorderSideNone   BorderSide = 0
	BorderSideTop    BorderSide = 1
	BorderSideRight  BorderSide = 2
	BorderSideBottom BorderSide = 4
	BorderSideLeft   BorderSide = 8
	BorderSideAll               = BorderSideTop | BorderSideRight | BorderSideBottom | BorderSideLeft
)

type BorderStyle

type BorderStyle int

BorderStyle controls the /BS dict for drawing annotations per ISO 32000-1 §12.5.4 Table 168.

const (
	BorderSolid     BorderStyle = iota // /S = /S
	BorderDashed                       // /S = /D + /D dash array
	BorderBeveled                      // /S = /B (3D raised effect)
	BorderInset                        // /S = /I (3D recessed effect)
	BorderUnderline                    // /S = /U (only the bottom edge)
)

type ButtonField

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

ButtonField is a push button — action only, no value semantics.

func (*ButtonField) FullName

func (b *ButtonField) FullName() string

func (*ButtonField) IsReadOnly

func (b *ButtonField) IsReadOnly() bool

func (*ButtonField) IsRequired

func (b *ButtonField) IsRequired() bool

func (*ButtonField) PageIndex

func (b *ButtonField) PageIndex() int

func (*ButtonField) PartialName

func (b *ButtonField) PartialName() string

func (*ButtonField) Rect

func (b *ButtonField) Rect() Rectangle

func (*ButtonField) SetReadOnly

func (f *ButtonField) SetReadOnly(v bool)

func (*ButtonField) SetValue

func (f *ButtonField) SetValue(s string) error

func (*ButtonField) Value

func (f *ButtonField) Value() string

type Cell

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

Cell is a single cell within a Row.

func (*Cell) Background

func (c *Cell) Background() *Color

func (*Cell) Border

func (c *Cell) Border() *BorderInfo

func (*Cell) ColSpan

func (c *Cell) ColSpan() int

ColSpan returns the cell's column span (1 if unset).

func (*Cell) Image

func (c *Cell) Image() (path string, hasImage bool)

Image returns the configured image source. path is empty when the image was set from a stream. hasImage is true when any image source is set.

func (*Cell) Margin

func (c *Cell) Margin() *MarginInfo

func (*Cell) Row

func (c *Cell) Row() *Row

Row returns the owning row.

func (*Cell) RowSpan

func (c *Cell) RowSpan() int

RowSpan returns the cell's row span (1 if unset).

func (*Cell) SetBackground

func (c *Cell) SetBackground(col *Color) *Cell

func (*Cell) SetBorder

func (c *Cell) SetBorder(b BorderInfo) *Cell

func (*Cell) SetColSpan

func (c *Cell) SetColSpan(n int) *Cell

SetColSpan sets the column span (cells the cell occupies horizontally). Default 1. Mirrors Aspose.PDF for .NET's Cell.ColSpan.

When colSpan > 1, the caller does NOT add cells for the positions covered by the span — the row simply has fewer cells.

func (*Cell) SetHAlign

func (c *Cell) SetHAlign(h HAlign) *Cell

func (*Cell) SetImage

func (c *Cell) SetImage(path string) *Cell

SetImage configures the cell to render the named image instead of text. PNG and JPEG supported (format auto-detected by magic bytes).

If both SetText and SetImage are configured, the image wins.

The image is auto-sized to fit the cell's interior width (sum of spanned column widths minus padding), preserving aspect ratio. Row height auto-fit computes the resulting image height plus margins. Use Row.SetHeight to override row height; the image then scales down to fit if needed.

Mirrors Aspose.PDF for .NET's Cell.Image property.

func (*Cell) SetImageFromStream

func (c *Cell) SetImageFromStream(r io.Reader) *Cell

SetImageFromStream is the io.Reader-based counterpart. The full stream is buffered immediately so that the table renderer can measure and draw later.

func (*Cell) SetMargin

func (c *Cell) SetMargin(m MarginInfo) *Cell

func (*Cell) SetRowSpan

func (c *Cell) SetRowSpan(n int) *Cell

SetRowSpan sets the row span (rows the cell occupies vertically). Default 1. Mirrors Aspose.PDF for .NET's Cell.RowSpan.

When rowSpan > 1, the caller does NOT add cells in subsequent rows for the positions covered by the span — those rows simply have fewer cells.

func (*Cell) SetText

func (c *Cell) SetText(text string) *Cell

func (*Cell) SetTextStyle

func (c *Cell) SetTextStyle(s TextStyle) *Cell

SetTextStyle overrides the table's DefaultCellStyle for this cell.

func (*Cell) SetVAlign

func (c *Cell) SetVAlign(v VAlign) *Cell

func (*Cell) Text

func (c *Cell) Text() string

func (*Cell) TextStyle

func (c *Cell) TextStyle() *TextStyle

TextStyle returns the per-cell style override (or nil if the cell inherits the table default).

type CheckboxField

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

CheckboxField is a checkbox with on/off state.

func (*CheckboxField) Checked

func (f *CheckboxField) Checked() bool

func (*CheckboxField) FullName

func (b *CheckboxField) FullName() string

func (*CheckboxField) IsReadOnly

func (b *CheckboxField) IsReadOnly() bool

func (*CheckboxField) IsRequired

func (b *CheckboxField) IsRequired() bool

func (*CheckboxField) PageIndex

func (b *CheckboxField) PageIndex() int

func (*CheckboxField) PartialName

func (b *CheckboxField) PartialName() string

func (*CheckboxField) Rect

func (b *CheckboxField) Rect() Rectangle

func (*CheckboxField) SetChecked

func (f *CheckboxField) SetChecked(v bool)

SetChecked sets the checkbox state. The "checked" /V is the kid widget's /AS export value (typically /Yes); the "unchecked" /V is /Off.

func (*CheckboxField) SetReadOnly

func (f *CheckboxField) SetReadOnly(v bool)

func (*CheckboxField) SetRequired

func (f *CheckboxField) SetRequired(v bool)

func (*CheckboxField) SetValue

func (f *CheckboxField) SetValue(s string) error

func (*CheckboxField) Value

func (f *CheckboxField) Value() string

type ChoiceOption

type ChoiceOption struct {
	Value  string // displayed text
	Export string // export value when distinct from Value
}

ChoiceOption is one option of a ComboBoxField or ListBoxField.

type CircleAnnotation

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

CircleAnnotation draws an elliptical annotation. Mirrors SquareAnnotation API; only the rendered shape and /Subtype differ. Border styles (Solid/Dashed/Beveled/Inset/Underline) and BorderWidth/Color/DashPattern are inherited from drawingAnnotationBase.

func NewCircleAnnotation

func NewCircleAnnotation(page *Page, rect Rectangle) *CircleAnnotation

NewCircleAnnotation builds an unbound circle annotation. Page must be non-nil. The ellipse is inscribed in the given rectangle.

func (*CircleAnnotation) AnnotationType

func (a *CircleAnnotation) AnnotationType() AnnotationType

func (*CircleAnnotation) BorderStyle

func (d *CircleAnnotation) BorderStyle() BorderStyle

BorderStyle returns the /BS/S style. Defaults to BorderSolid if absent.

func (*CircleAnnotation) BorderWidth

func (d *CircleAnnotation) BorderWidth() float64

BorderWidth returns the stroke line width. Reads /BS/W (preferred) or /Border[2] (legacy fallback). Defaults to 1 if neither is present.

func (*CircleAnnotation) DashPattern

func (d *CircleAnnotation) DashPattern() []float64

DashPattern returns a defensive copy of the dash array. Reads /BS/D (preferred) or falls back to the legacy /Border[3] entry per ISO 32000-1 §12.5.4. Returns nil if neither is present.

func (*CircleAnnotation) InteriorColor

func (a *CircleAnnotation) InteriorColor() *Color

InteriorColor returns the /IC fill color, or nil if absent.

func (*CircleAnnotation) RegenerateAppearance

func (a *CircleAnnotation) RegenerateAppearance()

RegenerateAppearance forces /AP/N to be rebuilt from current properties.

func (*CircleAnnotation) SetBorderStyle

func (d *CircleAnnotation) SetBorderStyle(s BorderStyle)

SetBorderStyle writes /BS/S using the PDF spec name codes.

func (*CircleAnnotation) SetBorderWidth

func (d *CircleAnnotation) SetBorderWidth(w float64)

SetBorderWidth writes /BS/W and clears any legacy /Border array.

func (*CircleAnnotation) SetColor

func (d *CircleAnnotation) SetColor(c *Color)

SetColor overrides annotationBase.SetColor to regenerate /AP/N after the stroke color changes.

func (*CircleAnnotation) SetDashPattern

func (d *CircleAnnotation) SetDashPattern(p []float64)

SetDashPattern writes /BS/D. The slice is copied; the caller may safely mutate p after this returns.

func (*CircleAnnotation) SetInteriorColor

func (a *CircleAnnotation) SetInteriorColor(c *Color)

SetInteriorColor writes /IC as an RGB array; nil removes the entry.

func (*CircleAnnotation) SetRect

func (d *CircleAnnotation) SetRect(r Rectangle)

SetRect overrides annotationBase.SetRect to regenerate /AP/N after the rectangle changes (the appearance stream's BBox is derived from /Rect).

type Color

type Color struct {
	R float64
	G float64
	B float64
	A float64
}

Color represents an RGBA color with values in [0, 1].

type ComboBoxField

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

ComboBoxField is a single-select dropdown choice field.

func (*ComboBoxField) AddOption

func (f *ComboBoxField) AddOption(o ChoiceOption)

AddOption appends a ChoiceOption to /Opt.

func (*ComboBoxField) FullName

func (b *ComboBoxField) FullName() string

func (*ComboBoxField) IsReadOnly

func (b *ComboBoxField) IsReadOnly() bool

func (*ComboBoxField) IsRequired

func (b *ComboBoxField) IsRequired() bool

func (*ComboBoxField) Options

func (f *ComboBoxField) Options() []ChoiceOption

func (*ComboBoxField) PageIndex

func (b *ComboBoxField) PageIndex() int

func (*ComboBoxField) PartialName

func (b *ComboBoxField) PartialName() string

func (*ComboBoxField) Rect

func (b *ComboBoxField) Rect() Rectangle

func (*ComboBoxField) RemoveOption

func (f *ComboBoxField) RemoveOption(index int) error

RemoveOption removes the option at index. Errors on out-of-range.

func (*ComboBoxField) Selected

func (f *ComboBoxField) Selected() int

func (*ComboBoxField) SetEditable

func (f *ComboBoxField) SetEditable(v bool)

SetEditable toggles bit 19 (/Ff Edit). When true, the combo accepts arbitrary user-typed text instead of restricting to /Opt entries.

func (*ComboBoxField) SetReadOnly

func (f *ComboBoxField) SetReadOnly(v bool)

SetReadOnly/SetRequired on choice types.

func (*ComboBoxField) SetRequired

func (f *ComboBoxField) SetRequired(v bool)

func (*ComboBoxField) SetSelected

func (f *ComboBoxField) SetSelected(index int) error

func (*ComboBoxField) SetValue

func (f *ComboBoxField) SetValue(s string) error

func (*ComboBoxField) Value

func (f *ComboBoxField) Value() string

type Destination

type Destination interface {
	DestinationType() DestinationType
	Page() *Page
}

Destination is the common interface for all explicit destinations. Per ISO 32000-1 §12.3.2.2.

type DestinationFit

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

DestinationFit — [page /Fit]

func NewDestinationFit

func NewDestinationFit(page *Page) *DestinationFit

func (*DestinationFit) DestinationType

func (d *DestinationFit) DestinationType() DestinationType

func (*DestinationFit) Page

func (d *DestinationFit) Page() *Page

type DestinationFitB

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

DestinationFitB — [page /FitB]

func NewDestinationFitB

func NewDestinationFitB(page *Page) *DestinationFitB

func (*DestinationFitB) DestinationType

func (d *DestinationFitB) DestinationType() DestinationType

func (*DestinationFitB) Page

func (d *DestinationFitB) Page() *Page

type DestinationFitBH

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

DestinationFitBH — [page /FitBH top]

func NewDestinationFitBH

func NewDestinationFitBH(page *Page, top float64) *DestinationFitBH

func NewDestinationFitBHUnchanged

func NewDestinationFitBHUnchanged(page *Page) *DestinationFitBH

func (*DestinationFitBH) DestinationType

func (d *DestinationFitBH) DestinationType() DestinationType

func (*DestinationFitBH) HasTop

func (d *DestinationFitBH) HasTop() bool

func (*DestinationFitBH) Page

func (d *DestinationFitBH) Page() *Page

func (*DestinationFitBH) Top

func (d *DestinationFitBH) Top() float64

type DestinationFitBV

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

DestinationFitBV — [page /FitBV left]

func NewDestinationFitBV

func NewDestinationFitBV(page *Page, left float64) *DestinationFitBV

func NewDestinationFitBVUnchanged

func NewDestinationFitBVUnchanged(page *Page) *DestinationFitBV

func (*DestinationFitBV) DestinationType

func (d *DestinationFitBV) DestinationType() DestinationType

func (*DestinationFitBV) HasLeft

func (d *DestinationFitBV) HasLeft() bool

func (*DestinationFitBV) Left

func (d *DestinationFitBV) Left() float64

func (*DestinationFitBV) Page

func (d *DestinationFitBV) Page() *Page

type DestinationFitH

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

DestinationFitH — [page /FitH top]

func NewDestinationFitH

func NewDestinationFitH(page *Page, top float64) *DestinationFitH

func NewDestinationFitHUnchanged

func NewDestinationFitHUnchanged(page *Page) *DestinationFitH

func (*DestinationFitH) DestinationType

func (d *DestinationFitH) DestinationType() DestinationType

func (*DestinationFitH) HasTop

func (d *DestinationFitH) HasTop() bool

func (*DestinationFitH) Page

func (d *DestinationFitH) Page() *Page

func (*DestinationFitH) Top

func (d *DestinationFitH) Top() float64

type DestinationFitR

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

DestinationFitR — [page /FitR left bottom right top]

func NewDestinationFitR

func NewDestinationFitR(page *Page, left, bottom, right, top float64) *DestinationFitR

func (*DestinationFitR) Bottom

func (d *DestinationFitR) Bottom() float64

func (*DestinationFitR) DestinationType

func (d *DestinationFitR) DestinationType() DestinationType

func (*DestinationFitR) Left

func (d *DestinationFitR) Left() float64

func (*DestinationFitR) Page

func (d *DestinationFitR) Page() *Page

func (*DestinationFitR) Right

func (d *DestinationFitR) Right() float64

func (*DestinationFitR) Top

func (d *DestinationFitR) Top() float64

type DestinationFitV

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

DestinationFitV — [page /FitV left]

func NewDestinationFitV

func NewDestinationFitV(page *Page, left float64) *DestinationFitV

func NewDestinationFitVUnchanged

func NewDestinationFitVUnchanged(page *Page) *DestinationFitV

func (*DestinationFitV) DestinationType

func (d *DestinationFitV) DestinationType() DestinationType

func (*DestinationFitV) HasLeft

func (d *DestinationFitV) HasLeft() bool

func (*DestinationFitV) Left

func (d *DestinationFitV) Left() float64

func (*DestinationFitV) Page

func (d *DestinationFitV) Page() *Page

type DestinationType

type DestinationType int

DestinationType identifies the destination flavor.

const (
	DestinationTypeXYZ DestinationType = iota
	DestinationTypeFit
	DestinationTypeFitH
	DestinationTypeFitV
	DestinationTypeFitR
	DestinationTypeFitB
	DestinationTypeFitBH
	DestinationTypeFitBV
	DestinationTypeNamed // named destination reference via collection lookup
)

type DestinationXYZ

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

DestinationXYZ — [page /XYZ left top zoom]. Any of left/top/zoom may be left "unchanged" (encoded as /null in PDF) via the Has* flags.

func NewDestinationXYZ

func NewDestinationXYZ(page *Page, left, top, zoom float64) *DestinationXYZ

func NewDestinationXYZUnchanged

func NewDestinationXYZUnchanged(page *Page, left float64, useLeft bool,
	top float64, useTop bool, zoom float64, useZoom bool) *DestinationXYZ

func (*DestinationXYZ) DestinationType

func (d *DestinationXYZ) DestinationType() DestinationType

func (*DestinationXYZ) HasLeft

func (d *DestinationXYZ) HasLeft() bool

func (*DestinationXYZ) HasTop

func (d *DestinationXYZ) HasTop() bool

func (*DestinationXYZ) HasZoom

func (d *DestinationXYZ) HasZoom() bool

func (*DestinationXYZ) Left

func (d *DestinationXYZ) Left() float64

func (*DestinationXYZ) Page

func (d *DestinationXYZ) Page() *Page

func (*DestinationXYZ) Top

func (d *DestinationXYZ) Top() float64

func (*DestinationXYZ) Zoom

func (d *DestinationXYZ) Zoom() float64

type Document

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

Document is a PDF document. Operations directly mutate the receiver.

func ImageToDocument

func ImageToDocument(path string, opts ...ImageToDocumentOptions) (*Document, error)

ImageToDocument creates a new Document with a single page containing the image. Page size is determined by image dimensions and DPI metadata (default 72 DPI).

func ImageToDocumentFromStream

func ImageToDocumentFromStream(r io.Reader, opts ...ImageToDocumentOptions) (*Document, error)

ImageToDocumentFromStream creates a new Document from an image reader. Format is detected by magic bytes.

func NewDocument

func NewDocument(width, height float64) *Document

NewDocument creates a single-page blank document with the given dimensions in points.

func NewDocumentFromFormat

func NewDocumentFromFormat(format PageFormat) *Document

NewDocumentFromFormat creates a single-page blank document using a predefined page format.

func Open

func Open(path string) (*Document, error)

Open opens a PDF file and returns a Document.

Example:

doc, err := asposepdf.Open("input.pdf")

func OpenStream

func OpenStream(r io.Reader) (*Document, error)

OpenStream reads a PDF from r and returns a Document. Returns ErrEncrypted if the input is password-protected; in that case retry with OpenStreamWithPassword.

Example:

doc, err := asposepdf.OpenStream(file)

func OpenStreamWithPassword

func OpenStreamWithPassword(r io.Reader, password string) (*Document, error)

OpenStreamWithPassword reads a password-protected PDF from r. Plain (unencrypted) PDFs are also accepted — the password is silently ignored — so this method is a safe drop-in for code that doesn't know up front whether the input is encrypted.

See OpenWithPassword for the edit-in-place preservation semantics.

func OpenWithPassword

func OpenWithPassword(path, password string) (*Document, error)

OpenWithPassword opens a password-protected PDF file. Use Open for unencrypted files. The password is tried as both user and owner password; either unlocks the document for editing.

Edit-in-place: the original /O, /U, /P, and /ID bytes from the file are preserved on the returned Document so a subsequent Save reuses them verbatim — BOTH the original user and owner passwords continue to work after re-save, and permissions are preserved bit-for-bit. If you call SetPassword, SetPermissions, SetEncryption, or RemoveEncryption after open, the preserved state is discarded and the document is re-encrypted from the new configuration.

Example:

doc, err := asposepdf.OpenWithPassword("locked.pdf", "secret")

func (*Document) AddBlankPage

func (d *Document) AddBlankPage(width, height float64) error

AddBlankPage appends a blank page to the end of the document.

func (*Document) AddBlankPageFromFormat

func (d *Document) AddBlankPageFromFormat(format PageFormat) error

AddBlankPageFromFormat appends a blank page using a predefined page format.

func (*Document) AddTextWatermark

func (d *Document) AddTextWatermark(text string, style TextStyle, pageNums ...int) error

AddTextWatermark adds a text watermark to selected pages of the document. If no page numbers are given, the watermark is applied to all pages. Page numbers are 1-based. The watermark covers the full page area (MediaBox). The caller controls all styling via TextStyle (rotation, behind, color, etc.).

func (*Document) Append

func (d *Document) Append(others ...*Document)

Append adds all pages from others to this document, merging their objects. Nil arguments are silently skipped.

Example:

doc1, _ := asposepdf.Open("part1.pdf")
doc2, _ := asposepdf.Open("part2.pdf")
doc1.Append(doc2)
doc1.Save("combined.pdf")

func (*Document) ApplyRedactions

func (d *Document) ApplyRedactions() error

ApplyRedactions destructively removes content (text glyphs, image XObjects, paths) inside every /Redact annotation's /QuadPoints (or /Rect if /QuadPoints is empty). Renders /OverlayText if set, then removes the redact annotations from the page.

Best-effort semantics: partial state on failure. Call ValidateRedactions first to surface parse errors before mutating.

func (*Document) ClearMetadata

func (d *Document) ClearMetadata()

ClearMetadata removes the Info dictionary entirely.

func (*Document) Extract

func (d *Document) Extract(ranges ...PageRange) (*Document, error)

Extract returns a new Document containing only the pages in the specified ranges. Ranges are 1-based and inclusive. Pages appear in the order the ranges are listed.

Example:

extracted, err := doc.Extract(asposepdf.PageRange{1, 3}, asposepdf.PageRange{5, 5})
extracted.Save("output.pdf")

func (*Document) ExtractImages

func (d *Document) ExtractImages() ([][]Image, error)

ExtractImages returns images from all pages (one slice per page).

func (*Document) ExtractText

func (d *Document) ExtractText() ([]string, error)

ExtractText returns the text content of each page. The returned slice has one entry per page (0-indexed).

func (*Document) ExtractTextWithLayout

func (d *Document) ExtractTextWithLayout() ([][]TextLine, error)

ExtractTextWithLayout returns structured text lines for each page. The returned slice has one entry per page (0-indexed).

func (*Document) Form

func (d *Document) Form() *Form

Form returns the document's AcroForm. Always non-nil; for a document without /AcroForm, an empty Form is returned (Fields() is empty, Field(name) returns nil, HasField returns false).

func (*Document) ImageInfos

func (d *Document) ImageInfos() ([][]ImageInfo, error)

ImageInfos returns image metadata for all pages (one slice per page) without decoding pixel data.

func (*Document) InsertBlankPage

func (d *Document) InsertBlankPage(position int, width, height float64) error

InsertBlankPage inserts a blank page at the given 1-based position. Existing pages at and after that position shift by one.

func (*Document) InsertBlankPageFromFormat

func (d *Document) InsertBlankPageFromFormat(position int, format PageFormat) error

InsertBlankPageFromFormat inserts a blank page at the given position using a predefined page format.

func (*Document) LoadFont

func (d *Document) LoadFont(path string) (Font, error)

LoadFont reads a TTF file, parses it, embeds it into the document, and returns a Font that can be used in TextStyle.Font. The full TTF is embedded without subsetting, so large fonts increase output size. The returned Font is bound to this document and must not be used with pages from other documents.

func (*Document) LoadFontFromStream

func (d *Document) LoadFontFromStream(r io.Reader) (Font, error)

LoadFontFromStream is like LoadFont but reads from an io.Reader.

func (*Document) Metadata

func (d *Document) Metadata() (Metadata, error)

Metadata returns the Info metadata from this document.

func (*Document) NamedDestinations

func (d *Document) NamedDestinations() *NamedDestinations

NamedDestinations returns the document's named-destination collection. Always non-nil. Lazy-initialized on first call from /Catalog/Names/Dests (modern PDF 1.2+ name tree) merged with legacy /Catalog/Dests; on collision the /Names/Dests entry wins.

Mirrors Aspose.PDF for .NET's Document.NamedDestinations property.

func (*Document) OptimizeImages

func (d *Document) OptimizeImages(opts OptimizeImageOptions) (int, error)

OptimizeImages optimizes all images in the document to reduce file size. Returns the number of images optimized.

func (*Document) Outlines

func (d *Document) Outlines() *OutlineItemCollection

Outlines returns the document's root outline collection. Always non-nil — an empty collection is returned for documents without outline content. Mirrors Aspose.PDF for .NET's Document.Outlines.

func (*Document) Page

func (d *Document) Page(n int) (*Page, error)

Page returns a live view of the page at the given 1-based number.

func (*Document) PageCount

func (d *Document) PageCount() int

PageCount returns the number of pages in the document.

func (*Document) Pages

func (d *Document) Pages() []*Page

Pages returns a live view of all pages in the document.

func (*Document) Permissions

func (d *Document) Permissions() (Permissions, bool)

Permissions returns the viewer-permission settings currently configured on this document, plus a boolean indicating whether the document is configured for encryption at all. For a document opened via OpenWithPassword, the permissions reflect the /P value read from the original file. Returns the zero Permissions and false for unencrypted documents.

func (*Document) RemoveEncryption

func (d *Document) RemoveEncryption()

RemoveEncryption clears any previously configured encryption (passwords and permissions) so the next Save produces a plaintext PDF. This is the way to "decrypt" an encrypted file via the public API: open with a password, call RemoveEncryption, save.

Example:

doc, _ := asposepdf.OpenWithPassword("locked.pdf", "secret")
doc.RemoveEncryption()
doc.Save("plain.pdf")

func (*Document) RemoveUnusedObjects

func (d *Document) RemoveUnusedObjects() int

RemoveUnusedObjects removes objects from the document that are not reachable from any page. Returns the number of objects removed.

func (*Document) Reorder

func (d *Document) Reorder(order []int) error

Reorder rearranges pages according to order, a slice of 1-based page numbers. Pages may be repeated or omitted.

Example — reverse a 4-page document:

err = doc.Reorder([]int{4, 3, 2, 1})

func (*Document) Rotate

func (d *Document) Rotate(angle RotationAngle, pageNums ...int) error

Rotate rotates selected pages clockwise by angle (Rotate90, Rotate180, or Rotate270). The rotation is added to any existing rotation. If no page numbers are given, all pages are rotated. Page numbers are 1-based.

Example:

err = doc.Rotate(asposepdf.Rotate90)        // rotate all pages
err = doc.Rotate(asposepdf.Rotate180, 1, 3) // rotate pages 1 and 3

func (*Document) Save

func (d *Document) Save(outputPath string) error

Save writes the document to outputPath.

func (*Document) SetEncryption

func (d *Document) SetEncryption(opts EncryptionOptions)

SetEncryption configures every encryption-related setting at once from an EncryptionOptions struct. It replaces any prior configuration set by SetPassword or SetPermissions. See EncryptionOptions for field-level semantics; nil Permissions means "grant all".

SetPassword and SetPermissions remain convenient for one-liner updates and compose cleanly either before or after SetEncryption.

Example:

doc.SetEncryption(asposepdf.EncryptionOptions{
    UserPassword:  "user",
    OwnerPassword: "owner",
    Permissions:   &asposepdf.Permissions{AllowPrint: true, AllowCopy: true},
})
doc.Save("restricted.pdf")

func (*Document) SetMetadata

func (d *Document) SetMetadata(meta Metadata)

SetMetadata replaces the document's Info dictionary with the given metadata. Empty string fields are omitted. This is a full replacement.

func (*Document) SetPassword

func (d *Document) SetPassword(userPassword, ownerPassword string)

SetPassword configures the document to be encrypted when saved. userPassword is required to open; ownerPassword controls permissions. If ownerPassword is empty, it defaults to userPassword.

Password encoding: The password bytes are passed unchanged to the PDF Standard Security Handler (RC4-128, V=2 R=3). For ASCII passwords this matches both the PDF specification and every major PDF viewer. For non-ASCII passwords the raw UTF-8 bytes are used, which is compatible with pypdf 6.x and Adobe Acrobat DC but may not be accepted by strictly legacy PDFDocEncoding-only viewers (e.g. Adobe Reader 9 and older). For international passwords with guaranteed interop, AES-256 (R=6) is the only complete solution — not yet supported by this library.

Example:

doc.SetPassword("secret", "")
doc.Save("encrypted.pdf")

func (*Document) SetPermissions

func (d *Document) SetPermissions(p Permissions)

SetPermissions configures what operations a viewer allows on the encrypted document (printing, copying, modifying, etc.). Permissions only take effect if the document is also encrypted — call SetPassword to set the user and owner passwords. If SetPermissions is never called, all operations are allowed by default, matching the historical behavior.

Example:

doc.SetPassword("secret", "owner-secret")
doc.SetPermissions(asposepdf.Permissions{AllowPrint: true, AllowCopy: true})
doc.Save("restricted.pdf")

func (*Document) SetRotation

func (d *Document) SetRotation(angle RotationAngle, pageNums ...int) error

SetRotation sets selected pages to exactly angle (Rotate0, Rotate90, Rotate180, or Rotate270), replacing any existing rotation. If no page numbers are given, all pages are affected. Page numbers are 1-based.

Example:

err = doc.SetRotation(asposepdf.Rotate90)        // set all pages to 90°
err = doc.SetRotation(asposepdf.Rotate0, 1, 3)  // reset pages 1 and 3 to 0°

func (*Document) Split

func (d *Document) Split() ([]*Document, error)

Split returns each page of the document as a separate *Document.

Example:

parts, err := doc.Split()
for i, p := range parts {
    p.Save(fmt.Sprintf("page%03d.pdf", i+1))
}

func (*Document) ValidateRedactions

func (d *Document) ValidateRedactions() error

ValidateRedactions performs a pre-flight dry-run parseability check on every page that has at least one RedactAnnotation. Returns the first content-stream parse error encountered, or nil if every redact-bearing page's content stream parses cleanly. Pages without redact annotations are not inspected.

Callers should invoke this before ApplyRedactions to surface malformed content streams up-front; ApplyRedactions has best-effort semantics and may leave partial state on failure.

func (*Document) WriteTo

func (d *Document) WriteTo(w io.Writer) (int64, error)

WriteTo writes the document to w. It implements io.WriterTo.

type EncryptionAlgorithm

type EncryptionAlgorithm int

EncryptionAlgorithm selects the cipher and security-handler revision used by (*Document).SetEncryption. The zero value is AES-128.

const (
	// EncryptionAlgAES128 — AES-128, Standard Security Handler V=4 R=4,
	// /CFM /AESV2. ISO 32000-1 §7.6.3.2. The default (zero value).
	EncryptionAlgAES128 EncryptionAlgorithm = iota

	// EncryptionAlgRC4_128 — RC4-128, Standard Security Handler V=2 R=3.
	// Legacy compatibility only — AES-128 is preferred for new documents.
	EncryptionAlgRC4_128

	// EncryptionAlgAES256 — AES-256, Standard Security Handler V=5 R=6,
	// /CFM /AESV3. ISO 32000-2 §7.6.4. Output PDF header is bumped to
	// %PDF-2.0; viewers older than Adobe Acrobat DC (~2015) may not
	// support PDF 2.0 documents.
	EncryptionAlgAES256
)

type EncryptionOptions

type EncryptionOptions struct {
	UserPassword  string
	OwnerPassword string
	Permissions   *Permissions
	Algorithm     EncryptionAlgorithm
}

EncryptionOptions bundles every knob that controls how a document is encrypted when saved. It is the unified structured input for (*Document).SetEncryption; the shorter SetPassword / SetPermissions methods remain available for the common case of one-line updates.

Zero values:

UserPassword  — no password (empty string is a valid "open without
                password" user-password under R<=4; the PDF still
                carries permissions).
OwnerPassword — defaults to UserPassword, matching Adobe behavior.
Permissions   — nil means "grant all" (the historical default);
                pass a non-nil pointer to restrict. Permissions{}
                (value, not pointer) deliberately denies everything,
                so the pointer distinguishes "omitted" from "deny".
Algorithm     — EncryptionAlgAES128 (zero value).

Example:

doc.SetEncryption(asposepdf.EncryptionOptions{
    UserPassword:  "user",
    OwnerPassword: "owner",
    Permissions:   &asposepdf.Permissions{AllowPrint: true, AllowCopy: true},
})
doc.Save("restricted.pdf")

type Field

type Field interface {
	PartialName() string
	FullName() string
	Value() string
	SetValue(s string) error
	IsReadOnly() bool
	IsRequired() bool
	PageIndex() int
	Rect() Rectangle
}

Field is the common interface implemented by every concrete form field type (TextBoxField, CheckboxField, RadioButtonField, etc.).

type FileAttachmentAnnotation

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

FileAttachmentAnnotation embeds a file in the document and shows an icon at the annotation's /Rect. Per ISO 32000-1 §12.5.6.15. No /AP is generated — viewers render the icon themselves based on /Name.

func NewFileAttachmentAnnotation

func NewFileAttachmentAnnotation(page *Page, position Point) *FileAttachmentAnnotation

NewFileAttachmentAnnotation builds an unbound file-attachment annotation. Page must be non-nil. The /Rect is auto-computed as a 24×24 pt square anchored at position (Acrobat icon convention).

Call SetFile or SetFileFromStream to embed file data; without that, the annotation has no /FS entry and viewers render an empty icon.

func (*FileAttachmentAnnotation) AnnotationType

func (a *FileAttachmentAnnotation) AnnotationType() AnnotationType

func (*FileAttachmentAnnotation) Color

func (b *FileAttachmentAnnotation) Color() *Color

Color returns the /C array as an RGB Color. Returns nil if /C is absent.

func (*FileAttachmentAnnotation) Contents

func (b *FileAttachmentAnnotation) Contents() string

Contents returns /Contents (the annotation body text).

func (*FileAttachmentAnnotation) FileBytes

func (a *FileAttachmentAnnotation) FileBytes() []byte

FileBytes returns a defensive copy of the embedded file's raw bytes. Nil if no file.

func (*FileAttachmentAnnotation) FileDescription

func (a *FileAttachmentAnnotation) FileDescription() string

FileDescription returns /Filespec/Desc. Empty if no description set.

func (*FileAttachmentAnnotation) FileMIMEType

func (a *FileAttachmentAnnotation) FileMIMEType() string

FileMIMEType returns the /Subtype on /EmbeddedFile (e.g. "application/pdf"). Empty if no file or /Subtype missing.

func (*FileAttachmentAnnotation) FileName

func (a *FileAttachmentAnnotation) FileName() string

FileName returns the displayed filename from /Filespec/F. Empty if no file.

func (*FileAttachmentAnnotation) FileSize

func (a *FileAttachmentAnnotation) FileSize() int

FileSize returns the size of the embedded file in bytes. Zero if no file.

func (*FileAttachmentAnnotation) HasFile

func (a *FileAttachmentAnnotation) HasFile() bool

HasFile returns true if SetFile or SetFileFromStream has been called successfully and not subsequently cleared. Stub for now — full implementation in Task 3.

func (*FileAttachmentAnnotation) Icon

Icon returns the /Name entry mapped to a FileAttachmentIcon. Returns FileAttachmentIconPaperclip (the spec default) if absent.

func (*FileAttachmentAnnotation) PageIndex

func (b *FileAttachmentAnnotation) PageIndex() int

PageIndex returns the 1-based index of the page this annotation lives on. 0 if the annotation is not yet attached or its /P doesn't resolve.

func (*FileAttachmentAnnotation) Rect

func (b *FileAttachmentAnnotation) Rect() Rectangle

Rect returns the annotation rectangle. Empty Rectangle if /Rect is missing or malformed.

func (*FileAttachmentAnnotation) RegenerateAppearance

func (a *FileAttachmentAnnotation) RegenerateAppearance()

RegenerateAppearance is a no-op for FileAttachmentAnnotation (no /AP — viewers render the icon themselves).

func (*FileAttachmentAnnotation) SetColor

func (b *FileAttachmentAnnotation) SetColor(c *Color)

SetColor writes /C as an RGB array; nil removes the entry.

func (*FileAttachmentAnnotation) SetContents

func (b *FileAttachmentAnnotation) SetContents(s string)

SetContents writes /Contents (the annotation body text); empty string removes the entry.

func (*FileAttachmentAnnotation) SetFile

func (a *FileAttachmentAnnotation) SetFile(path string) error

SetFile embeds the file at path as the annotation's attachment. The file's MIME type is auto-detected from the extension via mime.TypeByExtension; falls back to "application/octet-stream" for unknown extensions. Returns error on file-open or read failures.

func (*FileAttachmentAnnotation) SetFileDescription

func (a *FileAttachmentAnnotation) SetFileDescription(s string)

SetFileDescription writes /Filespec/Desc.

func (*FileAttachmentAnnotation) SetFileFromStream

func (a *FileAttachmentAnnotation) SetFileFromStream(r io.Reader, name string) error

SetFileFromStream is the io.Reader variant of SetFile. The caller supplies the displayed filename (used for /F entry and for MIME detection from extension).

func (*FileAttachmentAnnotation) SetIcon

SetIcon writes the /Name entry. Unknown is encoded as /Paperclip.

func (*FileAttachmentAnnotation) SetRect

func (b *FileAttachmentAnnotation) SetRect(r Rectangle)

SetRect writes the annotation rectangle.

func (*FileAttachmentAnnotation) SetTitle

func (b *FileAttachmentAnnotation) SetTitle(s string)

SetTitle writes /T (the annotation author / reviewer name); empty string removes the entry.

func (*FileAttachmentAnnotation) Title

func (b *FileAttachmentAnnotation) Title() string

Title returns /T (the annotation author / reviewer name).

type FileAttachmentIcon

type FileAttachmentIcon int

FileAttachmentIcon names per ISO 32000-1 §12.5.6.15 Table 178.

const (
	FileAttachmentIconUnknown FileAttachmentIcon = iota
	FileAttachmentIconGraph
	FileAttachmentIconPaperclip // PDF default
	FileAttachmentIconPushPin
	FileAttachmentIconTag
)

type Font

type Font interface {
	// BaseFont returns the PostScript name, e.g. "Helvetica" or "ArialMT".
	BaseFont() string
	// IsEmbedded reports whether font data is embedded in the PDF (true for TTF, false for standard 14).
	IsEmbedded() bool
}

Font is implemented by standard 14 fonts and embedded TTF fonts. Use the package-level vars (FontHelvetica, ...) or LoadFont to obtain a Font.

var (
	FontHelvetica            Font = standardFont{/* contains filtered or unexported fields */}
	FontHelveticaBold        Font = standardFont{/* contains filtered or unexported fields */}
	FontHelveticaOblique     Font = standardFont{/* contains filtered or unexported fields */}
	FontHelveticaBoldOblique Font = standardFont{/* contains filtered or unexported fields */}
	FontTimesRoman           Font = standardFont{/* contains filtered or unexported fields */}
	FontTimesBold            Font = standardFont{/* contains filtered or unexported fields */}
	FontTimesItalic          Font = standardFont{/* contains filtered or unexported fields */}
	FontTimesBoldItalic      Font = standardFont{/* contains filtered or unexported fields */}
	FontCourier              Font = standardFont{/* contains filtered or unexported fields */}
	FontCourierBold          Font = standardFont{/* contains filtered or unexported fields */}
	FontCourierOblique       Font = standardFont{/* contains filtered or unexported fields */}
	FontCourierBoldOblique   Font = standardFont{/* contains filtered or unexported fields */}
	FontSymbol               Font = standardFont{/* contains filtered or unexported fields */}
	FontZapfDingbats         Font = standardFont{/* contains filtered or unexported fields */}
)

Standard 14 PDF fonts. These Fonts need not be embedded — every PDF viewer is required to render them.

func FindFont

func FindFont(name string) (Font, error)

FindFont returns a standard 14 Font by PostScript name. The lookup is case-insensitive. Returns an error if the name is not a standard 14 name.

type Form

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

Form is the document's AcroForm view. Always non-nil — for documents without an /AcroForm dict, Form is empty (no fields, no flags). Field instances returned from Form are live handles over the underlying pdfDict; SetValue mutates in place and the next Save writes the new state.

func (*Form) AddCheckbox

func (f *Form) AddCheckbox(pageNum int, rect Rectangle, name string) (*CheckboxField, error)

AddCheckbox creates a checkbox widget on pageNum with the given rectangle and field name. Default state is unchecked (/V = /Off). The widget's /AP/N has two appearance states: "/Yes" (export name for checked) and "/Off". Callers can call SetChecked(true) on the returned handle to flip state and ensure /V and /AS are in sync.

Errors on duplicate name, invalid pageNum, or empty name.

func (*Form) AddComboBox

func (f *Form) AddComboBox(pageNum int, rect Rectangle, name string, options []ChoiceOption) (*ComboBoxField, error)

AddComboBox creates a single-select dropdown choice field. The caller can pre-populate options or pass an empty slice and call AddOption later. Field is non-editable by default; SetEditable(true) flips bit 19.

func (*Form) AddListBox

func (f *Form) AddListBox(pageNum int, rect Rectangle, name string, options []ChoiceOption) (*ListBoxField, error)

AddListBox creates a single-select list field. SetMultiSelect(true) on the returned handle enables multi-selection (bit 22).

func (*Form) AddPushButton

func (f *Form) AddPushButton(pageNum int, rect Rectangle, name string, caption string) (*ButtonField, error)

AddPushButton creates a non-toggling button. The caption is stored in /MK/CA and rendered by viewers as the button label. Push buttons have no value semantics — Value() returns "", SetValue returns an error.

func (*Form) AddRadioGroup

func (f *Form) AddRadioGroup(name string, items []RadioItem) (*RadioButtonField, error)

AddRadioGroup creates a radio-button parent field plus one widget per item. Items may live on different pages. Export values must be unique within the group.

func (*Form) AddTextField

func (f *Form) AddTextField(pageNum int, rect Rectangle, name string) (*TextBoxField, error)

AddTextField creates a single-line text input on pageNum with the given rectangle and field name, auto-creating /AcroForm and the default Helvetica font resource if needed. Returns the live *TextBoxField handle. Errors on duplicate name, invalid pageNum, or empty name.

func (*Form) Field

func (f *Form) Field(name string) Field

Field returns the leaf field by FullName, or nil if no such field exists. Mirrors the C# `doc.Form["name"]` indexer pattern.

func (*Form) Fields

func (f *Form) Fields() []Field

Fields returns all leaf form fields as a flat slice. Field tree hierarchy is resolved internally; callers see only the leaves whose FullName carries the dotted path.

func (*Form) HasField

func (f *Form) HasField(name string) bool

HasField reports whether a leaf field with the given FullName exists.

func (*Form) NeedAppearances

func (f *Form) NeedAppearances() bool

NeedAppearances reports whether /AcroForm/NeedAppearances is true, which tells viewers to regenerate cached /AP appearance streams when displaying form fields.

func (*Form) RemoveField

func (f *Form) RemoveField(name string) bool

RemoveField removes the named field (and all its widget annotations) from /AcroForm/Fields and from each affected page's /Annots. The underlying pdfObjects are deleted from the document's object map. Returns true if the field was found and removed; false otherwise.

For combined-pattern fields (TextField, Checkbox, ComboBox, ListBox, PushButton), the single dict is both the field and its widget: it is removed from /Fields and from the owning page's /Annots.

For radio groups, the parent dict is removed from /Fields, and each widget kid is removed from its respective page's /Annots.

After removal, any *Field handles previously returned for this field are dangling and must not be used.

func (*Form) SetNeedAppearances

func (f *Form) SetNeedAppearances(v bool)

SetNeedAppearances toggles /AcroForm/NeedAppearances. Any value- changing call (SetValue, SetChecked, SetSelected) auto-sets this to true; an explicit call here is needed only to disable the flag.

On a Document with no /AcroForm dict, calling this with true creates a new /AcroForm dict in the catalog so the flag is preserved on Save.

type FormFieldType

type FormFieldType int

FormFieldType identifies the kind of form field. Returned by FieldType().

const (
	FormFieldTypeUnknown FormFieldType = iota
	FormFieldTypeText
	FormFieldTypeCheckbox
	FormFieldTypeRadioButton
	FormFieldTypePushButton
	FormFieldTypeComboBox
	FormFieldTypeListBox
)

func FieldType

func FieldType(f Field) FormFieldType

FieldType returns the concrete kind of f. Convenience helper for callers who want a switch on type without the type-assertion form.

type FreeTextAnnotation

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

FreeTextAnnotation displays text directly on the page, rendered into /AP/N using an embedded font. Per ISO 32000-1 §12.5.6.6.

Supports /BS border, /BG background, /Q alignment via TextStyle, plus /IT intent (FreeText / FreeTextCallout / FreeTextTypewriter), /CL callout points, /BE border effect (cloudy), and /RD inner rect for callouts. Full feature set added incrementally across Tasks 9-17.

func NewFreeTextAnnotation

func NewFreeTextAnnotation(page *Page, rect Rectangle, contents string, style TextStyle) *FreeTextAnnotation

NewFreeTextAnnotation builds an unbound FreeText annotation. Page must be non-nil. Contents is the text body. style configures font, size, color, alignment, and background — serialized to /DA, /Q, /BG.

func (*FreeTextAnnotation) AnnotationType

func (a *FreeTextAnnotation) AnnotationType() AnnotationType

func (*FreeTextAnnotation) BorderEffect

func (a *FreeTextAnnotation) BorderEffect() BorderEffect

BorderEffect returns the /BE/S entry as a BorderEffect. Returns BorderEffectNone if /BE is absent or unrecognized.

func (*FreeTextAnnotation) BorderEffectIntensity

func (a *FreeTextAnnotation) BorderEffectIntensity() float64

BorderEffectIntensity returns the /BE/I entry. Returns 0 if absent. Default visual intensity for cloudy border is 1.0 — caller of SetBorderEffect typically also sets intensity via SetBorderEffectIntensity.

func (*FreeTextAnnotation) BorderStyle

func (d *FreeTextAnnotation) BorderStyle() BorderStyle

BorderStyle returns the /BS/S style. Defaults to BorderSolid if absent.

func (*FreeTextAnnotation) BorderWidth

func (d *FreeTextAnnotation) BorderWidth() float64

BorderWidth returns the stroke line width. Reads /BS/W (preferred) or /Border[2] (legacy fallback). Defaults to 1 if neither is present.

func (*FreeTextAnnotation) CalloutPoints

func (a *FreeTextAnnotation) CalloutPoints() []Point

CalloutPoints returns the /CL knee + endpoint points (page space). Returns nil if /CL is absent or malformed. Format: 2-element slice (knee, endpoint) for /CL = [x1 y1 x2 y2]; 3-element slice (knee1, knee2, endpoint) for /CL = [x1 y1 x2 y2 x3 y3].

func (*FreeTextAnnotation) Contents

func (a *FreeTextAnnotation) Contents() string

Contents returns the /Contents text body. Overrides annotationBase to ensure the value is always read from the dict.

func (*FreeTextAnnotation) DashPattern

func (d *FreeTextAnnotation) DashPattern() []float64

DashPattern returns a defensive copy of the dash array. Reads /BS/D (preferred) or falls back to the legacy /Border[3] entry per ISO 32000-1 §12.5.4. Returns nil if neither is present.

func (*FreeTextAnnotation) EndLineEnding

func (a *FreeTextAnnotation) EndLineEnding() LineEndingStyle

EndLineEnding returns the /LE entry as a LineEndingStyle. Returns LineEndingNone if absent or unrecognized.

func (*FreeTextAnnotation) InnerRect

func (a *FreeTextAnnotation) InnerRect() Rectangle

InnerRect returns the inner text rectangle derived from /RD entry. If /RD is absent, returns the full annotation /Rect.

func (*FreeTextAnnotation) Intent

func (a *FreeTextAnnotation) Intent() FreeTextIntent

Intent returns the /IT entry mapped to a FreeTextIntent. Returns FreeTextIntentFreeText (the spec default) if /IT is absent.

func (*FreeTextAnnotation) RegenerateAppearance

func (a *FreeTextAnnotation) RegenerateAppearance()

RegenerateAppearance forces /AP/N to be rebuilt from current state.

func (*FreeTextAnnotation) SetBorderEffect

func (a *FreeTextAnnotation) SetBorderEffect(e BorderEffect)

SetBorderEffect writes /BE/S. The default (BorderEffectNone) removes the /BE entry to keep the dict minimal.

func (*FreeTextAnnotation) SetBorderEffectIntensity

func (a *FreeTextAnnotation) SetBorderEffectIntensity(i float64)

SetBorderEffectIntensity writes /BE/I (cloud intensity, typically 0-2). Setting to 0 removes the /I entry; if /BE becomes empty, removes /BE entirely.

func (*FreeTextAnnotation) SetBorderStyle

func (d *FreeTextAnnotation) SetBorderStyle(s BorderStyle)

SetBorderStyle writes /BS/S using the PDF spec name codes.

func (*FreeTextAnnotation) SetBorderWidth

func (d *FreeTextAnnotation) SetBorderWidth(w float64)

SetBorderWidth writes /BS/W and clears any legacy /Border array.

func (*FreeTextAnnotation) SetCalloutPoints

func (a *FreeTextAnnotation) SetCalloutPoints(pts []Point)

SetCalloutPoints writes /CL (must be 2 or 3 points; otherwise the call is a no-op). Auto-sets Intent to FreeTextIntentCallout. The caller passes points in page-space coordinates; round-trip preserves them as written.

func (*FreeTextAnnotation) SetColor

func (d *FreeTextAnnotation) SetColor(c *Color)

SetColor overrides annotationBase.SetColor to regenerate /AP/N after the stroke color changes.

func (*FreeTextAnnotation) SetContents

func (a *FreeTextAnnotation) SetContents(s string)

SetContents writes /Contents and regenerates /AP/N (the rendered text content depends on Contents).

func (*FreeTextAnnotation) SetDashPattern

func (d *FreeTextAnnotation) SetDashPattern(p []float64)

SetDashPattern writes /BS/D. The slice is copied; the caller may safely mutate p after this returns.

func (*FreeTextAnnotation) SetEndLineEnding

func (a *FreeTextAnnotation) SetEndLineEnding(s LineEndingStyle)

SetEndLineEnding writes /LE for the callout endpoint shape.

func (*FreeTextAnnotation) SetInnerRect

func (a *FreeTextAnnotation) SetInnerRect(inner Rectangle)

SetInnerRect writes /RD computed from the difference between the outer /Rect and the supplied inner rect (page-space). Negative distances are clamped to 0 to keep /RD spec-valid.

func (*FreeTextAnnotation) SetIntent

func (a *FreeTextAnnotation) SetIntent(i FreeTextIntent)

SetIntent writes the /IT entry. The default (FreeTextIntentFreeText) removes the entry to keep the dict minimal.

func (*FreeTextAnnotation) SetRect

func (d *FreeTextAnnotation) SetRect(r Rectangle)

SetRect overrides annotationBase.SetRect to regenerate /AP/N after the rectangle changes (the appearance stream's BBox is derived from /Rect).

func (*FreeTextAnnotation) SetTextStyle

func (a *FreeTextAnnotation) SetTextStyle(s TextStyle)

SetTextStyle writes the style as /DA + /Q + /BG and regenerates /AP/N. VAlign is preserved in-memory (not stored in the PDF dict) and honored by the /AP/N renderer.

func (*FreeTextAnnotation) TextStyle

func (a *FreeTextAnnotation) TextStyle() TextStyle

TextStyle returns the text style reconstructed from /DA + /Q + /BG. Only fields that round-trip through PDF dict entries are populated: Font, Size, Color, Background, HAlign. Other fields (LineSpacing, Underline, Strikethrough, Rotation, VAlign) are rendering hints honored when /AP/N is generated; they don't survive a round-trip through the dict.

type FreeTextIntent

type FreeTextIntent int

FreeTextIntent per ISO 32000-1 §12.5.6.6 /IT entry. Defaults to FreeTextIntentFreeText (plain text in a rectangle).

const (
	FreeTextIntentFreeText   FreeTextIntent = iota // /FreeText
	FreeTextIntentCallout                          // /FreeTextCallout
	FreeTextIntentTypewriter                       // /FreeTextTypeWriter
)

type GenericAnnotation

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

GenericAnnotation is the catch-all surface for /Subtype values this release does not yet model (Stamp, FreeText, Ink, etc.). It exposes only the base Annotation accessors — callers can detect it via AnnotationType() == AnnotationTypeUnknown.

func (*GenericAnnotation) AnnotationType

func (a *GenericAnnotation) AnnotationType() AnnotationType

func (*GenericAnnotation) Color

func (b *GenericAnnotation) Color() *Color

Color returns the /C array as an RGB Color. Returns nil if /C is absent.

func (*GenericAnnotation) Contents

func (b *GenericAnnotation) Contents() string

Contents returns /Contents (the annotation body text).

func (*GenericAnnotation) PageIndex

func (b *GenericAnnotation) PageIndex() int

PageIndex returns the 1-based index of the page this annotation lives on. 0 if the annotation is not yet attached or its /P doesn't resolve.

func (*GenericAnnotation) Rect

func (b *GenericAnnotation) Rect() Rectangle

Rect returns the annotation rectangle. Empty Rectangle if /Rect is missing or malformed.

func (*GenericAnnotation) SetColor

func (b *GenericAnnotation) SetColor(c *Color)

SetColor writes /C as an RGB array; nil removes the entry.

func (*GenericAnnotation) SetContents

func (b *GenericAnnotation) SetContents(s string)

SetContents writes /Contents (the annotation body text); empty string removes the entry.

func (*GenericAnnotation) SetRect

func (b *GenericAnnotation) SetRect(r Rectangle)

SetRect writes the annotation rectangle.

func (*GenericAnnotation) SetTitle

func (b *GenericAnnotation) SetTitle(s string)

SetTitle writes /T (the annotation author / reviewer name); empty string removes the entry.

func (*GenericAnnotation) Title

func (b *GenericAnnotation) Title() string

Title returns /T (the annotation author / reviewer name).

type GoToAction

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

GoToAction navigates to a page within the same document. PageNum is 1-based; Top is the y-coordinate of the destination view in default user space.

func NewGoToAction

func NewGoToAction(pageNum int, top float64) *GoToAction

NewGoToAction builds a /GoTo action targeting the given 1-based page and a y-coordinate (top of view).

func (*GoToAction) ActionType

func (a *GoToAction) ActionType() ActionType

func (*GoToAction) PageNum

func (a *GoToAction) PageNum() int

PageNum returns the 1-based destination page number.

func (*GoToAction) SetPageNum

func (a *GoToAction) SetPageNum(n int)

SetPageNum updates the destination page number (1-based).

func (*GoToAction) SetTop

func (a *GoToAction) SetTop(t float64)

SetTop updates the y-coordinate of the destination view.

func (*GoToAction) Top

func (a *GoToAction) Top() float64

Top returns the y-coordinate of the destination view.

type GoToURIAction

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

GoToURIAction opens a URI in the user's default handler (typically a web browser).

func NewGoToURIAction

func NewGoToURIAction(uri string) *GoToURIAction

NewGoToURIAction builds a /URI action. Empty URI is permitted but usually not what callers want.

func (*GoToURIAction) ActionType

func (a *GoToURIAction) ActionType() ActionType

func (*GoToURIAction) SetURI

func (a *GoToURIAction) SetURI(uri string)

SetURI updates the destination URI.

func (*GoToURIAction) URI

func (a *GoToURIAction) URI() string

URI returns the destination URI.

type HAlign

type HAlign int

HAlign specifies horizontal text alignment within a rectangle.

const (
	HAlignLeft HAlign = iota // default
	HAlignCenter
	HAlignRight
)

type HighlightAnnotation

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

HighlightAnnotation marks a region with semi-transparent highlight color. Renders natively in spec-conforming viewers from /Subtype + /QuadPoints + /C — no /AP needed.

func NewHighlightAnnotation

func NewHighlightAnnotation(page *Page, rect Rectangle) *HighlightAnnotation

NewHighlightAnnotation builds an unbound highlight annotation. Page must be non-nil.

func (*HighlightAnnotation) AnnotationType

func (a *HighlightAnnotation) AnnotationType() AnnotationType

func (*HighlightAnnotation) Color

func (b *HighlightAnnotation) Color() *Color

Color returns the /C array as an RGB Color. Returns nil if /C is absent.

func (*HighlightAnnotation) Contents

func (b *HighlightAnnotation) Contents() string

Contents returns /Contents (the annotation body text).

func (*HighlightAnnotation) PageIndex

func (b *HighlightAnnotation) PageIndex() int

PageIndex returns the 1-based index of the page this annotation lives on. 0 if the annotation is not yet attached or its /P doesn't resolve.

func (*HighlightAnnotation) QuadPoints

func (a *HighlightAnnotation) QuadPoints() []QuadPoint

QuadPoints returns the array of quads describing the selection. Returns nil if /QuadPoints is absent or its array length is not a multiple of 8 (malformed).

func (*HighlightAnnotation) Rect

func (b *HighlightAnnotation) Rect() Rectangle

Rect returns the annotation rectangle. Empty Rectangle if /Rect is missing or malformed.

func (*HighlightAnnotation) SetColor

func (b *HighlightAnnotation) SetColor(c *Color)

SetColor writes /C as an RGB array; nil removes the entry.

func (*HighlightAnnotation) SetContents

func (b *HighlightAnnotation) SetContents(s string)

SetContents writes /Contents (the annotation body text); empty string removes the entry.

func (*HighlightAnnotation) SetQuadPoints

func (a *HighlightAnnotation) SetQuadPoints(qp []QuadPoint)

SetQuadPoints writes /QuadPoints. nil or empty slice removes the entry.

func (*HighlightAnnotation) SetRect

func (b *HighlightAnnotation) SetRect(r Rectangle)

SetRect writes the annotation rectangle.

func (*HighlightAnnotation) SetTitle

func (b *HighlightAnnotation) SetTitle(s string)

SetTitle writes /T (the annotation author / reviewer name); empty string removes the entry.

func (*HighlightAnnotation) Title

func (b *HighlightAnnotation) Title() string

Title returns /T (the annotation author / reviewer name).

type Image

type Image struct {
	Data       []byte          // encoded image bytes (PNG or JPEG)
	Format     ImageFormat     // output format
	Width      int             // pixel width
	Height     int             // pixel height
	BPC        int             // bits per component (original)
	ColorSpace ImageColorSpace // original PDF color space
	X, Y       float64         // position on page (lower-left, in points)
	PageWidth  float64         // display width on page (in points)
	PageHeight float64         // display height on page (in points)
	Inline     bool            // true if from inline image (BI/ID/EI)
}

Image holds an extracted image with its encoded data and metadata.

func (*Image) Save

func (img *Image) Save(path string) error

Save writes the image data to a file.

func (*Image) WriteTo

func (img *Image) WriteTo(w io.Writer) (int64, error)

WriteTo writes the image data to w.

type ImageColorSpace

type ImageColorSpace int

ImageColorSpace describes the original color space of the image in the PDF.

const (
	ColorSpaceDeviceRGB ImageColorSpace = iota
	ColorSpaceDeviceGray
	ColorSpaceDeviceCMYK
	ColorSpaceIndexed
	ColorSpaceICCBased
)

type ImageFormat

type ImageFormat int

ImageFormat describes the output format of an extracted image.

const (
	ImageFormatPNG ImageFormat = iota
	ImageFormatJPEG
)

type ImageInfo

type ImageInfo struct {
	Width      int             // pixel width
	Height     int             // pixel height
	BPC        int             // bits per component (original)
	ColorSpace ImageColorSpace // original PDF color space
	Format     ImageFormat     // output format (PNG or JPEG)
	X, Y       float64         // position on page (lower-left, in points)
	PageWidth  float64         // display width on page (in points)
	PageHeight float64         // display height on page (in points)
	Inline     bool            // true if from inline image (BI/ID/EI)
	Name       string          // XObject name (e.g. "/Im0"); empty for inline
	// contains filtered or unexported fields
}

ImageInfo holds metadata about an image found on a page without decoding pixel data. Call Extract() to perform the actual decoding and get the full Image.

func (*ImageInfo) Extract

func (info *ImageInfo) Extract() (*Image, error)

Extract decodes the image and returns the full Image with pixel data.

func (*ImageInfo) Remove

func (info *ImageInfo) Remove() error

Remove removes the image from the page. Deletes the XObject reference from page resources and the drawing operators from the content stream. The underlying XObject remains in the document's object store (safe for shared references). Images inside Form XObjects are not supported; only page-level images can be removed.

func (*ImageInfo) Replace

func (info *ImageInfo) Replace(path string) error

Replace replaces the image data with a new image from a file. Format is detected by magic bytes (JPEG, PNG). Dimensions may change. Position and size on the page remain unchanged.

func (*ImageInfo) ReplaceFromStream

func (info *ImageInfo) ReplaceFromStream(r io.Reader) error

ReplaceFromStream replaces the image data with a new image from a reader.

type ImageToDocumentOptions

type ImageToDocumentOptions struct {
	PageWidth    float64 // explicit page size in points; 0 = auto from image
	PageHeight   float64
	MarginLeft   float64
	MarginRight  float64
	MarginTop    float64
	MarginBottom float64
}

ImageToDocumentOptions controls page sizing for ImageToDocument.

type InkAnnotation

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

InkAnnotation draws a series of free-form strokes — typically used to represent handwritten ink. Each stroke is a sequence of points rendered as a polyline; in Task 16 strokes with 3+ points get Catmull-Rom smoothing for visual quality.

func NewInkAnnotation

func NewInkAnnotation(page *Page, strokes [][]Point) *InkAnnotation

NewInkAnnotation builds an unbound ink annotation. Page must be non-nil. Each inner slice is one continuous stroke. The /Rect entry is auto-computed as the bounding box of all stroke points plus padding equal to BorderWidth.

func (*InkAnnotation) AddStroke

func (a *InkAnnotation) AddStroke(stroke []Point)

AddStroke appends a single stroke to the annotation. Convenience for incremental construction.

func (*InkAnnotation) AnnotationType

func (a *InkAnnotation) AnnotationType() AnnotationType

func (*InkAnnotation) BorderStyle

func (d *InkAnnotation) BorderStyle() BorderStyle

BorderStyle returns the /BS/S style. Defaults to BorderSolid if absent.

func (*InkAnnotation) BorderWidth

func (d *InkAnnotation) BorderWidth() float64

BorderWidth returns the stroke line width. Reads /BS/W (preferred) or /Border[2] (legacy fallback). Defaults to 1 if neither is present.

func (*InkAnnotation) DashPattern

func (d *InkAnnotation) DashPattern() []float64

DashPattern returns a defensive copy of the dash array. Reads /BS/D (preferred) or falls back to the legacy /Border[3] entry per ISO 32000-1 §12.5.4. Returns nil if neither is present.

func (*InkAnnotation) RegenerateAppearance

func (a *InkAnnotation) RegenerateAppearance()

RegenerateAppearance forces /AP/N to be rebuilt from current properties.

func (*InkAnnotation) SetBorderStyle

func (d *InkAnnotation) SetBorderStyle(s BorderStyle)

SetBorderStyle writes /BS/S using the PDF spec name codes.

func (*InkAnnotation) SetBorderWidth

func (a *InkAnnotation) SetBorderWidth(w float64)

SetBorderWidth overrides drawingAnnotationBase.SetBorderWidth so /Rect (whose padding scales with BorderWidth) is recomputed before /AP/N regenerates — single-pass /BBox sync.

func (*InkAnnotation) SetColor

func (d *InkAnnotation) SetColor(c *Color)

SetColor overrides annotationBase.SetColor to regenerate /AP/N after the stroke color changes.

func (*InkAnnotation) SetDashPattern

func (d *InkAnnotation) SetDashPattern(p []float64)

SetDashPattern writes /BS/D. The slice is copied; the caller may safely mutate p after this returns.

func (*InkAnnotation) SetRect

func (d *InkAnnotation) SetRect(r Rectangle)

SetRect overrides annotationBase.SetRect to regenerate /AP/N after the rectangle changes (the appearance stream's BBox is derived from /Rect).

func (*InkAnnotation) SetStrokes

func (a *InkAnnotation) SetStrokes(strokes [][]Point)

SetStrokes writes /InkList. The slices are deep-copied; the caller may safely mutate after this returns.

func (*InkAnnotation) Strokes

func (a *InkAnnotation) Strokes() [][]Point

Strokes returns a deep copy of /InkList. Mutating the result does not affect the annotation.

type JavaScriptAction

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

JavaScriptAction holds a JavaScript snippet attached to an annotation. This subepic supports parsing JS actions read from existing PDFs.

func NewJavaScriptAction

func NewJavaScriptAction(script string) *JavaScriptAction

NewJavaScriptAction builds a /JavaScript action carrying the given script. The action runs when its parent annotation is activated (clicked) by a viewer that supports JavaScript.

SECURITY WARNING: Embedding JavaScript in a PDF can introduce security risks for recipients. Scripts execute in the viewer's JavaScript engine context with access to form fields, navigation, and viewer-specific APIs (varies by viewer). Use only with scripts you authored or audited; never embed user-supplied JS without careful review.

JavaScript actions are commonly disabled by default in viewers (Acrobat: Preferences > Security > "Enable JavaScript") so behavior is not guaranteed across all rendering environments.

func (*JavaScriptAction) ActionType

func (a *JavaScriptAction) ActionType() ActionType

func (*JavaScriptAction) Script

func (a *JavaScriptAction) Script() string

type LineAnnotation

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

LineAnnotation draws a straight line between two points, with optional line endings on each end (arrows, circles, etc. — added in Task 14). The /Rect entry is auto-computed from the endpoints + padding for line endings.

func NewLineAnnotation

func NewLineAnnotation(page *Page, start, end Point) *LineAnnotation

NewLineAnnotation builds an unbound line annotation. Page must be non-nil. The /Rect is auto-computed as the bounding box of the line plus padding equal to 9 × BorderWidth (Acrobat convention) on each side.

func (*LineAnnotation) AnnotationType

func (a *LineAnnotation) AnnotationType() AnnotationType

func (*LineAnnotation) BorderStyle

func (d *LineAnnotation) BorderStyle() BorderStyle

BorderStyle returns the /BS/S style. Defaults to BorderSolid if absent.

func (*LineAnnotation) BorderWidth

func (d *LineAnnotation) BorderWidth() float64

BorderWidth returns the stroke line width. Reads /BS/W (preferred) or /Border[2] (legacy fallback). Defaults to 1 if neither is present.

func (*LineAnnotation) DashPattern

func (d *LineAnnotation) DashPattern() []float64

DashPattern returns a defensive copy of the dash array. Reads /BS/D (preferred) or falls back to the legacy /Border[3] entry per ISO 32000-1 §12.5.4. Returns nil if neither is present.

func (*LineAnnotation) End

func (a *LineAnnotation) End() Point

End returns the line's end point.

func (*LineAnnotation) EndLineEnding

func (a *LineAnnotation) EndLineEnding() LineEndingStyle

EndLineEnding returns the style applied to the end of the line.

func (*LineAnnotation) InteriorColor

func (a *LineAnnotation) InteriorColor() *Color

InteriorColor returns the /IC fill color (used for filled line endings: ClosedArrow, RClosedArrow, Square, Circle, Diamond). Returns nil if absent.

func (*LineAnnotation) LeaderLineLength

func (a *LineAnnotation) LeaderLineLength() float64

LeaderLineLength returns the /LL value (0 if absent). Used for dimension-line annotations where the line is offset from the measured points by this much.

func (*LineAnnotation) RegenerateAppearance

func (a *LineAnnotation) RegenerateAppearance()

RegenerateAppearance forces /AP/N to be rebuilt from current properties.

func (*LineAnnotation) SetBorderStyle

func (d *LineAnnotation) SetBorderStyle(s BorderStyle)

SetBorderStyle writes /BS/S using the PDF spec name codes.

func (*LineAnnotation) SetBorderWidth

func (a *LineAnnotation) SetBorderWidth(w float64)

SetBorderWidth overrides drawingAnnotationBase.SetBorderWidth so /Rect (which depends on BorderWidth via line-ending padding) is recomputed before /AP/N regenerates — ensuring the appearance stream's /BBox matches the new bounds in a single pass.

func (*LineAnnotation) SetColor

func (d *LineAnnotation) SetColor(c *Color)

SetColor overrides annotationBase.SetColor to regenerate /AP/N after the stroke color changes.

func (*LineAnnotation) SetDashPattern

func (d *LineAnnotation) SetDashPattern(p []float64)

SetDashPattern writes /BS/D. The slice is copied; the caller may safely mutate p after this returns.

func (*LineAnnotation) SetEnd

func (a *LineAnnotation) SetEnd(p Point)

SetEnd updates the line's end point and recomputes /Rect.

func (*LineAnnotation) SetEndLineEnding

func (a *LineAnnotation) SetEndLineEnding(s LineEndingStyle)

SetEndLineEnding sets the end-side line-ending style.

func (*LineAnnotation) SetInteriorColor

func (a *LineAnnotation) SetInteriorColor(c *Color)

SetInteriorColor writes /IC as an RGB array; nil removes the entry.

func (*LineAnnotation) SetLeaderLineLength

func (a *LineAnnotation) SetLeaderLineLength(l float64)

SetLeaderLineLength writes /LL. Zero removes the entry.

func (*LineAnnotation) SetRect

func (d *LineAnnotation) SetRect(r Rectangle)

SetRect overrides annotationBase.SetRect to regenerate /AP/N after the rectangle changes (the appearance stream's BBox is derived from /Rect).

func (*LineAnnotation) SetStart

func (a *LineAnnotation) SetStart(p Point)

SetStart updates the line's start point and recomputes /Rect.

func (*LineAnnotation) SetStartLineEnding

func (a *LineAnnotation) SetStartLineEnding(s LineEndingStyle)

SetStartLineEnding sets the start-side line-ending style.

func (*LineAnnotation) Start

func (a *LineAnnotation) Start() Point

Start returns the line's start point.

func (*LineAnnotation) StartLineEnding

func (a *LineAnnotation) StartLineEnding() LineEndingStyle

StartLineEnding returns the style applied to the start of the line. Defaults to LineEndingNone if /LE is absent or malformed.

type LineCap

type LineCap int

LineCap is the /J line cap style per ISO 32000-1 §8.4.3.3 Table 54.

const (
	LineCapButt   LineCap = 0
	LineCapRound  LineCap = 1
	LineCapSquare LineCap = 2
)

type LineEndingStyle

type LineEndingStyle int

LineEndingStyle is one of the 10 line-ending shapes per ISO 32000-1 §12.5.6.7 Table 176, used in /Line annotations' /LE entry.

const (
	LineEndingNone LineEndingStyle = iota
	LineEndingSquare
	LineEndingCircle
	LineEndingDiamond
	LineEndingOpenArrow
	LineEndingClosedArrow
	LineEndingButt
	LineEndingROpenArrow   // OpenArrow rotated 180° (away from line)
	LineEndingRClosedArrow // ClosedArrow rotated 180°
	LineEndingSlash
)

type LineJoin

type LineJoin int

LineJoin is the /j line join style per ISO 32000-1 §8.4.3.4 Table 55.

const (
	LineJoinMiter LineJoin = 0
	LineJoinRound LineJoin = 1
	LineJoinBevel LineJoin = 2
)

type LineStyle

type LineStyle struct {
	Color       *Color    // nil → black {0,0,0,1}
	Width       float64   // ≤ 0 → no stroke (the draw call becomes a no-op for stroke)
	DashPattern []float64 // [on, off, on, off, ...]; nil or empty → solid
	DashPhase   float64   // offset into the dash pattern, default 0
	Cap         LineCap   // default LineCapButt (see appearance_builder.go); per ISO 32000-1 §8.4.3.3
	Join        LineJoin  // default LineJoinMiter (see appearance_builder.go); per ISO 32000-1 §8.4.3.4
	MiterLimit  float64   // ≤ 0 → PDF default (10)
}

LineStyle describes how a stroked path is drawn.

Zero value: black, 0pt wide (no stroke), solid, butt cap, miter join. Mirrors Aspose.PDF for .NET's GraphInfo stroke fields.

type LinkAnnotation

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

LinkAnnotation is a clickable region. Its visual is rendered by the viewer (no /AP needed). The associated /A action determines what happens on click — see Action and the various NewXxxAction factories.

func NewLinkAnnotation

func NewLinkAnnotation(page *Page, rect Rectangle) *LinkAnnotation

NewLinkAnnotation builds an unbound link annotation. Page must be non-nil. The annotation is not added to the document until page.Annotations().Add(link) succeeds.

func (*LinkAnnotation) Action

func (a *LinkAnnotation) Action() Action

Action returns the action attached to this link, or nil if no /A is present or the action type is unsupported.

func (*LinkAnnotation) AnnotationType

func (a *LinkAnnotation) AnnotationType() AnnotationType

func (*LinkAnnotation) Color

func (b *LinkAnnotation) Color() *Color

Color returns the /C array as an RGB Color. Returns nil if /C is absent.

func (*LinkAnnotation) Contents

func (b *LinkAnnotation) Contents() string

Contents returns /Contents (the annotation body text).

func (*LinkAnnotation) Highlight

func (a *LinkAnnotation) Highlight() LinkHighlightMode

Highlight returns the click-feedback mode (/H entry). Returns LinkHighlightInvert if /H is absent (the PDF default).

func (*LinkAnnotation) PageIndex

func (b *LinkAnnotation) PageIndex() int

PageIndex returns the 1-based index of the page this annotation lives on. 0 if the annotation is not yet attached or its /P doesn't resolve.

func (*LinkAnnotation) Rect

func (b *LinkAnnotation) Rect() Rectangle

Rect returns the annotation rectangle. Empty Rectangle if /Rect is missing or malformed.

func (*LinkAnnotation) SetAction

func (a *LinkAnnotation) SetAction(act Action)

SetAction writes the /A entry. nil clears /A.

func (*LinkAnnotation) SetColor

func (b *LinkAnnotation) SetColor(c *Color)

SetColor writes /C as an RGB array; nil removes the entry.

func (*LinkAnnotation) SetContents

func (b *LinkAnnotation) SetContents(s string)

SetContents writes /Contents (the annotation body text); empty string removes the entry.

func (*LinkAnnotation) SetHighlight

func (a *LinkAnnotation) SetHighlight(h LinkHighlightMode)

SetHighlight writes the /H entry. LinkHighlightInvert (the default) removes /H entirely so that the dict matches a freshly-created link.

func (*LinkAnnotation) SetRect

func (b *LinkAnnotation) SetRect(r Rectangle)

SetRect writes the annotation rectangle.

func (*LinkAnnotation) SetTitle

func (b *LinkAnnotation) SetTitle(s string)

SetTitle writes /T (the annotation author / reviewer name); empty string removes the entry.

func (*LinkAnnotation) Title

func (b *LinkAnnotation) Title() string

Title returns /T (the annotation author / reviewer name).

type LinkHighlightMode

type LinkHighlightMode int

LinkHighlightMode controls the visual feedback when the link is activated by the user (the /H entry per ISO 32000-1 §12.5.6.5).

const (
	// LinkHighlightInvert (default) inverts the contents of the link
	// rectangle when activated.
	LinkHighlightInvert LinkHighlightMode = iota
	// LinkHighlightNone means no visible feedback on activation.
	LinkHighlightNone
	// LinkHighlightOutline inverts the annotation's border.
	LinkHighlightOutline
	// LinkHighlightPush visually depresses the rectangle on activation.
	LinkHighlightPush
)

type ListBoxField

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

ListBoxField is a single- or multi-select list choice field.

func (*ListBoxField) AddOption

func (f *ListBoxField) AddOption(o ChoiceOption)

AddOption appends a ChoiceOption to /Opt.

func (*ListBoxField) FullName

func (b *ListBoxField) FullName() string

func (*ListBoxField) IsReadOnly

func (b *ListBoxField) IsReadOnly() bool

func (*ListBoxField) IsRequired

func (b *ListBoxField) IsRequired() bool

func (*ListBoxField) MultiSelect

func (f *ListBoxField) MultiSelect() bool

func (*ListBoxField) Options

func (f *ListBoxField) Options() []ChoiceOption

func (*ListBoxField) PageIndex

func (b *ListBoxField) PageIndex() int

func (*ListBoxField) PartialName

func (b *ListBoxField) PartialName() string

func (*ListBoxField) Rect

func (b *ListBoxField) Rect() Rectangle

func (*ListBoxField) RemoveOption

func (f *ListBoxField) RemoveOption(index int) error

RemoveOption removes the option at index. Errors on out-of-range.

func (*ListBoxField) Selected

func (f *ListBoxField) Selected() []int

Selected returns the indices of currently selected options. Single- select listboxes return at most one element.

func (*ListBoxField) SetMultiSelect

func (f *ListBoxField) SetMultiSelect(v bool)

SetMultiSelect toggles bit 22 (/Ff MultiSelect) on a ListBoxField.

func (*ListBoxField) SetReadOnly

func (f *ListBoxField) SetReadOnly(v bool)

func (*ListBoxField) SetRequired

func (f *ListBoxField) SetRequired(v bool)

func (*ListBoxField) SetSelected

func (f *ListBoxField) SetSelected(indices ...int) error

SetSelected replaces the selected indices. Variadic arguments allow SetSelected() (clear), SetSelected(0) (single), SetSelected(0, 1) (multi). Multi-selection on a single-select listbox returns an error.

func (*ListBoxField) SetValue

func (f *ListBoxField) SetValue(s string) error

func (*ListBoxField) Value

func (f *ListBoxField) Value() string

type MarginInfo

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

MarginInfo describes margins or padding in points: Top / Right / Bottom / Left. Inside a Cell, MarginInfo represents the padding between the cell's border and its text content. Mirrors Aspose.PDF for .NET's MarginInfo.

type Metadata

type Metadata struct {
	Title        string
	Author       string
	Subject      string
	Keywords     string
	Creator      string
	Producer     string
	CreationDate string
	ModDate      string
	Custom       map[string]string // arbitrary Info dict entries
}

Metadata contains document information from the PDF Info dictionary. Fields not present in the source PDF are empty strings.

type NamedAction

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

NamedAction triggers a built-in viewer command (FirstPage, Print, ...).

func NewNamedAction

func NewNamedAction(n NamedActionType) *NamedAction

NewNamedAction builds a /Named action.

func (*NamedAction) ActionType

func (a *NamedAction) ActionType() ActionType

func (*NamedAction) Name

func (a *NamedAction) Name() NamedActionType

func (*NamedAction) SetName

func (a *NamedAction) SetName(n NamedActionType)

type NamedActionType

type NamedActionType int

NamedActionType identifies one of the standard viewer commands supported by /Named actions per ISO 32000-1 §12.6.4.11.

const (
	NamedActionUnknown NamedActionType = iota
	NamedActionFirstPage
	NamedActionLastPage
	NamedActionNextPage
	NamedActionPrevPage
	NamedActionPrint
)

type NamedDestination

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

NamedDestination wraps a name reference into the document's NamedDestinations collection. Implements Destination so it can be used wherever an explicit destination is accepted (outline entries, future link annotation /Dest values, GoToAction).

Resolution is lazy: Page() and Resolve() look up the name in doc.NamedDestinations() at call time. This allows constructing a NamedDestination before adding the entry to the collection (forward reference).

Per ISO 32000-1 §12.3.2.3.

func NewNamedDestination

func NewNamedDestination(doc *Document, name string) *NamedDestination

NewNamedDestination builds a name-reference destination. The name need not be registered yet — resolution is lazy at Page() and write time.

Aspose .NET: new NamedDestination(name) Go: pdf.NewNamedDestination(doc, name)

func (*NamedDestination) DestinationType

func (n *NamedDestination) DestinationType() DestinationType

DestinationType returns DestinationTypeNamed.

func (*NamedDestination) Name

func (n *NamedDestination) Name() string

Name returns the registered name this destination references.

func (*NamedDestination) Page

func (n *NamedDestination) Page() *Page

Page resolves the underlying destination's page via the document's NamedDestinations collection. Returns nil if the name is not registered or the underlying destination has no Page.

func (*NamedDestination) Resolve

func (n *NamedDestination) Resolve() Destination

Resolve returns the underlying explicit destination registered under this name, or nil if absent. Useful when you need the typed concrete (e.g. *DestinationXYZ to read coordinates).

type NamedDestinations

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

NamedDestinations is a name-to-destination map per ISO 32000-1 §12.3.2.3. Backed at PDF level by the modern /Catalog/Names/Dests name tree (PDF 1.2+); on read it also absorbs legacy /Catalog/Dests for backward compatibility. On write, only /Names/Dests is emitted.

Mirrors Aspose.PDF for .NET's NamedDestinations collection.

func (*NamedDestinations) Add

func (n *NamedDestinations) Add(name string, dest Destination) error

Add registers dest under name. Errors on:

  • empty name
  • nil dest
  • dest is itself a *NamedDestination (would create a name→name loop)

If name was already present, the previous value is replaced silently.

func (*NamedDestinations) All

func (n *NamedDestinations) All() map[string]Destination

All returns a snapshot map of name → destination.

func (*NamedDestinations) Clear

func (n *NamedDestinations) Clear()

Clear removes every entry.

func (*NamedDestinations) Count

func (n *NamedDestinations) Count() int

Count returns the number of registered entries.

func (*NamedDestinations) Document

func (n *NamedDestinations) Document() *Document

Document returns the document this collection is bound to.

func (*NamedDestinations) Get

func (n *NamedDestinations) Get(name string) Destination

Get returns the destination registered under name, or nil if absent. Never returns a *NamedDestination (no recursive lookups).

func (*NamedDestinations) Has

func (n *NamedDestinations) Has(name string) bool

Has reports whether name is registered.

func (*NamedDestinations) Names

func (n *NamedDestinations) Names() []string

Names returns a snapshot slice of all registered names in lex order.

func (*NamedDestinations) Remove

func (n *NamedDestinations) Remove(name string) bool

Remove deletes the entry; returns true if it existed.

type OptimizeImageOptions

type OptimizeImageOptions struct {
	MaxDPI           float64 // images above this DPI are downscaled; 0 = no downscaling
	JPEGQuality      int     // JPEG quality 1-100; 0 = default (75)
	ConvertPNGToJPEG bool    // convert opaque PNG (no alpha) to JPEG
}

OptimizeImageOptions controls image optimization behavior.

type OutlineItemCollection

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

OutlineItemCollection represents an outline entry and the collection of its children. The recursive structure mirrors Aspose.PDF for .NET: each entry is both a tree node (with Title, Color, Action, Destination, etc.) and a collection (Add/At/Remove/Count for children). The root collection — returned by Document.Outlines() — has no parent and an empty Title; only its children are visible as top-level bookmarks.

Per ISO 32000-1 §12.3.3.

func NewOutlineItemCollection

func NewOutlineItemCollection(doc *Document) *OutlineItemCollection

NewOutlineItemCollection builds an unattached outline entry bound to the given document. Add it to a parent via Document.Outlines().Add(...) or via another entry's Add(...) — until added it has no effect on the saved PDF.

Aspose .NET: new OutlineItemCollection(doc.Outlines) Go: pdf.NewOutlineItemCollection(doc)

func (*OutlineItemCollection) Action

func (o *OutlineItemCollection) Action() Action

Action returns the action attached via /A. Reuses the Action interface defined for annotations.

func (*OutlineItemCollection) Add

Add appends child as the last child of this entry. Errors on nil, cross-document, cycle, or already-attached child.

func (*OutlineItemCollection) All

All returns a snapshot slice of direct children.

func (*OutlineItemCollection) At

At returns the child at the given 0-based index, or nil if out-of-range.

func (*OutlineItemCollection) Bold

func (o *OutlineItemCollection) Bold() bool

Bold corresponds to /F bit 2 in the outline item dict. Default false.

func (*OutlineItemCollection) Color

func (o *OutlineItemCollection) Color() *Color

Color returns the RGB label color, or nil if /C is absent (default black). SetColor(nil) clears /C.

func (*OutlineItemCollection) Count

func (o *OutlineItemCollection) Count() int

Count returns the number of direct children (placeholder until Task 5 adds the rest of the collection API).

func (*OutlineItemCollection) Destination

func (o *OutlineItemCollection) Destination() Destination

Destination returns the explicit view destination via /Dest, or nil if absent. If both Destination and Action are set, /Dest takes priority per ISO 32000-1 §12.3.3.

func (*OutlineItemCollection) Document

func (o *OutlineItemCollection) Document() *Document

Document returns the document this collection is bound to.

func (*OutlineItemCollection) Insert

func (o *OutlineItemCollection) Insert(index int, child *OutlineItemCollection) error

Insert inserts child at the given 0-based index among this entry's children.

func (*OutlineItemCollection) IsExpanded

func (o *OutlineItemCollection) IsExpanded() bool

IsExpanded controls the viewer's initial expand/collapse state. Encoded via the sign of /Count. Default true.

func (*OutlineItemCollection) Italic

func (o *OutlineItemCollection) Italic() bool

Italic corresponds to /F bit 1. Default false.

func (*OutlineItemCollection) Parent

Parent returns the parent entry, or nil for the root collection.

func (*OutlineItemCollection) Remove

Remove detaches child if it's a direct child. Returns true on hit.

func (*OutlineItemCollection) RemoveAt

func (o *OutlineItemCollection) RemoveAt(index int) error

RemoveAt detaches the child at the given index.

func (*OutlineItemCollection) SetAction

func (o *OutlineItemCollection) SetAction(a Action)

SetAction sets the /A action. Pass nil to clear.

func (*OutlineItemCollection) SetBold

func (o *OutlineItemCollection) SetBold(b bool)

func (*OutlineItemCollection) SetColor

func (o *OutlineItemCollection) SetColor(c *Color)

func (*OutlineItemCollection) SetDestination

func (o *OutlineItemCollection) SetDestination(d Destination)

SetDestination sets the /Dest entry. Pass nil to clear.

func (*OutlineItemCollection) SetIsExpanded

func (o *OutlineItemCollection) SetIsExpanded(b bool)

func (*OutlineItemCollection) SetItalic

func (o *OutlineItemCollection) SetItalic(b bool)

func (*OutlineItemCollection) SetTitle

func (o *OutlineItemCollection) SetTitle(s string)

SetTitle replaces the bookmark text.

func (*OutlineItemCollection) Title

func (o *OutlineItemCollection) Title() string

Title returns the bookmark text.

type Page

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

Page is a live view of a single page within a Document. It reflects the current state of the document, including any mutations.

func (*Page) AddImage

func (p *Page) AddImage(path string, rect Rectangle) error

AddImage adds an image from a file to the page within the given rectangle.

func (*Page) AddImageFromStream

func (p *Page) AddImageFromStream(r io.Reader, rect Rectangle) error

AddImageFromStream adds an image from a reader to the page within the given rectangle.

func (*Page) AddTable

func (p *Page) AddTable(t *Table, rect Rectangle) (int, error)

AddTable renders the table inside the given rectangle.

Returns the number of pages automatically appended to the document (0 when the table fits in rect). When the table doesn't fit and overflow is needed, new pages are appended with dimensions matching the receiver page; the continuation rectangle is computed from t.OverflowMargins(). Repeating header rows (see Table.SetRepeatingRowsCount) draw at the top of each page, including the original.

Errors before any drawing on validation failures: nil table, bad rect, non-positive column widths, mismatched cell counts (span-aware), merge overlaps, rowspan crossing the header/body boundary, or a spanning group too tall to fit any page.

func (*Page) AddText

func (p *Page) AddText(text string, style TextStyle, rect Rectangle) error

AddText draws text inside the rectangle using the given style. Text is wrapped at word boundaries to fit the rectangle width. Content exceeding the rectangle height is clipped.

func (*Page) Annotations

func (p *Page) Annotations() *AnnotationCollection

Annotations returns the page's annotation collection. Always non-nil; for a page with no /Annots array, the collection is empty.

func (*Page) ArtBox

func (p *Page) ArtBox() (PageSize, error)

ArtBox returns the art box of the page. Falls back to CropBox, then MediaBox if not set.

func (*Page) BleedBox

func (p *Page) BleedBox() (PageSize, error)

BleedBox returns the bleed box of the page. Falls back to CropBox, then MediaBox if not set.

func (*Page) CropBox

func (p *Page) CropBox() (PageSize, error)

CropBox returns the crop box of the page. Falls back to MediaBox if not set.

func (*Page) DrawCircle

func (p *Page) DrawCircle(center Point, radius float64, style ShapeStyle) error

DrawCircle strokes and/or fills a circle. Returns error for negative radius. No-op if radius is zero or neither stroke nor fill is configured.

Mirrors Aspose.PDF for .NET's Drawing.Circle.

func (*Page) DrawEllipse

func (p *Page) DrawEllipse(center Point, rx, ry float64, style ShapeStyle) error

DrawEllipse strokes and/or fills an axis-aligned ellipse. Returns error for negative semi-axis. No-op if either semi-axis is zero or neither stroke nor fill is configured.

Mirrors Aspose.PDF for .NET's Drawing.Ellipse.

func (*Page) DrawLine

func (p *Page) DrawLine(from, to Point, style LineStyle) error

DrawLine strokes a single line segment from→to with the given style. No-op if style.Width <= 0.

Mirrors Aspose.PDF for .NET's Drawing.Line shape.

func (*Page) DrawPath

func (p *Page) DrawPath(path *Path, style ShapeStyle) error

DrawPath strokes and/or fills the previously-built path. Errors if path is nil. No-op if path has no operations or style is empty.

Mirrors Aspose.PDF for .NET's Drawing.GraphicsPath / Drawing.Curve.

func (*Page) DrawPolygon

func (p *Page) DrawPolygon(points []Point, style ShapeStyle) error

DrawPolygon strokes and/or fills a closed polygon (last point connects back to the first via `h`). Errors if len(points) < 3. No-op if neither stroke nor fill is configured.

Mirrors Aspose.PDF for .NET's Drawing.Polygon.

func (*Page) DrawPolyline

func (p *Page) DrawPolyline(points []Point, style LineStyle) error

DrawPolyline strokes an open polyline (first and last points are NOT connected). No fill — even if one were specified, an open path has ambiguous fill semantics. Errors if len(points) < 2. No-op if style.Width <= 0.

Mirrors Aspose.PDF for .NET's Drawing.Polyline.

func (*Page) DrawRectangle

func (p *Page) DrawRectangle(rect Rectangle, style ShapeStyle) error

DrawRectangle strokes and/or fills an axis-aligned rectangle. No-op if neither stroke (Width > 0) nor fill (FillColor != nil) is set.

Mirrors Aspose.PDF for .NET's Drawing.Rectangle shape.

func (*Page) DrawRoundedRectangle

func (p *Page) DrawRoundedRectangle(rect Rectangle, radius float64, style ShapeStyle) error

DrawRoundedRectangle strokes and/or fills an axis-aligned rectangle with rounded corners of the given radius. The radius is clamped to half the shorter side. Returns error for negative radius.

Implemented as a Path: 4 straight edges + 4 quarter-arc corners.

Mirrors Aspose.PDF for .NET's Drawing.RoundedRectangle.

func (*Page) ExtractImages

func (p *Page) ExtractImages() ([]Image, error)

ExtractImages returns all images found on the page.

func (*Page) ExtractText

func (p *Page) ExtractText() (string, error)

ExtractText returns the text content of the page. Characters from fonts with unrecognized encodings are replaced with U+FFFD.

func (*Page) ExtractTextWithLayout

func (p *Page) ExtractTextWithLayout() ([]TextLine, error)

ExtractTextWithLayout returns structured text lines sorted in visual (top-to-bottom, left-to-right) reading order. Each line contains its concatenated text and individual fragments with positions.

func (*Page) ImageInfos

func (p *Page) ImageInfos() ([]ImageInfo, error)

ImageInfos returns metadata for all images found on the page without decoding pixel data.

func (*Page) Label

func (p *Page) Label() string

Label returns the formatted page label for this page as defined by the document's /PageLabels number tree (PDF spec §12.4.2).

Common label styles:

  • /D — decimal integers: 1, 2, 3, …
  • /r — lowercase roman: i, ii, iii, …
  • /R — uppercase roman: I, II, III, …
  • /a — lowercase alphabetic: a, b, …, z, aa, ab, …
  • /A — uppercase alphabetic: A, B, …, Z, AA, AB, …

A /P prefix string is prepended when present (e.g. "A-1", "A-2").

If the document has no /PageLabels entry, the decimal page number is returned.

func (*Page) Number

func (p *Page) Number() int

Number returns the 1-based page number within the document.

func (*Page) Rotation

func (p *Page) Rotation() RotationAngle

Rotation returns the effective rotation of the page in degrees (0, 90, 180, 270).

func (*Page) Size

func (p *Page) Size() (PageSize, error)

Size returns the page dimensions from its MediaBox. If MediaBox is not set on the page itself, it is inherited from the page tree.

func (*Page) TrimBox

func (p *Page) TrimBox() (PageSize, error)

TrimBox returns the trim box of the page. Falls back to CropBox, then MediaBox if not set.

type PageFormat

type PageFormat struct {
	Width  float64
	Height float64
}

PageFormat describes a page size in points (1/72 inch).

func (PageFormat) Landscape

func (f PageFormat) Landscape() PageFormat

Landscape returns the format with width and height swapped.

type PageRange

type PageRange struct {
	From, To int
}

PageRange specifies an inclusive range of pages (1-based).

type PageSize

type PageSize struct {
	Width  float64
	Height float64
}

PageSize holds the width and height of a PDF page in points (1/72 inch).

func PageSizes

func PageSizes(inputPath string) ([]PageSize, error)

PageSizes returns the dimensions of every page in the given PDF file.

type Path

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

Path is a sequence of MoveTo/LineTo/CurveTo/Close operations defining an arbitrary 2D path in PDF user space (origin at page bottom-left, Y up).

Construct via NewPath() and chain mutator methods, then pass to (*Page).DrawPath. Path is a builder type — it accumulates operations and holds no rendering state.

func NewPath

func NewPath() *Path

NewPath returns an empty path.

func (*Path) Arc

func (p *Path) Arc(cx, cy, r, startAngle, sweepAngle float64) *Path

Arc adds an arc to the path, approximated by cubic Bezier curves.

(cx, cy) is the center; r is the radius. startAngle and sweepAngle are in radians; sweepAngle may be negative (clockwise). The arc is subdivided into segments of ≤90°, each approximated by one cubic Bezier using k = (4/3) * tan(segmentAngle / 4) for the control-point magnitude.

If the path has no current point, MoveTo to the arc's start is implicit. After the call, the path's current point is the arc's endpoint.

No-op if r <= 0 or sweepAngle == 0.

func (*Path) Close

func (p *Path) Close() *Path

Close closes the current subpath with a line back to the most recent MoveTo. PDF operator h.

func (*Path) CurveTo

func (p *Path) CurveTo(c1x, c1y, c2x, c2y, x, y float64) *Path

CurveTo adds a cubic Bezier curve from the current point to (x, y) with control points (c1x, c1y) and (c2x, c2y). PDF operator c.

func (*Path) LineTo

func (p *Path) LineTo(x, y float64) *Path

LineTo adds a straight line segment from the current point to (x, y). If there is no current point, equivalent to MoveTo per PDF spec semantics.

func (*Path) MoveTo

func (p *Path) MoveTo(x, y float64) *Path

MoveTo begins a new subpath at (x, y). Returns p for chaining.

func (*Path) QuadTo

func (p *Path) QuadTo(cx, cy, x, y float64) *Path

QuadTo adds a quadratic Bezier curve (one control point) from the current point to (x, y), automatically converted to the equivalent cubic per the standard quadratic-to-cubic formula:

C1 = P0 + (2/3) * (Q - P0)
C2 = P3 + (2/3) * (Q - P3)

If there is no current point, treats (0, 0) as the start (matching PDF path semantics).

type Permissions

type Permissions struct {
	AllowPrint         bool
	AllowModify        bool
	AllowCopy          bool
	AllowAnnotations   bool
	AllowFormFill      bool
	AllowAccessibility bool
	AllowAssembly      bool
	AllowPrintHighRes  bool
}

Permissions controls what a viewer allows on an encrypted PDF. The zero value denies every operation. Permissions only take effect when the document is also encrypted (SetPassword); viewers enforce the bits — the library itself is not a DRM enforcer.

Per ISO 32000-1 §7.6.3.2 Table 22, bit meanings for R=3/R=4:

AllowPrint         — bit 3  (low-resolution print)
AllowModify        — bit 4  (modify page contents)
AllowCopy          — bit 5  (copy text / extract graphics)
AllowAnnotations   — bit 6  (add/modify text annotations)
AllowFormFill      — bit 9  (fill in existing form fields)
AllowAccessibility — bit 10 (extract text/graphics for accessibility)
AllowAssembly      — bit 11 (insert/rotate/delete pages)
AllowPrintHighRes  — bit 12 (print in high resolution)

type Point

type Point struct {
	X, Y float64
}

Point is a single point in PDF user-space coordinates.

type QuadPoint

type QuadPoint struct {
	X1, Y1, X2, Y2, X3, Y3, X4, Y4 float64
}

QuadPoint is one quadrilateral within a markup annotation's /QuadPoints array. Per ISO 32000-1 §12.5.6.10 the eight floats name the corners in this order: (X1,Y1)=upper-left, (X2,Y2)=upper-right, (X3,Y3)=lower-left, (X4,Y4)=lower-right (in default user space, so "upper" means higher Y).

type RadioButtonField

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

RadioButtonField is a group of mutually exclusive options.

func (*RadioButtonField) FullName

func (b *RadioButtonField) FullName() string

func (*RadioButtonField) IsReadOnly

func (b *RadioButtonField) IsReadOnly() bool

func (*RadioButtonField) IsRequired

func (b *RadioButtonField) IsRequired() bool

func (*RadioButtonField) Options

func (f *RadioButtonField) Options() []*RadioButtonOptionField

Options returns one RadioButtonOptionField per widget in the group.

func (*RadioButtonField) PageIndex

func (b *RadioButtonField) PageIndex() int

func (*RadioButtonField) PartialName

func (b *RadioButtonField) PartialName() string

func (*RadioButtonField) Rect

func (b *RadioButtonField) Rect() Rectangle

func (*RadioButtonField) SetReadOnly

func (f *RadioButtonField) SetReadOnly(v bool)

func (*RadioButtonField) SetRequired

func (f *RadioButtonField) SetRequired(v bool)

func (*RadioButtonField) SetValue

func (f *RadioButtonField) SetValue(s string) error

SetValue takes the export name of the option to select. Empty string clears the selection (writes /Off). Any other unknown value returns an error.

func (*RadioButtonField) Value

func (f *RadioButtonField) Value() string

type RadioButtonOptionField

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

RadioButtonOptionField is one of the option widgets inside a RadioButtonField. Mirrors the C# nested type pattern.

func (*RadioButtonOptionField) Name

func (o *RadioButtonOptionField) Name() string

Name returns the option's export value (its /AS state when selected, equivalently its non-/Off key in the widget's /AP/N dict).

func (*RadioButtonOptionField) Selected

func (o *RadioButtonOptionField) Selected() bool

Selected reports whether this option is the currently selected one.

func (*RadioButtonOptionField) SetSelected

func (o *RadioButtonOptionField) SetSelected(v bool)

SetSelected(true) selects this option and clears all siblings. SetSelected(false) clears the selection if this option is currently selected; siblings are unaffected.

type RadioItem

type RadioItem struct {
	PageNum int
	Rect    Rectangle
	Export  string
}

RadioItem describes one widget inside a radio group. PageNum is 1-based; Export is the unique export value for this option (becomes the /AS state name when selected).

type Rectangle

type Rectangle struct {
	LLX, LLY float64 // lower-left corner
	URX, URY float64 // upper-right corner
}

Rectangle represents a PDF rectangle [llx, lly, urx, ury] in points (1/72 inch).

type RedactAnnotation

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

RedactAnnotation marks regions for redaction. Mark mode (this type) renders a semi-transparent fill of /QuadPoints regions. The destructive content removal happens when (*Document).ApplyRedactions is called — this annotation is then removed and the underlying page content is irreversibly rewritten. Per ISO 32000-1 §12.5.6.20.

func NewRedactAnnotation

func NewRedactAnnotation(page *Page, rect Rectangle) *RedactAnnotation

NewRedactAnnotation builds an unbound redact annotation. Page must be non-nil. By default, /QuadPoints is empty (rendering uses /Rect as a single quad). Callers typically call SetQuadPoints to specify multiple disjoint regions.

func (*RedactAnnotation) AnnotationType

func (a *RedactAnnotation) AnnotationType() AnnotationType

func (*RedactAnnotation) BorderStyle

func (d *RedactAnnotation) BorderStyle() BorderStyle

BorderStyle returns the /BS/S style. Defaults to BorderSolid if absent.

func (*RedactAnnotation) BorderWidth

func (d *RedactAnnotation) BorderWidth() float64

BorderWidth returns the stroke line width. Reads /BS/W (preferred) or /Border[2] (legacy fallback). Defaults to 1 if neither is present.

func (*RedactAnnotation) DashPattern

func (d *RedactAnnotation) DashPattern() []float64

DashPattern returns a defensive copy of the dash array. Reads /BS/D (preferred) or falls back to the legacy /Border[3] entry per ISO 32000-1 §12.5.4. Returns nil if neither is present.

func (*RedactAnnotation) InteriorColor

func (a *RedactAnnotation) InteriorColor() *Color

InteriorColor returns the /IC fill color (used for both mark visual and post-apply overlay). Returns nil if absent.

func (*RedactAnnotation) OverlayText

func (a *RedactAnnotation) OverlayText() string

OverlayText returns /OverlayText. Empty string if absent.

func (*RedactAnnotation) OverlayTextStyle

func (a *RedactAnnotation) OverlayTextStyle() TextStyle

OverlayTextStyle returns the style reconstructed from /DA + /Q. Background is not relevant for redact overlay.

func (*RedactAnnotation) QuadPoints

func (a *RedactAnnotation) QuadPoints() []QuadPoint

QuadPoints returns the regions to redact in page space. Returns nil if /QuadPoints is absent (Apply uses /Rect as the single region).

func (*RedactAnnotation) RegenerateAppearance

func (a *RedactAnnotation) RegenerateAppearance()

RegenerateAppearance forces /AP/N to be rebuilt.

func (*RedactAnnotation) RepeatOverlayText

func (a *RedactAnnotation) RepeatOverlayText() bool

RepeatOverlayText returns /Repeat. False if absent.

func (*RedactAnnotation) SetBorderStyle

func (d *RedactAnnotation) SetBorderStyle(s BorderStyle)

SetBorderStyle writes /BS/S using the PDF spec name codes.

func (*RedactAnnotation) SetBorderWidth

func (d *RedactAnnotation) SetBorderWidth(w float64)

SetBorderWidth writes /BS/W and clears any legacy /Border array.

func (*RedactAnnotation) SetColor

func (d *RedactAnnotation) SetColor(c *Color)

SetColor overrides annotationBase.SetColor to regenerate /AP/N after the stroke color changes.

func (*RedactAnnotation) SetDashPattern

func (d *RedactAnnotation) SetDashPattern(p []float64)

SetDashPattern writes /BS/D. The slice is copied; the caller may safely mutate p after this returns.

func (*RedactAnnotation) SetInteriorColor

func (a *RedactAnnotation) SetInteriorColor(c *Color)

SetInteriorColor writes /IC. nil deletes the entry.

func (*RedactAnnotation) SetOverlayText

func (a *RedactAnnotation) SetOverlayText(s string)

SetOverlayText writes /OverlayText. Empty string deletes the entry.

func (*RedactAnnotation) SetOverlayTextStyle

func (a *RedactAnnotation) SetOverlayTextStyle(s TextStyle)

SetOverlayTextStyle writes /DA + /Q.

func (*RedactAnnotation) SetQuadPoints

func (a *RedactAnnotation) SetQuadPoints(qp []QuadPoint)

SetQuadPoints writes /QuadPoints. nil/empty slice removes the entry (Apply will then use /Rect as single region).

func (*RedactAnnotation) SetRect

func (d *RedactAnnotation) SetRect(r Rectangle)

SetRect overrides annotationBase.SetRect to regenerate /AP/N after the rectangle changes (the appearance stream's BBox is derived from /Rect).

func (*RedactAnnotation) SetRepeatOverlayText

func (a *RedactAnnotation) SetRepeatOverlayText(repeat bool)

SetRepeatOverlayText writes /Repeat. False removes the entry.

type ResetFormAction

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

ResetFormAction resets named form fields to their /DV defaults.

func NewResetFormAction

func NewResetFormAction(fields []string) *ResetFormAction

NewResetFormAction builds a /ResetForm action targeting the given field names. Empty fields means "reset all fields" per spec. The fields slice is copied; the caller may safely mutate it after this returns.

func (*ResetFormAction) ActionType

func (a *ResetFormAction) ActionType() ActionType

func (*ResetFormAction) FieldNames

func (a *ResetFormAction) FieldNames() []string

FieldNames returns a copy of the field-name list. The returned slice is owned by the caller; mutating it does not affect the action.

func (*ResetFormAction) SetFieldNames

func (a *ResetFormAction) SetFieldNames(f []string)

SetFieldNames replaces the field-name list. The slice is copied; the caller may safely mutate f after this returns.

type RotationAngle

type RotationAngle int

RotationAngle represents a valid PDF page rotation in clockwise degrees.

const (
	Rotate0   RotationAngle = 0
	Rotate90  RotationAngle = 90
	Rotate180 RotationAngle = 180
	Rotate270 RotationAngle = 270
)

type Row

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

Row is a single row within a Table.

func (*Row) AddCell

func (r *Row) AddCell(text string) *Cell

AddCell appends a cell with the given text.

func (*Row) AddCells

func (r *Row) AddCells(texts ...string) []*Cell

AddCells is a convenience that calls AddCell for each text in order.

func (*Row) Background

func (r *Row) Background() *Color

Background returns the row-level background color, or nil if unset.

func (*Row) Border

func (r *Row) Border() *BorderInfo

Border returns the row-level border override, or nil if unset.

func (*Row) CellCount

func (r *Row) CellCount() int

CellCount returns the number of cells in this row.

func (*Row) Cells

func (r *Row) Cells() []*Cell

Cells returns the row's cells. The slice is the live backing — do not mutate.

func (*Row) Height

func (r *Row) Height() float64

Height returns the configured row height. 0 means auto-fit.

func (*Row) Margin

func (r *Row) Margin() *MarginInfo

Margin returns the row-level margin override, or nil if unset.

func (*Row) SetBackground

func (r *Row) SetBackground(col *Color) *Row

SetBackground sets a row-level background color. Cells in the row inherit this background unless the cell itself calls SetBackground.

func (*Row) SetBorder

func (r *Row) SetBorder(b BorderInfo) *Row

SetBorder sets a row-level default border. Cells inherit unless overridden.

func (*Row) SetHeight

func (r *Row) SetHeight(h float64) *Row

SetHeight sets the row's drawn height in points. Pass 0 to use auto-fit (the renderer measures cell contents to compute a row height that fits).

func (*Row) SetMargin

func (r *Row) SetMargin(m MarginInfo) *Row

SetMargin sets a row-level default cell padding. Cells inherit unless overridden.

func (*Row) SetTextStyle

func (r *Row) SetTextStyle(s TextStyle) *Row

SetTextStyle sets a row-level default text style. Cells in the row inherit this style (overlaid on table.DefaultCellStyle) unless overridden per-cell.

func (*Row) Table

func (r *Row) Table() *Table

Table returns the owning table.

func (*Row) TextStyle

func (r *Row) TextStyle() *TextStyle

TextStyle returns the row-level text style override, or nil if unset.

type ShapeStyle

type ShapeStyle struct {
	LineStyle
	FillColor *Color // nil = no fill
}

ShapeStyle combines a stroke (LineStyle) with an optional fill color.

FillColor nil → no fill (stroke-only). Width ≤ 0 in the embedded LineStyle → no stroke (fill-only). If both are unset, the draw call is a no-op.

Mirrors Aspose.PDF for .NET's GraphInfo (stroke + fill).

type SquareAnnotation

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

SquareAnnotation draws a rectangular annotation with stroked border and optional interior fill. Renders natively from /AP/N — Solid, Dashed, Beveled, Inset, and Underline border styles supported.

func NewSquareAnnotation

func NewSquareAnnotation(page *Page, rect Rectangle) *SquareAnnotation

NewSquareAnnotation builds an unbound square annotation. Page must be non-nil. The annotation is not added to the document until page.Annotations().Add(square) succeeds.

func (*SquareAnnotation) AnnotationType

func (a *SquareAnnotation) AnnotationType() AnnotationType

func (*SquareAnnotation) BorderStyle

func (d *SquareAnnotation) BorderStyle() BorderStyle

BorderStyle returns the /BS/S style. Defaults to BorderSolid if absent.

func (*SquareAnnotation) BorderWidth

func (d *SquareAnnotation) BorderWidth() float64

BorderWidth returns the stroke line width. Reads /BS/W (preferred) or /Border[2] (legacy fallback). Defaults to 1 if neither is present.

func (*SquareAnnotation) DashPattern

func (d *SquareAnnotation) DashPattern() []float64

DashPattern returns a defensive copy of the dash array. Reads /BS/D (preferred) or falls back to the legacy /Border[3] entry per ISO 32000-1 §12.5.4. Returns nil if neither is present.

func (*SquareAnnotation) InteriorColor

func (a *SquareAnnotation) InteriorColor() *Color

InteriorColor returns the /IC fill color, or nil if absent.

func (*SquareAnnotation) RegenerateAppearance

func (a *SquareAnnotation) RegenerateAppearance()

RegenerateAppearance forces /AP/N to be rebuilt from current properties. Useful when the underlying dict was mutated directly (bypassing setters).

func (*SquareAnnotation) SetBorderStyle

func (d *SquareAnnotation) SetBorderStyle(s BorderStyle)

SetBorderStyle writes /BS/S using the PDF spec name codes.

func (*SquareAnnotation) SetBorderWidth

func (d *SquareAnnotation) SetBorderWidth(w float64)

SetBorderWidth writes /BS/W and clears any legacy /Border array.

func (*SquareAnnotation) SetColor

func (d *SquareAnnotation) SetColor(c *Color)

SetColor overrides annotationBase.SetColor to regenerate /AP/N after the stroke color changes.

func (*SquareAnnotation) SetDashPattern

func (d *SquareAnnotation) SetDashPattern(p []float64)

SetDashPattern writes /BS/D. The slice is copied; the caller may safely mutate p after this returns.

func (*SquareAnnotation) SetInteriorColor

func (a *SquareAnnotation) SetInteriorColor(c *Color)

SetInteriorColor writes /IC as an RGB array; nil removes the entry.

func (*SquareAnnotation) SetRect

func (d *SquareAnnotation) SetRect(r Rectangle)

SetRect overrides annotationBase.SetRect to regenerate /AP/N after the rectangle changes (the appearance stream's BBox is derived from /Rect).

type SquigglyAnnotation

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

SquigglyAnnotation draws a wavy underline under text (typically used for spell-check style hints).

func NewSquigglyAnnotation

func NewSquigglyAnnotation(page *Page, rect Rectangle) *SquigglyAnnotation

NewSquigglyAnnotation builds an unbound squiggly-underline annotation.

func (*SquigglyAnnotation) AnnotationType

func (a *SquigglyAnnotation) AnnotationType() AnnotationType

func (*SquigglyAnnotation) Color

func (b *SquigglyAnnotation) Color() *Color

Color returns the /C array as an RGB Color. Returns nil if /C is absent.

func (*SquigglyAnnotation) Contents

func (b *SquigglyAnnotation) Contents() string

Contents returns /Contents (the annotation body text).

func (*SquigglyAnnotation) PageIndex

func (b *SquigglyAnnotation) PageIndex() int

PageIndex returns the 1-based index of the page this annotation lives on. 0 if the annotation is not yet attached or its /P doesn't resolve.

func (*SquigglyAnnotation) QuadPoints

func (a *SquigglyAnnotation) QuadPoints() []QuadPoint

QuadPoints returns the array of quads describing the squiggly region. Returns nil if /QuadPoints is absent or its array length is not a multiple of 8 (malformed).

func (*SquigglyAnnotation) Rect

func (b *SquigglyAnnotation) Rect() Rectangle

Rect returns the annotation rectangle. Empty Rectangle if /Rect is missing or malformed.

func (*SquigglyAnnotation) SetColor

func (b *SquigglyAnnotation) SetColor(c *Color)

SetColor writes /C as an RGB array; nil removes the entry.

func (*SquigglyAnnotation) SetContents

func (b *SquigglyAnnotation) SetContents(s string)

SetContents writes /Contents (the annotation body text); empty string removes the entry.

func (*SquigglyAnnotation) SetQuadPoints

func (a *SquigglyAnnotation) SetQuadPoints(qp []QuadPoint)

SetQuadPoints writes /QuadPoints. nil or empty slice removes the entry.

func (*SquigglyAnnotation) SetRect

func (b *SquigglyAnnotation) SetRect(r Rectangle)

SetRect writes the annotation rectangle.

func (*SquigglyAnnotation) SetTitle

func (b *SquigglyAnnotation) SetTitle(s string)

SetTitle writes /T (the annotation author / reviewer name); empty string removes the entry.

func (*SquigglyAnnotation) Title

func (b *SquigglyAnnotation) Title() string

Title returns /T (the annotation author / reviewer name).

type StampAnnotation

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

StampAnnotation is a rubber-stamp annotation. Renders one of 14 predefined visuals (Approved, Confidential, Draft, etc.) or a custom image. Per ISO 32000-1 §12.5.6.13.

func NewStampAnnotation

func NewStampAnnotation(page *Page, rect Rectangle, name StampName) *StampAnnotation

NewStampAnnotation builds an unbound stamp annotation. Page must be non-nil. /Name defaults to the supplied name (use StampNameDraft if uncertain).

func (*StampAnnotation) AnnotationType

func (a *StampAnnotation) AnnotationType() AnnotationType

func (*StampAnnotation) BorderStyle

func (d *StampAnnotation) BorderStyle() BorderStyle

BorderStyle returns the /BS/S style. Defaults to BorderSolid if absent.

func (*StampAnnotation) BorderWidth

func (d *StampAnnotation) BorderWidth() float64

BorderWidth returns the stroke line width. Reads /BS/W (preferred) or /Border[2] (legacy fallback). Defaults to 1 if neither is present.

func (*StampAnnotation) ClearCustomImage

func (a *StampAnnotation) ClearCustomImage()

ClearCustomImage reverts /AP/N to the predefined-name template visual. The previously-attached image XObject becomes orphan and can be reclaimed via doc.RemoveUnusedObjects().

func (*StampAnnotation) DashPattern

func (d *StampAnnotation) DashPattern() []float64

DashPattern returns a defensive copy of the dash array. Reads /BS/D (preferred) or falls back to the legacy /Border[3] entry per ISO 32000-1 §12.5.4. Returns nil if neither is present.

func (*StampAnnotation) HasCustomImage

func (a *StampAnnotation) HasCustomImage() bool

HasCustomImage returns true if SetCustomImage / SetCustomImageFromStream has been called and not subsequently cleared. Stub for now — full custom-image support in Task 8.

func (*StampAnnotation) Name

func (a *StampAnnotation) Name() StampName

Name returns the StampName decoded from /Name. Returns StampNameUnknown for non-spec custom names.

func (*StampAnnotation) RawName

func (a *StampAnnotation) RawName() string

RawName returns the /Name entry as a raw string ("/Approved", custom).

func (*StampAnnotation) RegenerateAppearance

func (a *StampAnnotation) RegenerateAppearance()

RegenerateAppearance forces /AP/N to be rebuilt from current state.

func (*StampAnnotation) SetBorderStyle

func (d *StampAnnotation) SetBorderStyle(s BorderStyle)

SetBorderStyle writes /BS/S using the PDF spec name codes.

func (*StampAnnotation) SetBorderWidth

func (d *StampAnnotation) SetBorderWidth(w float64)

SetBorderWidth writes /BS/W and clears any legacy /Border array.

func (*StampAnnotation) SetColor

func (d *StampAnnotation) SetColor(c *Color)

SetColor overrides annotationBase.SetColor to regenerate /AP/N after the stroke color changes.

func (*StampAnnotation) SetCustomImage

func (a *StampAnnotation) SetCustomImage(path string) error

SetCustomImage embeds the image at path as the stamp's /AP/N visual, overriding the predefined-name template. Format auto-detected from magic bytes (JPEG, PNG).

func (*StampAnnotation) SetCustomImageFromStream

func (a *StampAnnotation) SetCustomImageFromStream(r io.Reader) error

SetCustomImageFromStream is the io.Reader variant of SetCustomImage.

func (*StampAnnotation) SetDashPattern

func (d *StampAnnotation) SetDashPattern(p []float64)

SetDashPattern writes /BS/D. The slice is copied; the caller may safely mutate p after this returns.

func (*StampAnnotation) SetName

func (a *StampAnnotation) SetName(n StampName)

SetName writes the /Name entry from a typed StampName.

func (*StampAnnotation) SetRawName

func (a *StampAnnotation) SetRawName(s string)

SetRawName writes the /Name entry from a raw string. Used for non-spec custom names. Calling SetRawName with a value not matching any spec name will cause Name() to return StampNameUnknown.

func (*StampAnnotation) SetRect

func (d *StampAnnotation) SetRect(r Rectangle)

SetRect overrides annotationBase.SetRect to regenerate /AP/N after the rectangle changes (the appearance stream's BBox is derived from /Rect).

type StampName

type StampName int

StampName names per ISO 32000-1 §12.5.6.13 Table 184. Used in /Subtype /Stamp annotations' /Name entry. Unknown handles non-spec custom names (round-tripped via RawName).

const (
	StampNameUnknown StampName = iota
	StampNameApproved
	StampNameAsIs
	StampNameConfidential
	StampNameDepartmental
	StampNameDraft // PDF default
	StampNameExperimental
	StampNameExpired
	StampNameFinal
	StampNameForComment
	StampNameForPublicRelease
	StampNameNotApproved
	StampNameNotForPublicRelease
	StampNameSold
	StampNameTopSecret
)

func (StampName) String

func (n StampName) String() string

String returns the spec name (e.g. "Approved") for diagnostics.

type StrikeOutAnnotation

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

StrikeOutAnnotation draws a horizontal line through text.

func NewStrikeOutAnnotation

func NewStrikeOutAnnotation(page *Page, rect Rectangle) *StrikeOutAnnotation

NewStrikeOutAnnotation builds an unbound strike-out annotation.

func (*StrikeOutAnnotation) AnnotationType

func (a *StrikeOutAnnotation) AnnotationType() AnnotationType

func (*StrikeOutAnnotation) Color

func (b *StrikeOutAnnotation) Color() *Color

Color returns the /C array as an RGB Color. Returns nil if /C is absent.

func (*StrikeOutAnnotation) Contents

func (b *StrikeOutAnnotation) Contents() string

Contents returns /Contents (the annotation body text).

func (*StrikeOutAnnotation) PageIndex

func (b *StrikeOutAnnotation) PageIndex() int

PageIndex returns the 1-based index of the page this annotation lives on. 0 if the annotation is not yet attached or its /P doesn't resolve.

func (*StrikeOutAnnotation) QuadPoints

func (a *StrikeOutAnnotation) QuadPoints() []QuadPoint

QuadPoints returns the array of quads describing the strike-out region. Returns nil if /QuadPoints is absent or its array length is not a multiple of 8 (malformed).

func (*StrikeOutAnnotation) Rect

func (b *StrikeOutAnnotation) Rect() Rectangle

Rect returns the annotation rectangle. Empty Rectangle if /Rect is missing or malformed.

func (*StrikeOutAnnotation) SetColor

func (b *StrikeOutAnnotation) SetColor(c *Color)

SetColor writes /C as an RGB array; nil removes the entry.

func (*StrikeOutAnnotation) SetContents

func (b *StrikeOutAnnotation) SetContents(s string)

SetContents writes /Contents (the annotation body text); empty string removes the entry.

func (*StrikeOutAnnotation) SetQuadPoints

func (a *StrikeOutAnnotation) SetQuadPoints(qp []QuadPoint)

SetQuadPoints writes /QuadPoints. nil or empty slice removes the entry.

func (*StrikeOutAnnotation) SetRect

func (b *StrikeOutAnnotation) SetRect(r Rectangle)

SetRect writes the annotation rectangle.

func (*StrikeOutAnnotation) SetTitle

func (b *StrikeOutAnnotation) SetTitle(s string)

SetTitle writes /T (the annotation author / reviewer name); empty string removes the entry.

func (*StrikeOutAnnotation) Title

func (b *StrikeOutAnnotation) Title() string

Title returns /T (the annotation author / reviewer name).

type SubmitFormAction

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

SubmitFormAction submits form field values to a URL.

func NewSubmitFormAction

func NewSubmitFormAction(url string, fields []string, flags SubmitFormFlags) *SubmitFormAction

NewSubmitFormAction builds a /SubmitForm action. The fields slice is copied; the caller may safely mutate it after this returns.

func (*SubmitFormAction) ActionType

func (a *SubmitFormAction) ActionType() ActionType

func (*SubmitFormAction) FieldNames

func (a *SubmitFormAction) FieldNames() []string

FieldNames returns a copy of the field-name list. The returned slice is owned by the caller; mutating it does not affect the action.

func (*SubmitFormAction) Flags

func (a *SubmitFormAction) Flags() SubmitFormFlags

func (*SubmitFormAction) SetFieldNames

func (a *SubmitFormAction) SetFieldNames(f []string)

SetFieldNames replaces the field-name list. The slice is copied; the caller may safely mutate f after this returns.

func (*SubmitFormAction) SetFlags

func (a *SubmitFormAction) SetFlags(f SubmitFormFlags)

func (*SubmitFormAction) SetURL

func (a *SubmitFormAction) SetURL(u string)

func (*SubmitFormAction) URL

func (a *SubmitFormAction) URL() string

type SubmitFormFlags

type SubmitFormFlags int

SubmitFormFlags is the /Flags bitfield for a /SubmitForm action per ISO 32000-1 Table 237. Bit 1 is least significant.

const (
	SubmitIncludeNoValueFields SubmitFormFlags = 1 << 1
	SubmitExportFormat         SubmitFormFlags = 1 << 2
	SubmitGetMethod            SubmitFormFlags = 1 << 3
	SubmitSubmitCoordinates    SubmitFormFlags = 1 << 4
	SubmitXFDF                 SubmitFormFlags = 1 << 5
	SubmitIncludeAppendSaves   SubmitFormFlags = 1 << 6
	SubmitIncludeAnnotations   SubmitFormFlags = 1 << 7
	SubmitSubmitPDF            SubmitFormFlags = 1 << 8
	SubmitCanonicalFormat      SubmitFormFlags = 1 << 9
	SubmitExclNonUserAnnots    SubmitFormFlags = 1 << 10
	SubmitExclFKey             SubmitFormFlags = 1 << 11
	SubmitEmbedForm            SubmitFormFlags = 1 << 13
)

type Table

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

Table is a transient builder for a tabular layout drawn onto a Page. Mirrors Aspose.PDF for .NET's Table class. After (*Page).AddTable renders the table, the *Table is not held by the document.

func NewTable

func NewTable() *Table

NewTable returns an empty table. Configure via Set* methods + AddRow. Mirrors Aspose.PDF for .NET's `new Table()` constructor.

func (*Table) AddRow

func (t *Table) AddRow() *Row

AddRow appends an empty row and returns it for further configuration.

func (*Table) AddRows

func (t *Table) AddRows(rows [][]string) []*Row

AddRows is a convenience that creates one Row per inner slice and one Cell per string in that slice. Returns the rows in insertion order so callers can apply further per-row customization (SetBackground, SetHeight, etc.).

Rows added through AddRows have plain cells — no ColSpan/RowSpan. For spanning, use the explicit AddRow + Cell.SetColSpan flow.

func (*Table) Border

func (t *Table) Border() BorderInfo

func (*Table) ColumnWidths

func (t *Table) ColumnWidths() []float64

ColumnWidths returns a copy of the column widths.

func (*Table) DefaultCellBorder

func (t *Table) DefaultCellBorder() BorderInfo

func (*Table) DefaultCellMargin

func (t *Table) DefaultCellMargin() MarginInfo

func (*Table) DefaultCellStyle

func (t *Table) DefaultCellStyle() TextStyle

func (*Table) OverflowMargins

func (t *Table) OverflowMargins() (top, bottom float64)

OverflowMargins returns the configured overflow margins (defaults 50/50 if SetOverflowMargins has not been called).

func (*Table) RepeatingRowsCount

func (t *Table) RepeatingRowsCount() int

RepeatingRowsCount returns the number of header rows that repeat on each continuation page (default 0).

func (*Table) RowCount

func (t *Table) RowCount() int

RowCount returns the number of rows.

func (*Table) Rows

func (t *Table) Rows() []*Row

Rows returns the rows in order. The slice is the live backing — do not mutate.

func (*Table) SetBorder

func (t *Table) SetBorder(b BorderInfo) *Table

func (*Table) SetColumnWidths

func (t *Table) SetColumnWidths(widths []float64) *Table

SetColumnWidths sets the column widths in points. Defensive-copies the slice.

func (*Table) SetDefaultCellBorder

func (t *Table) SetDefaultCellBorder(b BorderInfo) *Table

func (*Table) SetDefaultCellMargin

func (t *Table) SetDefaultCellMargin(m MarginInfo) *Table

func (*Table) SetDefaultCellStyle

func (t *Table) SetDefaultCellStyle(s TextStyle) *Table

func (*Table) SetOverflowMargins

func (t *Table) SetOverflowMargins(top, bottom float64) *Table

SetOverflowMargins sets the top/bottom margins (in points) used to compute the continuation-page bounding rectangle when the table overflows the original rect. Defaults: 50pt on each side.

The continuation rect uses the same LLX/URX as the original rect; the Y range becomes [bottom, pageHeight - top].

func (*Table) SetRepeatingRowsCount

func (t *Table) SetRepeatingRowsCount(n int) *Table

SetRepeatingRowsCount marks the first n rows as headers that repeat at the top of every continuation page. Default 0 (no repeat).

Mirrors Aspose.PDF for .NET's Table.RepeatingRowsCount property.

type TextAnnotation

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

TextAnnotation is a sticky-note annotation. Renders as an icon (no /AP/N — viewers draw their own icon for the /Name value). The associated /Contents is the note's body text shown in a popup when the icon is clicked.

func NewTextAnnotation

func NewTextAnnotation(page *Page, position Point) *TextAnnotation

NewTextAnnotation builds an unbound text-note annotation. Page must be non-nil. The /Rect is auto-computed as a 24×24 pt square anchored at position (Acrobat sticky-note convention).

func (*TextAnnotation) AnnotationType

func (a *TextAnnotation) AnnotationType() AnnotationType

func (*TextAnnotation) Color

func (b *TextAnnotation) Color() *Color

Color returns the /C array as an RGB Color. Returns nil if /C is absent.

func (*TextAnnotation) Contents

func (b *TextAnnotation) Contents() string

Contents returns /Contents (the annotation body text).

func (*TextAnnotation) Icon

func (a *TextAnnotation) Icon() TextIcon

Icon returns the /Name value mapped to a TextIcon. Returns TextIconNote (the spec default) if /Name is absent.

func (*TextAnnotation) Open

func (a *TextAnnotation) Open() bool

Open returns the /Open flag (whether the popup is initially shown).

func (*TextAnnotation) PageIndex

func (b *TextAnnotation) PageIndex() int

PageIndex returns the 1-based index of the page this annotation lives on. 0 if the annotation is not yet attached or its /P doesn't resolve.

func (*TextAnnotation) Rect

func (b *TextAnnotation) Rect() Rectangle

Rect returns the annotation rectangle. Empty Rectangle if /Rect is missing or malformed.

func (*TextAnnotation) RegenerateAppearance

func (a *TextAnnotation) RegenerateAppearance()

RegenerateAppearance is a no-op for TextAnnotation (no /AP — viewers render the icon themselves). Present for API symmetry across all annotation types.

func (*TextAnnotation) SetColor

func (b *TextAnnotation) SetColor(c *Color)

SetColor writes /C as an RGB array; nil removes the entry.

func (*TextAnnotation) SetContents

func (b *TextAnnotation) SetContents(s string)

SetContents writes /Contents (the annotation body text); empty string removes the entry.

func (*TextAnnotation) SetIcon

func (a *TextAnnotation) SetIcon(t TextIcon)

SetIcon writes the /Name entry. Unknown is encoded as /Note (default) to avoid producing an empty name.

func (*TextAnnotation) SetOpen

func (a *TextAnnotation) SetOpen(open bool)

SetOpen writes the /Open flag.

func (*TextAnnotation) SetRect

func (b *TextAnnotation) SetRect(r Rectangle)

SetRect writes the annotation rectangle.

func (*TextAnnotation) SetTitle

func (b *TextAnnotation) SetTitle(s string)

SetTitle writes /T (the annotation author / reviewer name); empty string removes the entry.

func (*TextAnnotation) Title

func (b *TextAnnotation) Title() string

Title returns /T (the annotation author / reviewer name).

type TextBoxField

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

TextBoxField is a single- or multi-line text input.

func (*TextBoxField) FullName

func (b *TextBoxField) FullName() string

func (*TextBoxField) IsMultiline

func (f *TextBoxField) IsMultiline() bool

func (*TextBoxField) IsPassword

func (f *TextBoxField) IsPassword() bool

func (*TextBoxField) IsReadOnly

func (b *TextBoxField) IsReadOnly() bool

func (*TextBoxField) IsRequired

func (b *TextBoxField) IsRequired() bool

func (*TextBoxField) MaxLen

func (f *TextBoxField) MaxLen() int

func (*TextBoxField) PageIndex

func (b *TextBoxField) PageIndex() int

func (*TextBoxField) PartialName

func (b *TextBoxField) PartialName() string

func (*TextBoxField) Rect

func (b *TextBoxField) Rect() Rectangle

func (*TextBoxField) SetMaxLen

func (f *TextBoxField) SetMaxLen(n int)

SetMaxLen sets the maximum number of characters. 0 removes the limit.

func (*TextBoxField) SetMultiline

func (f *TextBoxField) SetMultiline(v bool)

func (*TextBoxField) SetPassword

func (f *TextBoxField) SetPassword(v bool)

func (*TextBoxField) SetReadOnly

func (f *TextBoxField) SetReadOnly(v bool)

func (*TextBoxField) SetRequired

func (f *TextBoxField) SetRequired(v bool)

func (*TextBoxField) SetValue

func (f *TextBoxField) SetValue(s string) error

func (*TextBoxField) Value

func (f *TextBoxField) Value() string

type TextFragment

type TextFragment struct {
	Text          string
	X             float64 // horizontal position in points (from left edge)
	Y             float64 // vertical position in points (from bottom edge)
	Width         float64 // width in points
	FontName      string  // e.g. "Helvetica", "Arial-BoldMT"
	FontSize      float64 // effective size in points
	Height        float64 // text height in points (from ascent/descent metrics)
	Bold          bool
	Italic        bool
	CharSpacing   float64 // character spacing (Tc operator) in text space units
	Color         Color   // fill color
	IsSubscript   bool    // Y is below the line baseline
	IsSuperscript bool    // Y is above the line baseline
}

TextFragment represents a contiguous run of text with uniform font.

type TextIcon

type TextIcon int

TextIcon names per ISO 32000-1 §12.5.6.4 Table 172, used in /Subtype /Text annotations' /Name entry.

const (
	TextIconUnknown TextIcon = iota
	TextIconComment
	TextIconKey
	TextIconNote // PDF default if /Name is absent
	TextIconHelp
	TextIconNewParagraph
	TextIconParagraph
	TextIconInsert
)

type TextLine

type TextLine struct {
	Text      string  // concatenated text of all fragments (with spaces)
	Y         float64 // vertical position in points (from bottom edge)
	Fragments []TextFragment
}

TextLine represents a horizontal line of text fragments at a common Y position.

type TextStyle

type TextStyle struct {
	Font          Font    // nil defaults to FontHelvetica in AddText
	Size          float64 // in points; 0 treated as 12
	Color         *Color  // nil → black opaque {0,0,0,1}
	Background    *Color  // nil → no background
	HAlign        HAlign  // default: HAlignLeft
	VAlign        VAlign  // default: VAlignTop
	LineSpacing   float64 // multiplier of font size; 0 treated as 1.2
	Underline     bool
	Strikethrough bool
	Rotation      float64 // degrees counter-clockwise; pivot = lower-left corner of rect; default 0
	Behind        bool    // if true, text is drawn under existing page content; default false
}

TextStyle defines reusable text formatting properties.

type UnderlineAnnotation

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

UnderlineAnnotation draws a horizontal line under text.

func NewUnderlineAnnotation

func NewUnderlineAnnotation(page *Page, rect Rectangle) *UnderlineAnnotation

NewUnderlineAnnotation builds an unbound underline annotation.

func (*UnderlineAnnotation) AnnotationType

func (a *UnderlineAnnotation) AnnotationType() AnnotationType

func (*UnderlineAnnotation) Color

func (b *UnderlineAnnotation) Color() *Color

Color returns the /C array as an RGB Color. Returns nil if /C is absent.

func (*UnderlineAnnotation) Contents

func (b *UnderlineAnnotation) Contents() string

Contents returns /Contents (the annotation body text).

func (*UnderlineAnnotation) PageIndex

func (b *UnderlineAnnotation) PageIndex() int

PageIndex returns the 1-based index of the page this annotation lives on. 0 if the annotation is not yet attached or its /P doesn't resolve.

func (*UnderlineAnnotation) QuadPoints

func (a *UnderlineAnnotation) QuadPoints() []QuadPoint

QuadPoints returns the array of quads describing the underlined region. Returns nil if /QuadPoints is absent or its array length is not a multiple of 8 (malformed).

func (*UnderlineAnnotation) Rect

func (b *UnderlineAnnotation) Rect() Rectangle

Rect returns the annotation rectangle. Empty Rectangle if /Rect is missing or malformed.

func (*UnderlineAnnotation) SetColor

func (b *UnderlineAnnotation) SetColor(c *Color)

SetColor writes /C as an RGB array; nil removes the entry.

func (*UnderlineAnnotation) SetContents

func (b *UnderlineAnnotation) SetContents(s string)

SetContents writes /Contents (the annotation body text); empty string removes the entry.

func (*UnderlineAnnotation) SetQuadPoints

func (a *UnderlineAnnotation) SetQuadPoints(qp []QuadPoint)

SetQuadPoints writes /QuadPoints. nil or empty slice removes the entry.

func (*UnderlineAnnotation) SetRect

func (b *UnderlineAnnotation) SetRect(r Rectangle)

SetRect writes the annotation rectangle.

func (*UnderlineAnnotation) SetTitle

func (b *UnderlineAnnotation) SetTitle(s string)

SetTitle writes /T (the annotation author / reviewer name); empty string removes the entry.

func (*UnderlineAnnotation) Title

func (b *UnderlineAnnotation) Title() string

Title returns /T (the annotation author / reviewer name).

type VAlign

type VAlign int

VAlign specifies vertical text alignment within a rectangle.

const (
	VAlignTop VAlign = iota // default
	VAlignMiddle
	VAlignBottom
)

type ValidationIssue

type ValidationIssue struct {
	Code    string // e.g. "INVALID_HEADER", "XREF_ERROR", "OBJECT_ERROR", "PAGE_TREE_ERROR", "ENCRYPTED"
	Message string
}

ValidationIssue describes a single problem found in a PDF file.

type ValidationReport

type ValidationReport struct {
	// Valid is true when no issues were found.
	Valid  bool
	Issues []ValidationIssue
}

ValidationReport is returned by Validate and summarises the structural integrity of a PDF.

func Validate

func Validate(inputPath string) (*ValidationReport, error)

Validate checks a PDF file for structural integrity. It verifies the file header, cross-reference table, all indirect objects, and the page tree. Encrypted documents are flagged with an ENCRYPTED issue but are not treated as invalid.

A non-nil error is returned only for I/O failures (file not found, etc.). PDF-level problems are reported inside ValidationReport.Issues.

Example:

report, err := asposepdf.Validate("document.pdf")
if err != nil {
    log.Fatal(err)
}
if !report.Valid {
    for _, issue := range report.Issues {
        fmt.Println(issue.Code, issue.Message)
    }
}

type WidgetAnnotation

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

WidgetAnnotation is the read-only view of a form widget annotation surfaced through AnnotationCollection. Form fields continue to be mutated via the Form API — a WidgetAnnotation only exposes the base Annotation surface (Rect, Color, Title, Contents, PageIndex).

func (*WidgetAnnotation) AnnotationType

func (a *WidgetAnnotation) AnnotationType() AnnotationType

func (*WidgetAnnotation) Color

func (b *WidgetAnnotation) Color() *Color

Color returns the /C array as an RGB Color. Returns nil if /C is absent.

func (*WidgetAnnotation) Contents

func (b *WidgetAnnotation) Contents() string

Contents returns /Contents (the annotation body text).

func (*WidgetAnnotation) PageIndex

func (b *WidgetAnnotation) PageIndex() int

PageIndex returns the 1-based index of the page this annotation lives on. 0 if the annotation is not yet attached or its /P doesn't resolve.

func (*WidgetAnnotation) Rect

func (b *WidgetAnnotation) Rect() Rectangle

Rect returns the annotation rectangle. Empty Rectangle if /Rect is missing or malformed.

func (*WidgetAnnotation) SetColor

func (b *WidgetAnnotation) SetColor(c *Color)

SetColor writes /C as an RGB array; nil removes the entry.

func (*WidgetAnnotation) SetContents

func (b *WidgetAnnotation) SetContents(s string)

SetContents writes /Contents (the annotation body text); empty string removes the entry.

func (*WidgetAnnotation) SetRect

func (b *WidgetAnnotation) SetRect(r Rectangle)

SetRect writes the annotation rectangle.

func (*WidgetAnnotation) SetTitle

func (b *WidgetAnnotation) SetTitle(s string)

SetTitle writes /T (the annotation author / reviewer name); empty string removes the entry.

func (*WidgetAnnotation) Title

func (b *WidgetAnnotation) Title() string

Title returns /T (the annotation author / reviewer name).

Jump to

Keyboard shortcuts

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