Help us shape the future of Go! Take the 2026 Go Developer Survey

asposepdf

package module
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: MIT Imports: 54 Imported by: 22

README

Aspose.PDF FOSS for Go

test lint Go Reference Go Version

Aspose.PDF FOSS for Go

A pure Go PDF library — no CGo, no native libraries, no third-party package dependencies (standard library only), MIT-licensed. It creates, edits, renders, signs, encrypts, converts, and validates PDF documents: split/merge/extract pages, extract and search text, fill and build AcroForms, draw text/vector graphics/tables, embed and subset fonts, apply digital signatures (PKCS#7, PAdES, timestamps), validate and convert PDF/A, author accessible Tagged PDF, and render pages to images with a built-in rasterizer that has no third-party package dependencies of its own, convert to and from Markdown, HTML, and SVG, and query documents through a set of AI copilots over any OpenAI-compatible endpoint.

The API shape mirrors Aspose.PDF for .NET where natural, so concepts transfer directly for developers coming from that library, and spec references throughout follow ISO 32000-1 (PDF 1.7) and ISO 32000-2 (PDF 2.0). This project is not to be confused with aspose-pdf-go-cpp (a CGo wrapper around a native library) — it is 100% Go source, go get and cross-compile anywhere.

Navigation

At a Glance

flowchart TD
  subgraph StartingPoints["Starting Points"]
    direction LR
    i1["An existing PDF document (including encrypted)"]
    i2["Nothing — authored from scratch"]
  end
  PRODUCT["Aspose.PDF FOSS for Go"]
  subgraph Capabilities["Core Capabilities"]
    direction LR
    subgraph capl[" "]
      direction TB
      c1["Page-level operations (split, merge, extract, impose)"]
      c2["Encryption and digital signatures"]
      c3["Content authoring via the Flow layout engine"]
      c4["Tables and vector graphics"]
      c5["AcroForm fields"]
      c6["Annotations, bookmarks, redaction, and portfolios"]
      c7["Stamps and watermarks"]
    end
    subgraph capr[" "]
      direction TB
      c8["Tagged PDF and PDF/UA accessibility"]
      c9["PDF/A and structural validation"]
      c10["Rendering to raster images"]
      c11["HTML, SVG, and Markdown conversion"]
      c12["AI copilots"]
      c13["Text extraction, search, and replace"]
      c14["Table detection and Office/eBook conversion"]
    end
  end
  subgraph Outputs["Outputs"]
    direction TB
    o1["PDF documents (file path or in-memory stream)"]
    o2["PNG, JPEG, GIF, BMP, and TIFF raster images"]
    o3["HTML (single-file)"]
    o4["SVG"]
    o5["Markdown"]
    o6["Plain text"]
    o7["DOCX (Word), XLSX (Excel), and EPUB"]
  end
  StartingPoints --> PRODUCT --> Capabilities --> Outputs

Key Capabilities

  • Page-level operations and metadata — Document.Split() breaks a document into per-page documents; Extract builds a new document from selected PageRanges without touching the source; Append combines multiple PDFs into one by merging another document's pages in place; Rotate/SetRotation turn pages, and Reorder rearranges them by an explicit 1-based index slice (repeats and omissions both allowed); Document.NUp/Document.Booklet (NUp/Booklet) impose pages onto larger sheets for N-up printing or saddle-stitch binding, each returning a new document built from Form XObjects and leaving the source untouched; and blank PDFs can be created from scratch with NewDocument/NewDocumentFromFormat. Each *Page exposes its own Number(), Size() (a PageSize{Width, Height} in points), and Rotation() getters, and page geometry (MediaBox/CropBox/TrimBox/BleedBox/ArtBox) is readable and, via SetMediaBox/SetCropBox/SetTrimBox/SetBleedBox/SetArtBox (plus the SetPageSize shorthand for resizing the MediaBox), writable without scaling existing content; the /Info dictionary round-trips through Document.Info()/SetInfo()/ClearInfo() and a DocumentInfo struct, distinct from the XMP metadata packet available via Document.XMP()/SetXMP()/ClearXMP() (backed by the /Catalog/Metadata stream, with a raw XMPRaw()/SetXMPRaw() escape hatch and SyncInfoToXMP() to mirror /Info into XMP); and the /PageLabels numbering tree is written with Document.SetPageLabels (roman/decimal/alphabetic styles, prefix, and start value per range) and read back per-page via Page.Label().
  • Encryption and digital signatures — Document.SetPassword(userPassword, ownerPassword) password-protects the document on save with AES-128 (/CFM /AESV2), AES-256 (/CFM /AESV3, bumps the file to PDF 2.0), or RC4-128 and granular viewer permissions (print, copy, modify, annotate, fill, accessibility, assemble); sign with a PKCS#7-detached signature (SHA-256, RSA or ECDSA) that can be PAdES, a DocMDP certification, and/or carry an RFC 3161 trusted timestamp, over plain or already-encrypted documents, with support for multiple incremental signatures and verification via VerifySignatures — optionally asking the issuer whether the signing certificate was revoked (OCSP or CRL, network opt-in through ValidationOptions) and embedding that evidence as a /DSS with AddValidationInfo, so the signature still verifies after the certificate expires (LTV). Keys are passed as a standard crypto.Signer plus *x509.Certificate — no .p12 file required. Documents can also be encrypted for certificate recipients instead of a password (EncryptionOptions.Recipients, the /Adobe.PubSec handler): each recipient gets its own permissions, and the file opens with OpenWithCertificate(path, cert, key) for any crypto.Decrypter.
  • Content authoring with the Flow layout engine — Document.NewFlow lays out paragraphs, headings, images, tables, and lists top-to-bottom with automatic pagination; floating boxes (absolute, in-flow, or floated with text wrap-around) and multi-column layout are built on the same engine; FlowOptions.Tagged auto-tags every element for a one-call PDF/UA-conformant document.
  • Tables and vector graphics — pdf.NewTable() builds multi-page tables with repeating header rows (auto-fit or explicit Row.SetHeight), cell merging via Cell.SetColSpan/SetRowSpan, per-cell styling, and image cells via Cell.SetImage, rendered onto a page with (*Page).AddTable(t, rect); (*Page).DrawLine/DrawRectangle/DrawCircle/ DrawPath and friends draw first-class vector content directly on a page, and a Path fluent builder (MoveTo/LineTo/CurveTo/QuadTo/Arc/Close) covers arbitrary shapes; fills support solid colours, ShapeStyle.FillGradient (linear or radial), and Document.CreateTilingPattern(w, h) repeating-motif tiling patterns.
  • AcroForms — read, and build from scratch every standard field type with AddTextField/AddCheckbox/AddRadioGroup/AddComboBox/AddListBox/AddPushButton (plus the typed password/file-select/rich-text/number/date variants — behavior flags exposed as /Ff on the underlying field dictionary) and remove one with RemoveField; AddBarcodeField draws Code128, QR, or PDF417 symbols in place of text, encoded by this library's own pure-Go encoders (no external dependency); Field.SetStyle/Style() control widget appearance (border, background, font), and (*ButtonField).SetAppearance gives push buttons distinct normal/rollover/down captions and an icon; field values round-trip as typed JSON, FDF, and XFDF for template-fill and Acrobat-interoperable data interchange.
  • Annotations, bookmarks, and redaction — the full ISO 32000-1 markup/drawing annotation family with auto-regenerated appearance streams, hierarchical outlines (OutlineItemCollection) and named destinations with all 8 PDF destination types, and mark-then-apply redaction that irreversibly removes text, images, and paths from the marked regions. Document.Flatten()/ Form.Flatten() bake interactive fields and annotations into static page content so the result renders identically but is no longer editable.
  • Attachments and portfolios — Document.EmbeddedFiles() attaches, reads back, and removes document-level files through the /Catalog/Names/EmbeddedFiles name tree, while Document.Collection() turns those attachments into a PDF portfolio: a schema of custom columns (Schema().Add("Amount", "Total", CollectionFieldNumber)), per-file values via EmbeddedFile.CollectionItem(), an initial file, a sort order, and a details/tiles/hidden presentation mode — so viewers show a navigable table instead of a plain attachment list, and the cover page still opens anywhere.
  • Tagged PDF and PDF/UA accessibility — Document.TaggedContent() builds a logical structure tree as content is drawn (TagContent, AddTaggedTable, AddTaggedList), links and other annotations join the tree via StructElement.AddObjectReference (an /OBJR to the annotation itself, not marked content), and Document.ValidatePDFUA() reports the PDF/UA-1 prerequisites still missing.
  • PDF/A and structural validation — Validate checks structural integrity; ValidatePDFA(PDFA1B/2B/3B/1A/2A/3A) reports archival-conformance violations; ConvertToPDFA moves a document toward conformance in one call (strips encryption/JavaScript, embeds non-embedded Standard-14 fonts, adds an sRGB ICC OutputIntent, writes the pdfaid XMP packet).
  • E-invoices (ZUGFeRD / Factur-X) — Document.AttachInvoice(xml) turns a document into a hybrid e-invoice: the CII XML is embedded as factur-x.xml with the associated-file relationship its profile calls for, the Factur-X metadata and extension schema are written, and the document is converted to PDF/A-3. Document.Invoice() extracts the invoice from incoming Factur-X and ZUGFeRD 2.x/1.0 files together with its profile. Attachments also gain PDF/A-3 associated-file relationships (EmbeddedFile.SetAFRelationship).
  • Rendering to raster images — a pure-Go anti-aliased renderer with no third-party package dependencies of its own (its own rasterizer — no golang.org/x/image, no cgo) draws vector graphics, images (including CCITT fax, JBIG2, and JPEG2000 (/JPXDecode) scans), and text (embedded and non-embedded via a FontRepository covering .ttc/.otf faces, including non-embedded CJK) to PNG, JPEG, GIF, BMP, and single- or multi-page TIFF via Page.RenderImage/RenderPNG/RenderTIFF/… and Document.RenderTIFF.
  • HTML, SVG, and Markdown conversion — SaveHTML exports a single-file HTML document with no external assets in four modes (faithful raster, visible text, native SVG-per-page, and reflowable), including fillable AcroForm controls; in text/native modes, embedded TrueType/ OpenType fonts are re-wrapped as WOFF @font-face data URLs with a browser cmap synthesized from the font's /ToUnicode mapping, so text renders in the document's real faces. SaveSVG exports standalone true-vector SVG pages with all binary parts embedded as data: URLs by default, or externalized via ResourceWriter, and AddSVG imports SVG 1.1 content (shapes, gradients, clipping, masks) back onto a page; MarkdownToDocument renders CommonMark + GFM as a paginated PDF (652/652 on the official test suite), Flow.AddMarkdown mixes Markdown into a Flow document, Page.AddMarkdown(md, rect) draws it into a Rectangle on an existing page, and SaveMarkdown re-assembles a PDF as GFM Markdown.
  • Stamps and watermarks — Document.AddTextWatermark/AddSVGWatermark overlay a text or SVG watermark across selected pages (or every page); (*Page).AddStamp/(*Document).AddStamp place a TextStamp, ImageStamp, or PageNumberStamp on one or more pages.
  • Table detection and Office/eBook conversion — TableAbsorber (Visit(page) then TableList()) recognizes ruled and borderless tables directly from a page's vector geometry (no rasterization), with conservative guards so ordinary prose, lists, TOCs, and code listings are never mistaken for tables. This feeds Document.SaveDocx/WriteDocx (a pure-stdlib OOXML writer producing styled runs, heading styles, hyperlinks, and lists, plus real Word tables — EnhancedFlow, the default mode — from detected table structure), Document.SaveXlsx/ WriteXlsx (detected tables become Excel worksheets with real numeric cells, merged cells, and header shading, or a full-page cell-per-line mode), and Document.SaveEpub/WriteEpub (a reflowable, spec-correct OCF-container EPUB 3 book with chapters split at headings and a real navigation TOC).
  • Document comparison — CompareDocumentsPageByPage and CompareFlatDocuments report what changed between two PDFs word by word, with the page and rectangle of every difference; ComparisonResult.SaveMarkup writes a copy of either document in which insertions are highlighted, deletions struck out and removed text kept in the annotation note, so a reviewer reads the change list in any PDF viewer. GraphicalPdfComparer.GetDifference catches what the word comparer can't — moved or edited graphics, font substitution — by rasterizing both pages and diffing pixels, reporting a changed-pixel ratio and a difference image; SideBySideComparePages/ SideBySideCompareDocuments lay the marked-up before/after side by side in one vector spread PDF. HTMLDiffOutputGenerator/JSONDiffOutputGenerator/MarkdownDiffOutputGenerator/ PDFDiffOutputGenerator serialize the same differences as an HTML fragment, JSON, GFM Markdown, or a generated, colored PDF report. Mirrors Aspose.PDF for .NET's TextPdfComparer, GraphicalPdfComparer, SideBySidePdfComparer and the Aspose.Pdf.Comparison.OutputGenerator namespace.
  • AI copilots — the ai subpackage adds document summarization (SummaryCopilot), OCR of scanned pages with a MakeSearchable pipeline that writes recognized text back as an invisible, selectable layer, document Q&A with conversation history (ChatCopilot), and automatic /Alt text generation for tagged figures (ImageDescriptionCopilot), over any OpenAI-compatible endpoint.
  • Text extraction, fonts, and optimization — extract text in visual or raw reading order (TextExtractOptions{Mode: TextExtractRaw}) with full layout info, recover paragraph/column structure (Paragraphs()), search and replace text in place, embed and subset TrueType/ OpenType fonts (.ttf/.otf/.ttc) — Document.LoadFont/Document.LoadFontByName("Calibri", bold, italic) resolve faces by family name via a pluggable FontRepository, and Document.SubsetFonts() rebuilds each embedded font's own glyph tables (glyf/loca/hmtx/ CIDToGIDMap) down to only the glyphs actually used; custom glyphs can also be authored outright with Document.CreateType3Font() — Type3Font.AddGlyph(rune, width) hands back a drawing canvas in glyph space, so a symbol drawn with the vector API becomes a real font character whose text still extracts and searches (an embedded ToUnicode CMap carries the mapping); Document.RemoveUnusedObjects() deletes every object that neither a page nor the document catalog uses (metadata, bookmarks, attachments and the structure tree are kept) and returns the removed count on its own, or fold that same cleanup into a larger pass with the unified Document.Optimize pass (DefaultOptimizationOptions() is the safe, lossless preset — remove unused objects, subset fonts, Flate-compress and dedupe streams, pack objects into object streams; opt into lossy image recompression via OptimizationOptions.Images, or into dropping a Helvetica/Times/Courier font's own embedded program via OptimizationOptions.UnembedFonts) or the image-only Document.OptimizeImages(OptimizeImageOptions) pass (max DPI downscaling, JPEG quality, and PNG→JPEG conversion); reduce file size further with Document.SaveLinearized/WriteToLinearized (linearized/fast-web-view output per ISO 32000-1 Annex F, so viewers can render page 1 before the whole file downloads), or ConvertToGrayscale.

Installation

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

Requires Go 1.24 or newer. The module has no transitive dependencies — everything is built on the Go standard library, including the PDF parser/writer, the raster renderer, the SVG and Markdown engines, and the PKCS#7/CMS signing code.

Dependencies

Required Package Dependencies

No required third-party package dependencies.

Native and System Requirements
  • Go 1.24 or later (go.mod's own go 1.24 directive).

Quick Start

package main

import (
	"fmt"
	"log"

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

func main() {
	// Open a PDF and split it into per-page documents.
	doc, err := pdf.Open("input.pdf")
	if err != nil {
		log.Fatal(err)
	}
	pages, err := doc.Split()
	if err != nil {
		log.Fatal(err)
	}
	for i, p := range pages {
		p.Save(fmt.Sprintf("page%03d.pdf", i+1))
	}

	// Merge two PDFs into one — Append mutates the receiver in place.
	a, _ := pdf.Open("file1.pdf")
	b, _ := pdf.Open("file2.pdf")
	a.Append(b)
	fmt.Println("merged:", a.PageCount(), "pages")
	a.Save("merged.pdf")
}

See _examples/ for full runnable programs covering text, forms, annotations, tables, vector graphics, SVG, and the end-to-end feature_showcase demo, or short focused API snippets under "Examples" on pkg.go.dev.

Feature Showcase

Feature showcase preview

docs/feature_showcase.pdf is a single 20-page PDF generated by _examples/feature_showcase that walks nearly every capability above in one document — a clickable table of contents (built with Page.AddTOC), styled AcroForm fields, Code128 / QR / PDF417 barcode fields, transparency flattening shown as real before/after renders, all four stamp types, a word-level document comparison, the full annotation gallery, redactions, multi-page tables, vector graphics, and a meta "Rendering & Imposition" page whose thumbnails are renders of the document itself, produced by this library's own renderer. Cross-cutting metadata — bookmarks, named destinations, page labels, and Info + XMP metadata — is set once and carried through the whole document. The showcase itself is deliberately left unencrypted so it previews inline on GitHub and opens in every viewer; encryption (RC4 / AES-128 / AES-256) is covered in Encryption and Signing below. Regenerate it locally with go run ./_examples/feature_showcase.

Additional Examples

The most representative example beyond Quick Start is building a document from scratch with the Flow layout engine — an additive layer over the Rectangle-based drawing API that computes the rectangles for you — rather than editing an existing one.

Content Authoring With the Flow Layout Engine
doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
flow := doc.NewFlow(pdf.FlowOptions{})
flow.AddHeading(1, "Quarterly Report", pdf.TextStyle{})
flow.AddParagraph("Revenue grew in every region this quarter.", pdf.TextStyle{Size: 11})
flow.AddList([]string{"North: +12%", "South: +8%"}, false, pdf.TextStyle{Size: 11})

pages, err := flow.Render()
if err != nil {
	log.Fatal(err)
}
fmt.Println("pages:", pages)

NewFlow returns a *Flow that lays chained AddParagraph/AddHeading/AddImage/AddTable/ AddList calls out top-to-bottom, paginating automatically; Render() returns the number of pages produced. FlowOptions.Tagged auto-tags every element for a one-call PDF/UA-conformant document.

View Additional Code Examples
Encrypt a Document
doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
doc.SetEncryption(pdf.EncryptionOptions{
	UserPassword:  "secret",
	OwnerPassword: "owner-secret",
	Permissions:   &pdf.Permissions{AllowPrint: true, AllowCopy: true},
	Algorithm:     pdf.EncryptionAlgAES128,
})

var buf bytes.Buffer
if _, err := doc.WriteTo(&buf); err != nil {
	log.Fatal(err)
}

// The file is now encrypted; Open returns ErrEncrypted.
if _, err := pdf.OpenStream(&buf); err != nil {
	fmt.Println("encrypted")
}
Digitally Sign and Verify
key, _ := ecdsa.GenerateKey(elliptic.P256(), cryptorand.Reader)
tmpl := &x509.Certificate{
	SerialNumber: big.NewInt(1),
	Subject:      pkix.Name{CommonName: "Jane Signer"},
	NotBefore:    time.Now().Add(-time.Hour),
	NotAfter:     time.Now().Add(24 * time.Hour),
	KeyUsage:     x509.KeyUsageDigitalSignature,
}
der, _ := x509.CreateCertificate(cryptorand.Reader, tmpl, tmpl, &key.PublicKey, key)
cert, _ := x509.ParseCertificate(der)

doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
if err := doc.Sign(pdf.SignOptions{Certificate: cert, PrivateKey: key, Reason: "Approval"}); err != nil {
	log.Fatal(err)
}
var buf bytes.Buffer
if _, err := doc.WriteTo(&buf); err != nil {
	log.Fatal(err)
}

signed, _ := pdf.OpenStream(&buf)
sigs, err := signed.VerifySignatures()
if err != nil {
	log.Fatal(err)
}
fmt.Printf("signatures: %d, valid: %v, reason: %s\n", len(sigs), sigs[0].Valid, sigs[0].Reason)
Build a Table
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")
Render a Page to an Image
doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
page, _ := doc.Page(1)
_ = page.AddText("Preview me", pdf.TextStyle{Size: 24},
	pdf.Rectangle{LLX: 50, LLY: 700, URX: 545, URY: 780})

img, err := doc.RenderImage(1, pdf.RenderOptions{DPI: 96})
if err != nil {
	log.Fatal(err)
}
fmt.Println("rendered:", img.Bounds().Dx() > 0 && img.Bounds().Dy() > 0)

API Reference

The public API lives in the single root package asposepdf (imported as pdf), centered on Document — opened via Open/OpenStream/OpenWithPassword/OpenStreamWithPassword (the stream forms take any io.Reader) and serialized via Document.WriteTo (implements io.WriterTo, so it writes to any io.Writer); its Pages() method returns live *Page views, and nearly every mutating method (rotation, reorder, metadata, passwords, …) modifies the receiver in place; Split and Extract are the two exceptions, each returning a fresh, fully independent *Document. AI copilots live in the separate ai subpackage so the root package stays free of network code.

View the Full Core API Surface
Core API
Class Description
AFRelationship AFRelationship says how an embedded file relates to the document.
AIClient AIClient is the contract every copilot consumes: one call, one chat completion.
APIError APIError is returned when the AI endpoint answers with a non-2xx status.
Action Action is the common interface implemented by every concrete action type.
ActionType ActionType identifies the kind of action attached to an annotation (typically a LinkAnnotation's /A entry).
Annotation Annotation is the common interface implemented by every concrete annotation type.
AnnotationCollection AnnotationCollection is the live, ordered set of annotations attached to a single page.
AnnotationType AnnotationType identifies the kind of annotation.
BmpDevice BmpDevice renders a page to BMP.
BookletBinding BookletBinding selects the binding edge of a booklet.
BookletOptions BookletOptions configures Booklet imposition.
BorderEffect BorderEffect controls the /BE/S entry per ISO 32000-1 §12.5.4 Table 167.
BorderInfo BorderInfo describes a border drawn around a table or cell.
BorderSide BorderSide is a bitmask selecting which sides of a rectangular border are drawn.
BorderStyle BorderStyle controls the /BS dict for drawing annotations per ISO 32000-1 §12.5.4 Table 168.
ButtonAppearance ButtonAppearance configures a push button's rich appearance: separate captions for the normal / rollover / down states, an optional icon image, and face/border/text colours.
ButtonField ButtonField is a push button — action only, no value semantics.
ButtonIconPosition ButtonIconPosition controls how a push button lays out its icon and caption — the /MK /TP entry per ISO 32000-1 §12.5.6.19 Table 189.
CaretAnnotation CaretAnnotation marks a point of text insertion or deletion, drawn as an upward caret ("^") filled with the annotation colour; an optional paragraph symbol is set with SetSymbol(pdf.CaretSymbolParagraph).
CaretSymbol CaretSymbol is the /Sy entry of a Caret annotation per ISO 32000-1 §12.5.6.11 Table 180 — an optional symbol drawn together with the caret to associate it with an editing action.
Cell Cell is a single cell within a Row.
CertifyPermission CertifyPermission is the DocMDP permission level of a certification signature (ISO 32000-1 §12.8.2.2 Table 254).
ChatCopilot ChatCopilot answers questions about a document, keeping conversation history.
ChatOptions ChatOptions configures a ChatCopilot.
CheckboxField CheckboxField is a checkbox with on/off state.
ChoiceOption ChoiceOption is one option of a ComboBoxField or ListBoxField.
CircleAnnotation CircleAnnotation draws an elliptical annotation.
Collection Collection is the document's portfolio view over its embedded files.
CollectionField CollectionField is one portfolio column.
CollectionFieldType CollectionFieldType is a schema column's data type (the collection field's /Subtype).
CollectionItem CollectionItem holds one attachment's values for the portfolio's schema fields.
CollectionSchema CollectionSchema is the portfolio's set of columns.
CollectionView CollectionView selects how a viewer presents the portfolio's files.
Color Color represents an RGBA color with values in [0, 1].
ComboBoxField ComboBoxField is a single-select dropdown choice field.
CompletionRequest CompletionRequest describes one chat-completion call.
CompletionResponse CompletionResponse is the model's reply.
DateField DateField is a text field with a JavaScript date-format action and a format mask (e.g. "mm/dd/yyyy").
Destination Destination is the common interface for all explicit destinations.
DestinationFit DestinationFit — [page /Fit].
DestinationFitB DestinationFitB — [page /FitB].
DestinationFitBH DestinationFitBH — [page /FitBH top].
DestinationFitBV DestinationFitBV — [page /FitBV left].
DestinationFitH DestinationFitH — [page /FitH top].
DestinationFitR DestinationFitR — [page /FitR left bottom right top].
DestinationFitV DestinationFitV — [page /FitV left].
DestinationType DestinationType identifies the destination flavor.
DestinationXYZ DestinationXYZ — [page /XYZ left top zoom].
Document Document is a PDF document.
DocumentInfo DocumentInfo contains document information from the PDF Info dictionary.
EmbeddedFile EmbeddedFile is one attachment: a /Filespec dictionary with an embedded stream.
EmbeddedFiles EmbeddedFiles is the document's collection of attached (embedded) files — the /Catalog/Names/EmbeddedFiles name tree (ISO 32000-1 §7.11.4).
EncryptionAlgorithm EncryptionAlgorithm selects the cipher and security-handler revision used by (*Document).SetEncryption.
EncryptionOptions EncryptionOptions bundles every knob that controls how a document is encrypted when saved.
Field Field is the common interface implemented by every concrete form field type (TextBoxField, CheckboxField, RadioButtonField, etc.).
FieldStyle FieldStyle is the visual styling applied to a form field's widget(s).
FigureAlt FigureAlt is a /Figure structure element that has no alternate text, paired with the image it brackets (when resolvable).
FileAttachmentAnnotation FileAttachmentAnnotation embeds a file in the document and shows an icon at the annotation's /Rect.
FileAttachmentIcon FileAttachmentIcon names per ISO 32000-1 §12.5.6.15 Table 178.
FileSelectBoxField FileSelectBoxField is a text field whose value is a file path (FileSelect flag), used to attach a local file on submit.
FloatSide FloatSide selects which edge a floated box hugs while text wraps around it.
FloatingBox FloatingBox is a positioned content container (Tier 2 of the flow model): a box with an optional border, background and padding that lays its own content (paragraphs, headings, images, lists) inside its width.
Flow Flow is a document generator that lays content out top-to-bottom and paginates automatically — the "flow" counterpart to the Rectangle-based drawing API.
FlowOptions FlowOptions configures a Flow.
Font Font is implemented by standard 14 fonts and embedded TTF fonts.
Form Form is the document's AcroForm view.
FormFieldType FormFieldType identifies the kind of form field.
FreeTextAnnotation FreeTextAnnotation displays text directly on the page, rendered into /AP/N using an embedded font.
FreeTextIntent FreeTextIntent per ISO 32000-1 §12.5.6.6 /IT entry.
GenericAnnotation GenericAnnotation is the catch-all surface for /Subtype values this release does not yet model (Stamp, FreeText, Ink, etc.).
GifDevice GifDevice renders a page to GIF.
GoToAction GoToAction navigates to a page within the same document.
GoToURIAction GoToURIAction opens a URI in the user's default handler (typically a web browser).
Gradient Gradient is a fill that varies colour across a shape: either a LinearGradient or a RadialGradient.
GradientStop GradientStop is one colour stop in a gradient, positioned at Offset (0 at the gradient's start, 1 at its end).
HAlign HAlign specifies horizontal text alignment within a rectangle.
HTMLMode HTMLMode selects how SaveHTML / WriteHTML represents page text.
HTMLSaveOptions HTMLSaveOptions configures SaveHTML / WriteHTML.
HighlightAnnotation HighlightAnnotation marks a region with semi-transparent highlight color.
Image Image holds an extracted image with its encoded data and metadata.
ImageColorSpace ImageColorSpace describes the original color space of the image in the PDF.
ImageDescriptionCopilot ImageDescriptionCopilot describes images with a vision model.
ImageDescriptionOptions ImageDescriptionOptions configures an ImageDescriptionCopilot.
ImageFormat ImageFormat describes the output format of an extracted image.
ImageInfo ImageInfo holds metadata about an image found on a page without decoding pixel data.
ImageStamp ImageStamp overlays a raster image (PNG or JPEG), stretched to fill Rect.
ImageToDocumentOptions ImageToDocumentOptions controls page sizing for ImageToDocument.
InkAnnotation InkAnnotation draws a series of free-form strokes — typically used to represent handwritten ink.
Invoice Invoice is an e-invoice found in a document.
InvoiceOptions InvoiceOptions configures AttachInvoice.
InvoiceProfile InvoiceProfile is the Factur-X / ZUGFeRD conformance level of an invoice.
JSONExportOptions JSONExportOptions controls (*Form).ExportJSON / WriteJSON.
JavaScriptAction JavaScriptAction holds a JavaScript snippet attached to an annotation.
JavaScriptCollection JavaScriptCollection is the document-level JavaScript store, backed by the /Catalog/Names/JavaScript name tree (ISO 32000-1 §7.7.4 / §8.5.1).
JpegDevice JpegDevice renders a page to JPEG.
LLMOCREngine LLMOCREngine recognizes text by sending the page image to a vision-capable chat model.
LLMOCROptions LLMOCROptions configures the vision-model OCR engine.
Layer Layer is one Optional Content Group (OCG) in the document, created with Document.AddLayer(name), bracketed on a page with Page.BeginLayer/EndLayer, and toggled with Layer.SetVisible.
LineAnnotation LineAnnotation draws a straight line between two points, with optional line endings on each end (arrows, circles, etc.
LineCap LineCap is the /J line cap style per ISO 32000-1 §8.4.3.3 Table 54.
LineEndingStyle 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.
LineJoin LineJoin is the /j line join style per ISO 32000-1 §8.4.3.4 Table 55.
LineStyle LineStyle describes how a stroked path is drawn.
LinearGradient LinearGradient interpolates colour along the line from (X1, Y1) to (X2, Y2).
LinkAnnotation LinkAnnotation is a clickable region.
LinkHighlightMode LinkHighlightMode controls the visual feedback when the link is activated by the user (the /H entry per ISO 32000-1 §12.5.6.5).
ListBoxField ListBoxField is a single- or multi-select list choice field.
MarginInfo MarginInfo describes margins or padding in points: Top / Right / Bottom / Left.
MarkdownOptions MarkdownOptions configures Markdown rendering.
MarkdownSaveOptions MarkdownSaveOptions configures SaveMarkdown / WriteMarkdown.
MarkupParagraph MarkupParagraph is a run of consecutive lines forming one paragraph.
MarkupSection MarkupSection is a column of paragraphs (left-to-right across the page).
Message Message is a single chat message.
MessageImage MessageImage is an inline image attached to a message, sent as a base64 data: URL.
NUpOptions NUpOptions configures NUp imposition.
NUpOrder NUpOrder controls the order in which source pages fill the grid cells of an N-up sheet.
NamedAction NamedAction triggers a built-in viewer command (FirstPage, Print, ...).
NamedActionType NamedActionType identifies one of the standard viewer commands supported by /Named actions per ISO 32000-1 §12.6.4.11.
NamedDestination NamedDestination wraps a name reference into the document's NamedDestinations collection.
NamedDestinations NamedDestinations is a name-to-destination map per ISO 32000-1 §12.3.2.3.
NumberField NumberField is a text field with a JavaScript number-format action, so viewers display and validate the value as a formatted number.
NumberFormatOptions NumberFormatOptions configures a NumberField's display formatting (maps to Acrobat's AFNumber_Format).
OCRBox OCRBox is a rectangle in image pixel space: origin at the top-left corner, Y increasing downward (the usual raster convention — distinct from PDF user space on purpose).
OCREngine OCREngine recognizes text on one page image.
OCRLine OCRLine is one physical text line.
OCRResult OCRResult is the recognized content of one page image.
OCRWord OCRWord is word-level detail within a line, for engines that provide it.
OcrCopilot OcrCopilot recognizes text on scanned pages.
OcrOptions OcrOptions configures an OcrCopilot.
OpenAIClient OpenAIClient talks to an OpenAI-compatible chat-completions endpoint using only the standard library.
OpenAIClientOptions OpenAIClientOptions configures NewOpenAIClient.
OptimizationOptions OptimizationOptions selects which reductions Document.Optimize applies.
OptimizationResult OptimizationResult reports what Document.Optimize changed.
OptimizeImageOptions OptimizeImageOptions controls image optimization behavior.
OutlineItemCollection OutlineItemCollection represents an outline entry and the collection of its children.
PDFAFormat PDFAFormat identifies a PDF/A conformance level.
PDFAIssue PDFAIssue describes a single PDF/A conformance violation.
PDFAValidationReport PDFAValidationReport is returned by (*Document).ValidatePDFA.
PDFUAIssue PDFUAIssue describes a single PDF/UA (accessibility) conformance violation.
PDFUAValidationReport PDFUAValidationReport is returned by (*Document).ValidatePDFUA.
Page Page is a live view of a single page within a Document.
PageFormat PageFormat describes a page size in points (1/72 inch).
PageLabelRange PageLabelRange describes a contiguous run of pages that share a numbering style.
PageLabelStyle PageLabelStyle is the numbering style applied within a PageLabelRange.
PageMarkup PageMarkup is the structured text of one page.
PageNumberStamp PageNumberStamp stamps the page number (and optionally the total), formatted by Format.
PageRange PageRange specifies an inclusive range of pages (1-based).
PageSize PageSize holds the width and height of a PDF page in points (1/72 inch).
PasswordBoxField PasswordBoxField is a text field whose input is masked (Password flag).
Path 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).
PdfPageStamp PdfPageStamp overlays (or underlays) a page from another PDF document as a stamp — the source page is imported once as a Form XObject and drawn into the stamp's Rect, scaled to fit while preserving aspect ratio, positioned by HAlign/VAlign, and honoring Opacity, RotateAngle and Background.
Permissions Permissions controls what a viewer allows on an encrypted PDF.
PngDevice PngDevice renders a page to PNG at a fixed resolution.
Point Point is a single point in PDF user-space coordinates.
PolygonAnnotation PolygonAnnotation draws a closed polygon through a []pdf.Point list of vertices, with a stroked border and optional interior fill.
PolylineAnnotation PolylineAnnotation draws an open polyline through a []pdf.Point list of vertices, with a stroked border, optional line endings at the first and last vertex, and optional interior fill for closed endings.
QuadPoint QuadPoint is one quadrilateral within a markup annotation's /QuadPoints array.
RadialGradient RadialGradient interpolates colour from the focal point (FX, FY) out to the circle centred at (CX, CY) with radius R.
RadioButtonField RadioButtonField is a group of mutually exclusive options.
RadioButtonOptionField RadioButtonOptionField is one of the option widgets inside a RadioButtonField.
RadioItem RadioItem describes one widget inside a radio group.
Recipient Recipient is one certificate that may open a public-key-encrypted document, optionally with its own permission set.
Rectangle Rectangle represents a PDF rectangle [llx, lly, urx, ury] in points (1/72 inch).
RedactAnnotation RedactAnnotation marks regions for redaction.
RenderOptions RenderOptions controls page rasterization.
ReplaceOptions ReplaceOptions tunes how ReplaceText matches the search text.
ResetFormAction ResetFormAction resets named form fields to their /DV defaults.
Resolution Resolution is a rendering resolution in DPI.
RevocationCheck RevocationCheck selects how far verification goes in establishing whether a signing certificate was revoked.
RevocationFetcher RevocationFetcher retrieves revocation material.
RevocationSource RevocationSource records where an answer came from.
RevocationState RevocationState is what a responder or a CRL says about a certificate.
RevocationStatus RevocationStatus is what the issuer says about a signing certificate.
RichTextBoxField RichTextBoxField is a text field that carries a rich-text value (RichText flag + /RV) in addition to its plain /V.
RotationAngle RotationAngle represents a valid PDF page rotation in clockwise degrees.
Row Row is a single row within a Table.
SVG SVG is the pre-parsed SVG document.
SVGFontResolver SVGFontResolver maps an SVG font-family + style to a pdf.Font.
SVGSaveOptions SVGSaveOptions configures SaveSVG / WriteSVG.
SearchOptions SearchOptions tunes how SearchText interprets the query.
ShapeStyle ShapeStyle combines a stroke (LineStyle) with an optional fill color.
SignOptions SignOptions configures a digital signature.
SignatureAppearance SignatureAppearance controls the visible signature block's content and styling.
SignatureVerification SignatureVerification is the result of verifying one digital signature.
SquareAnnotation SquareAnnotation draws a rectangular annotation with stroked border and optional interior fill.
SquigglyAnnotation SquigglyAnnotation draws a wavy underline under text (typically used for spell-check style hints).
Stamp Stamp is content overlaid on (or behind) a page: a TextStamp, an ImageStamp, or a PageNumberStamp.
StampAnnotation StampAnnotation is a rubber-stamp annotation.
StampName StampName names per ISO 32000-1 §12.5.6.13 Table 184.
StrikeOutAnnotation StrikeOutAnnotation draws a horizontal line through text.
StructElement StructElement is a node in the logical structure tree.
StructType StructType is a PDF standard structure type (ISO 32000-1 §14.8.4), used as the /S value of a structure element.
SubmitFormAction SubmitFormAction submits form field values to a URL.
SubmitFormFlags SubmitFormFlags is the /Flags bitfield for a /SubmitForm action per ISO 32000-1 Table 237.
SummaryCopilot SummaryCopilot produces document summaries with an AI model.
SummaryOptions SummaryOptions configures a SummaryCopilot.
TOCEntry TOCEntry is one line of a table of contents: a title, an indent level (0 = top level), and the page it points at.
TOCOptions TOCOptions controls how a table of contents is rendered.
Table Table is a transient builder for a tabular layout drawn onto a Page.
TaggedContent TaggedContent is the facade for authoring a Tagged PDF (ISO 32000-1 §14.8): it owns the document's logical structure tree and sets the catalog marks PDF/UA requires.
TextAnnotation TextAnnotation is a sticky-note annotation.
TextBoxField TextBoxField is a single- or multi-line text input.
TextExtractOptions TextExtractOptions configures ExtractText.
TextExtractionMode TextExtractionMode selects how ExtractText orders the extracted text.
TextFragment TextFragment represents a contiguous run of text with uniform font.
TextIcon TextIcon names per ISO 32000-1 §12.5.6.4 Table 172, used in /Subtype /Text annotations' /Name entry.
TextLine TextLine represents a horizontal line of text fragments at a common Y position.
TextMatch TextMatch is a single occurrence located by SearchText.
TextRecognitionResult TextRecognitionResult is the recognized text of one processed page.
TextStamp TextStamp overlays a line (or wrapped block) of text.
TextStyle TextStyle defines reusable text formatting properties.
TiffDevice TiffDevice renders pages to TIFF.
TilingPattern TilingPattern is a repeating fill (PatternType 1, ISO 32000-1 §8.7.3.1): a small cell of content tiled across whatever shape it fills.
Type3Font Type3Font is a user-defined glyph-stream font.
UnderlineAnnotation UnderlineAnnotation draws a horizontal line under text.
Usage Usage reports token counts when the provider returns them.
VAlign VAlign specifies vertical text alignment within a rectangle.
ValidationOptions ValidationOptions configures signature verification.
ValidationIssue ValidationIssue describes a single problem found in a PDF file.
ValidationReport ValidationReport is returned by Validate and summarises the structural integrity of a PDF.
WidgetAnnotation WidgetAnnotation is the read-only view of a form widget annotation surfaced through AnnotationCollection.
XForm XForm is a reusable Form XObject (ISO 32000-1 §8.10) — an independent content stream (with its own resources) that can be placed on any number of pages and positions with a single Do invocation. Create one with Document.CreateForm(w, h) and draw into it via Canvas(), place it with Page.AddForm(form, rect), list a page's existing forms with Page.Forms(), or copy one (with its whole resource graph) from another document with Document.ImportForm.
XMPMetadata XMPMetadata is the document's XMP packet modelled as common schema fields plus a list of arbitrary Custom properties.
XMPProperty XMPProperty is a single simple (string-valued) XMP property in an arbitrary namespace.

Detailed Member Reference
Encryption and Signing
  • Permissions fields map to ISO 32000-1 §7.6.3.2 Table 22 bits 3–12; the library encodes them with the Adobe convention (reserved bits set high). In EncryptionOptions, Permissions is a pointer so nil means "grant all", distinguishing that default from an explicit &Permissions{}, which denies everything.
  • OpenWithPassword reads Standard-handler files encrypted with RC4-40 (R2), RC4 (R3), AES-128 (R4, /AESV2) and AES-256 in both revision 6 and Acrobat 9's revision 5, and returns ErrInvalidPassword when the password matches neither the user nor the owner password. Writing always uses revision 6 for AES-256.
  • EncryptionOptions.Recipients switches to the public-key security handler (ISO 32000-1 §7.6.4): the document is sealed for a list of X.509 certificates — each with optional per-recipient Permissions, which a password cannot express — and opened with OpenWithCertificate/OpenStreamWithCertificate by supplying the certificate and any crypto.Decrypter private key. AES-128 and AES-256 are supported (AES-256 by default); RSA recipients only, and the file re-saves for the same recipients after editing.
  • Document.Sign covers the whole file with one PKCS#7-detached signature, invisible by default or visible via Visible/Rect/Page/SignatureAppearance; PAdES switches the subfilter to ETSI.CAdES.detached, Certify adds a DocMDP certification, and TimestampURL embeds an RFC 3161 timestamp. Re-signing an already-signed document appends an incremental update so the earlier signature stays valid. Document.VerifySignatures returns Valid, IntegrityOK, CoversWholeDocument, and the signer Certificate per signature field — trust-chain validation against your own store is the caller's responsibility.
Forms (AcroForm)
  • Form.AddBarcodeField(pageNum, rect, name, symbology, value) draws a Code128, QR, or PDF417 barcode in place of text (form.AddBarcodeField(1, rect, "sku", pdf.BarcodeQR, "https://example.com/sku/123")); (*BarcodeField).Symbology()/SetSymbology() read/change the encoding, and SetValue validates the new value encodes under the current symbology before writing it. All three encoders are pure Go, with no external dependency; a PDF417 symbol picks its column count to match the rectangle.
  • Field values containing non-ASCII characters are encoded as UTF-16BE with a BOM. Form.Export/ ImportJSON round-trips every field as typed JSON keyed by full name (checkbox → bool, list box → array); Form.Export/ImportFDF and Form.Export/ImportXFDF provide the same round-trip in Acrobat-interoperable FDF and XFDF.
  • Every widget's /AP appearance stream is pre-generated and regenerated on every value or style change, so fields render identically across Acrobat, Foxit, browser viewers, MuPDF, and Poppler without depending on /AcroForm/NeedAppearances.
Outlines, Named Destinations, and Table of Contents
  • Document.Outlines() is the root OutlineItemCollection; NewOutlineItemCollection(doc) constructs an unattached entry with an IList-equivalent surface (Add/Insert/Remove/ RemoveAt/At/Count/All). All 8 destination types (XYZ/Fit/FitH/FitV/FitR/FitB/FitBH/ FitBV) are supported; Action and Destination may both be set (viewers honor /Dest first).
  • Document.NamedDestinations() reads both /Catalog/Dests (legacy) and /Catalog/Names/Dests (modern), writing modern-only with automatic migration on save.
  • Document.GenerateTOC builds a clickable table of contents from the outline tree and inserts it as new page(s) at the front; Page.AddTOC renders a caller-supplied entry list into a rectangle, auto-paginating on overflow. TOCOptions controls the heading, per-level indent, and whether page numbers, dotted leaders, and links are drawn. A runnable example lives in _examples/toc.
Attachments and Portfolios
  • Document.EmbeddedFiles() manages document-level attachments through the /Catalog/Names/EmbeddedFiles name tree (ISO 32000-1 §7.11.4): Add(path)/ AddFromStream(name, r) embed a file (MIME type detected from the extension), and each *EmbeddedFile exposes Name(), Description()/SetDescription(), MIMEType(), Size(), and Data()/WriteTo(w)/Save(path) to read it back. The page-pinned counterpart is FileAttachmentAnnotation.
  • Document.Collection() presents those attachments as a portfolio (ISO 32000-1 §7.11.6 and §12.3.5): SetView(CollectionViewDetails|Tiles|Hidden) chooses the presentation mode, Schema().Add(key, header, type) declares the columns a viewer shows — text, number, and date columns carry per-file values, while CollectionFieldFilename/Description/ModDate/ CreationDate/Size are derived from the attachment itself (CollectionField.IsDerived()) — and SetInitialFile(name) plus SetSort(field, ascending) control what opens first and how the list is ordered. Values are written per attachment with EmbeddedFile.CollectionItem() (SetText/SetNumber/SetDate, read back with Text/Number/Date). IsPortfolio() reports the state and Remove() reverts the document to a plain attachment list without touching the files. Folder hierarchies (/Folders) are out of scope.
Document JavaScript and Open Actions
  • Document.JavaScript() returns the document-level named-script collection, backed by the /Catalog/Names/JavaScript name tree (ISO 32000-1 §7.7.4 / §8.5.1) — Add(name, script), Get(name), Has(name), Remove(name), Names(), Count(), and Clear() manage it directly. This is distinct from the action-level JavaScriptAction that fires on an annotation click, not on the document-open event.
  • Document.OpenAction()/Document.SetOpenAction(act)/Document.RemoveOpenAction() read, set, and clear the /Catalog/OpenAction entry (ISO 32000-1 §12.3.2 / §12.6.1) — the action a viewer runs when the document opens (GoTo, JavaScript, Named, …). A GoTo open action is bound to the document, so its destination resolves to a 1-based page number on read; both round-trip through Save and coexist with named destinations. Document-level JavaScript executes in the recipient's viewer when the file is opened — embed only scripts you authored or audited.
Deleting Pages and Inserting Blank Pages
  • Document.DeletePages(pageNums ...int) removes one or more 1-based pages in place — page numbers are de-duplicated and validated before anything is removed, so a call that would remove every page returns an error and leaves the document unchanged; Document.DeletePage(n) is the single-page convenience form.
  • Document.AddBlankPage(width, height)/Document.AddBlankPageFromFormat(format) append a blank page to the end of an already-open document; Document.InsertBlankPage(position, width, height)/Document.InsertBlankPageFromFormat(position, format) insert one at a specific 1-based position instead — distinct from building a whole new document from scratch via NewFlow.
Text Drawing and Right-to-Left / Arabic Shaping
  • TextStyle.RTL (or simply including RTL characters) enables right-to-left/bidirectional layout for drawn text: a pure-Go Unicode Bidi Algorithm (UAX #9) implementation reorders each line into visual order, keeping embedded numbers and Latin runs left-to-right, and RTL paragraphs right-align by default. Arabic contextual shaping (connected letterforms plus lam-alef ligatures via Presentation Forms-B) renders proper Arabic with any font that covers the block, including the bundled DejaVu Sans.
  • Embedded OpenType fonts are shaped by their own GSUB/GPOS tables: a pure-Go shaping engine applies contextual forms, ligatures, kerning, and cursive and mark attachment the way HarfBuzz does, glyph for glyph, so Arabic, Persian, and Urdu join in fonts without Presentation Forms-B (Amiri, Noto Naskh Arabic), vowel marks sit on their base letters, and Latin text kerns. It needs no API change — AddText shapes automatically — and shaped text stays extractable and searchable through ToUnicode mappings and ActualText spans.
  • Document.CreateType3Font() authors a Type3 font (ISO 32000-1 §9.6.5), whose glyphs are content streams rather than outlines: AddGlyph(r, width) returns a *Page canvas in glyph space (1000 units per em, baseline at y = 0) that accepts the whole drawing API, and the finished font drops into TextStyle.Font alongside Standard-14 and embedded faces. The font freezes on first use, embedding each glyph as a /CharProcs stream plus a generated ToUnicode CMap, so text drawn with custom symbols still extracts, searches, and renders.
Vector Graphics and SVG Import
  • AddSVG/AddSVGFromStream render a parsed SVG onto a page: basic shapes, the full SVG 1.1 path syntax, transforms, viewBox/preserveAspectRatio, 147 CSS named colors, linear/radial gradients (gradientUnits/gradientTransform), <text>/<tspan> with font styling and a pluggable SVGFontResolver for non-Latin text, <image> (data URIs), <defs>/<use>/ <symbol>, <clipPath> (clipping paths compile to PDF W/W* operators), <mask> (soft masks via a PDF Form XObject transparency group + ExtGState /SMask, honoring maskUnits/maskContentUnits), CSS <style> blocks, <filter feDropShadow>, and <marker> (marker-start/marker-mid/marker-end rotate via orient=auto along the path tangent, using refX/refY anchors). Unsupported and skipped silently: <textPath>, vertical writing modes, external <image href>, real Gaussian blur, and em/ex/% length units.
Annotations
  • Page.Annotations() returns the page's AnnotationCollection, with Add/At/Delete/ DeleteAt managing the list directly.
  • Supported subtypes: Link (with GoToURI/GoTo/Named/SubmitForm/ResetForm/JavaScript actions), Highlight, Underline, StrikeOut, Squiggly, Square, Circle, Line, Ink, Text, FreeText (Plain/Callout/Typewriter intents), Stamp (14 predefined visuals or a custom image), Polygon/Polyline, Caret, FileAttachment, and Redact. Existing form widgets surface as read-only WidgetAnnotation; mutate them through the Form API instead.
  • FileAttachmentAnnotation shows one of four icons (Paperclip default, Graph, PushPin, Tag); the embedded file's MIME type is auto-detected from its extension.
  • Border styles (Solid/Dashed/Beveled/Inset/Underline) and 10 line-ending shapes are available on the drawing types; every property setter immediately regenerates the annotation's /AP/N appearance stream, so no /NeedAppearances flag is needed.
  • Document.ApplyRedactions() removes text glyphs, image XObjects, and paths inside a Redact annotation's /QuadPoints; ValidateRedactions() is a recommended pre-flight parseability check. NewJavaScriptAction carries a documented security warning — embedded JavaScript executes in the recipient's viewer.
Stamps
  • TextStamp, ImageStamp, PageNumberStamp, and PdfPageStamp (which stamps in a page from another PDF) overlay or underlay content via (*Page/*Document).AddStamp, with Opacity, centre-pivot RotateAngle, alignment, and a Background behind-content flag; PageNumberStamp.Format uses {0}/{1} placeholders for the page number and total (e.g. "Page {0} of {1}").
Validation: Structural, PDF/A, and PDF/UA
  • Validate is a structural-integrity check only (INVALID_HEADER/XREF_ERROR/OBJECT_ERROR/ PAGE_TREE_ERROR/STREAM_ERROR/ENCRYPTED issue codes) — not a PDF/A or PDF/UA conformance check.
  • ValidatePDFA(PDFA1B/2B/3B/1A/2A/3A) inspects the XMP pdfaid identifier, font embedding, encryption, JavaScript/Launch actions, the ICC OutputIntent against device colour, transparency (PDF/A-1), annotation flags, and metadata compression; the "a" levels additionally require a Tagged PDF (structure tree + /Lang).
  • ConvertToPDFA strips encryption and JavaScript, removes embedded files for PDF/A-1, sets annotation print flags and draws the appearances annotations are missing, embeds the fonts the document actually draws with — Standard-14 and other simple fonts through bundled metric-compatible clones, composite (CJK) fonts as a subset of the matching installed face, and Symbol or ZapfDingbats from a face registered through AddFontFile/AddFontFolder — adds a pure-Go sRGB ICC OutputIntent, and writes a pdfaid XMP packet, then returns a report of whatever still fails. Across a 1,000-document corpus, 97% convert to a clean report; confirm full conformance with a dedicated validator such as veraPDF. ConvertToPDFA does not flatten transparency (a TRANSPARENCY finding for PDF/A-1 stays unresolved) — call Document.FlattenTransparency() separately first: it rasterizes only the pages that actually use a transparency group, soft mask, non-Normal blend mode, or alpha < 1, leaving every other page fully vector.
  • ValidatePDFUA checks the PDF/UA-1 (ISO 14289-1) prerequisites: a Tagged PDF with /StructTreeRoot + /ParentTree, a declared /Lang, a displayed title, alternate text on every figure/formula, and accessibility not blocked by encryption.
Tagged PDF Authoring
  • AddTaggedTable renders a Table and builds its /Table → /TR → /TH//TD structure in one call (repeating header rows become /TH); AddTaggedList does the same for bulleted/numbered lists. Decoration (headers, footers, page numbers) is marked as an artifact so it stays out of the structure tree.
  • StructElement.AddObjectReference associates a structure element directly with an annotation via an /OBJR (ISO 32000-1 §14.7.4.4) instead of marked content — the way a /Link element points at its LinkAnnotation — and composes with AddChild/TagContent rather than replacing them.
Rendering to Images
  • The renderer draws vector graphics (paths, Gray/RGB/CMYK/Separation/DeviceN colour, shadings, tiling patterns, clipping, alpha, soft masks, blend modes), images (Image XObjects, stencil masks, CCITT Group 3/4 fax, JBIG2 bilevel scans, JPEG2000 colour scans including MRC stencil-masked layers), and text (embedded TrueType/CFF/Type3, non-embedded fonts via bundled metric-compatible substitutes, non-embedded CJK via predefined Adobe CMaps rendered from installed system fonts), and annotation appearances (AcroForm field widgets, stamps, highlights, free text, …) to PNG/JPEG/GIF/BMP/TIFF at a default 150 DPI over the CropBox. Unsupported elements (mesh shadings, isolated/knockout transparency groups, non-embedded Symbol) are skipped so a page always renders. Embedded fonts render via /FontFile3 (CFF/ Type1C and CID-keyed) and TrueType tables; non-embedded fonts resolve through a FontRepository covering exact/installed fonts including .ttc collections and .otf/CFF; JPEG2000 colour scans (/JPXDecode) are decoded including MRC high-resolution stencil-masked foreground layers.
HTML, SVG, and Markdown Conversion
  • SaveHTML/WriteHTML export one single-file HTML document with no external assets and no JavaScript; text is selectable and Ctrl+F-searchable in every mode, link annotations become clickable <a> overlays, and InteractiveForms turns AcroForm fields into real browser controls.
  • SaveSVG/WriteSVG export standalone true-vector SVG with real Bézier paths, native strokes, and glyph-outline text (no font dependencies); SVGSaveOptions.DPI (default 150) sets the resolution of the small raster patches used only where shadings/patterns/soft masks can't be expressed in SVG.
  • MarkdownToDocument/FromStream render headings, styled bold/italic/code/link runs, task checkboxes, block quotes, code cards, and GFM tables into a paginated PDF; MarkdownOptions. FontFamily/CodeFontFamily (or explicit LoadFont faces) cover non-Latin text. SaveMarkdown/ WriteMarkdown reverse the process, inferring headings from font size and recovering bold/italic/code runs, links, and nested lists — tables are not yet reconstructed and flow as paragraphs.
AI Copilots
  • ai.NewSummaryCopilot produces plain-text or, with ai.SummaryOptions.Markdown set, Markdown-rendered document summaries — the model is asked to format the summary as Markdown, which is then rendered through the same MarkdownToDocument pipeline used elsewhere; ai.NewOcrCopilot recognizes scanned pages (auto-detected by low extractable text plus a dominant full-page image) and its MakeSearchable method writes the recognized text back as an invisible, selectable layer; ai.NewChatCopilot answers questions about a document with conversation history; ai.NewImageDescriptionCopilot.FillAltTexts fills missing /Alt text on a tagged document's figures. All four work over any OpenAI-compatible endpoint (OpenAI, LiteLLM, Ollama, …) and are implemented with the standard library only.
Text Extraction, Search, and Images
  • SearchText (literal, case-insensitive, or RE2 regex, with an optional region) returns per-match bounding boxes built from per-glyph positions; ReplaceText redraws the replacement at the same baseline/size/colour in a metric-compatible Standard-14 face. Both match within a single text line only.
  • Document.ExtractImages()/Page.ExtractImages() decode every image on all pages (or one page) as JPEG (DCTDecode passthrough) or PNG, across DeviceRGB/DeviceGray/DeviceCMYK/Indexed/ICCBased color spaces with soft masks applied as PNG alpha; Document.ImageInfos()/Page.ImageInfos() list the same images' position, size, and color space without decoding pixel data, for fast, selective extraction (call .Extract() on just the ones you need). AddImage/ AddImageFromStream (a file path or an io.Reader, respectively; an Image XObject either way) is the recommended default for anything larger than a tiny icon, where AddInlineImage is more appropriate.
  • ImageToDocument(path, opts...)/ImageToDocumentFromStream(r, opts...) build a brand-new single-page *Document from a standalone JPEG or PNG file, with ImageToDocumentOptions controlling explicit PageWidth/PageHeight and margins (0 = size the page from the image's own DPI). An already-placed page image can be swapped in place with ImageInfo.Replace(path)/ .ReplaceFromStream(r) (format auto-detected from magic bytes; position and size on the page stay unchanged even if the new image's own dimensions differ) or removed entirely with ImageInfo.Remove() (deletes the XObject reference and its drawing operators from the page; page-level images only, not ones nested inside a Form XObject).

Documentation & Resources

Scope and Limitations

  • Viewer permissions (Permissions/SetPermissions) are enforced by PDF viewers, not by this library — the encryption bitfield is written into the file, but the library itself is not a DRM mechanism.
  • Linearization (SaveLinearized/WriteToLinearized) cannot be combined with encryption or digital signing in the same document.
  • Certificate-based encryption accepts RSA recipients only (PKCS#1 v1.5 key transport); elliptic curve recipients (key agreement) and the legacy RC4 sub-filters are not written.
  • OpenType shaping covers Arabic-family, Hebrew, and simple (Latin, Cyrillic, Greek) scripts; the Indic, Khmer, Myanmar, and Hangul reordering shapers and vertical text are not implemented.
  • ConvertToPDFA embeds a font only when a face is available to it: Symbol and ZapfDingbats need one registered through AddFontFile/AddFontFolder (no metric-compatible clone is bundled), and a composite font needs the matching face installed. It does not flatten transparency itself (call Document.FlattenTransparency() before converting to PDF/A-1) or draw appearances for icon annotations (sticky notes, file attachments), and a font whose licensing bits forbid embedding is left alone. Confirm full conformance with a dedicated validator such as veraPDF.
  • FlattenTransparency only looks at a page's content stream and /Resources graph; an annotation's own opacity or the transparency inside its /AP appearance stream is untouched — flatten annotations into page content first (Annotation.Flatten()/Form.Flatten()) if that also needs to go. It also only rasterizes whole pages, not just the transparent region within one, so a flattened page's text is no longer extractable.
  • The built-in renderer does not support mesh shadings (PDF shading types 4-7); other shading types, patterns, and blend modes render normally.
  • ConvertToGrayscale maps device colours, images, and shadings/patterns to their luminance grey in place, but Separation/DeviceN, Indexed, and PostScript/sampled shading functions are best-effort only.
  • MarkdownToDocument has no syntax highlighting yet; SaveMarkdown does not reconstruct tables from a PDF (cell text flows as paragraphs) and caps inferred heading levels at 3.
  • SearchText and ReplaceText match within a single text line only — a query that straddles a line break is not found.
  • Scanned pages are auto-detected (no extractable text plus a dominant full-page image); OcrOptions.Pages/All override the default selection when auto-detection guesses wrong. The bundled LLMOCREngine returns line-level OCR text with no coordinates, so MakeSearchable positions the hidden searchable text on an even grid rather than exact per-word boxes; implement the one-method ai.OCREngine interface over an engine that reports word boxes (e.g. Tesseract or a cloud OCR service) for exact alignment. For non-Latin text, pass a Unicode font via OcrOptions.Font (see Document.LoadFont).
  • The AI copilots (summarization, OCR, chat, alt-text) send extracted document text and/or rendered page images to the configured endpoint. For sensitive documents, point the client at a local endpoint (e.g. Ollama) — the same client code works unchanged.
  • Table does not yet support content-driven auto-fit column widths, per-side border dash patterns, or a RowSpan group splitting across a page break.

These limitations don't apply to Aspose.PDF for Go — Enterprise Edition, which adds the full Aspose.PDF facade surface, broader format coverage, and commercial support.

Development and Testing

go build ./...
go test ./...

Standalone runnable example programs live in _examples/<name>/main.go (excluded from go build ./.../go test ./... by their leading underscore); run one directly with go run ./_examples/<name>. Short, focused API examples live as ExampleXxx functions in examples_test.go, validated by go test via their // Output: comments and surfaced on pkg.go.dev next to each documented function. Test PDF fixtures live flat under testdata/.

Third-Party Notices

The compiled library links against nothing but the Go standard library, and every PDF primitive — the parser, writer, raster renderer, SVG and Markdown engines, and the PKCS#7/CMS signing code — is implemented from scratch within the module. It bundles Latin-subset copies of four metric-compatible open fonts (Arimo, Tinos, Cousine, and Carlito), used to render the PDF Standard-14 fonts and Calibri when no embedded or system font is available, licensed under the SIL Open Font License 1.1 — see fonts/LICENSE.txt. The PDF417 codeword-to-bar table (defined by ISO/IEC 15438 Annex A) was extracted from ZXing (Apache License 2.0) and verified against zint — see third_party/PDF417-TABLE-NOTICE.txt.

License

This project is licensed under the MIT License. The MIT License permits use, copying, modification, distribution, sublicensing, and commercial use, provided its copyright and permission notice are retained. The software is provided without warranty.

The library also bundles the Arimo, Tinos, Cousine, and Carlito font families under the SIL Open Font License 1.1, used to render the PDF Standard-14 fonts (and Calibri) when no embedded or system font is available — see fonts/LICENSE.txt (SPDX: MIT AND OFL-1.1 for the distribution as a whole). The MIT license above covers the library's own code.

Documentation

Overview

Package asposepdf is a pure Go PDF library — no CGo, no native dependencies, standard library only, MIT-licensed. It reads, creates, edits, renders, signs, encrypts, converts, and validates PDF documents.

Capabilities include: page manipulation (split, merge, extract, rotate, N-up/booklet imposition); text extraction in reading order with layout, search (literal/regex) and replace; drawing text (with word wrap, Unicode, RTL/Arabic shaping), vector graphics (paths, gradients, tiling patterns) and tables with automatic pagination; a flow document generator; TrueType and OpenType font embedding with subsetting; AcroForm reading, filling, creation, styling and flattening with JSON/FDF/XFDF interchange; the full annotation family with generated appearance streams; encryption (RC4-128, AES-128, AES-256) and digital signatures (PKCS#7, PAdES, DocMDP certification, RFC 3161 timestamps, multiple signatures) with verification; bookmarks, named destinations, page labels, Info and XMP metadata, embedded files, optional-content layers; PDF/A validation and conversion, Tagged PDF authoring and PDF/UA validation; redaction; linearization (fast web view); and a unified size optimizer.

Converters: render pages to PNG, JPEG, GIF, BMP and multi-page TIFF with the built-in dependency-free rasterizer; export documents to HTML (four modes, including fillable forms), SVG (true vector) and Markdown; convert Markdown (CommonMark + GFM, 652/652 official test suite), SVG and raster images to PDF. The ai subpackage adds AI copilots — summarization, OCR with a searchable-PDF pipeline, document Q&A and image description — over any OpenAI-compatible endpoint.

The public API is shaped to mirror Aspose.PDF for .NET (Document, Page, TextFragment, Table, Form, OutlineItemCollection, …), adapted to Go idioms: error returns, io.Reader/io.Writer streams, and exported functions over constructors. Spec references follow ISO 32000-1 (PDF 1.7) and ISO 32000-2 (PDF 2.0).

Index

Examples

Constants

View Source
const DefaultDPI = 150

DefaultDPI is the rendering resolution used when RenderOptions.DPI is unset. 150 matches Aspose.PDF for .NET's default Resolution.

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.

View Source
var ErrInvalidPassword = errors.New("invalid password")

ErrInvalidPassword is returned by OpenWithPassword / OpenStreamWithPassword when the supplied password matches neither the user nor the owner password of the file. Mirrors Aspose.PDF for .NET's InvalidPasswordException.

Functions

func AddFontFile added in v0.3.0

func AddFontFile(path string)

AddFontFile registers a single font file. Mirrors a FileFontSource.

func AddFontFolder added in v0.3.0

func AddFontFolder(path string)

AddFontFolder registers a directory searched (recursively) for fonts when rendering. Mirrors adding a FolderFontSource in Aspose.PDF for .NET.

func AddSystemFonts added in v0.3.0

func AddSystemFonts()

AddSystemFonts registers the operating system's standard font directories. Mirrors adding a SystemFontSource. Not enabled by default — call it to let the renderer use installed fonts (e.g. real Arial / Times New Roman).

func AssembleDestinationText added in v0.9.0

func AssembleDestinationText(ops []DiffOperation) string

AssembleDestinationText rebuilds the second document's text — everything equal plus everything inserted. Mirrors Aspose.PDF for .NET's TextPdfComparer.AssemblyDestinationPageText. With ComparisonOptions.IgnoreCase set, equal runs carry the first document's spelling, so the result can differ from the second document in letter case.

func AssembleSourceText added in v0.9.0

func AssembleSourceText(ops []DiffOperation) string

AssembleSourceText rebuilds the first document's text from the operations — everything equal plus everything deleted. Mirrors Aspose.PDF for .NET's TextPdfComparer.AssemblySourcePageText.

func ClearFontSources added in v0.3.0

func ClearFontSources()

ClearFontSources removes all registered folders and files.

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

func MeasureText added in v0.13.0

func MeasureText(text string, style TextStyle) (float64, error)

MeasureText returns the width in points of text drawn as a single line with style, using the same font resolution, Arabic/bidi reordering and OpenType shaping AddTextAt applies — so a caller doing its own line-breaking can measure a candidate line exactly the way it would be drawn. Unlike AddText's own internal wrapping measurement, whitespace in text is never collapsed. style.Font nil defaults to FontHelvetica, style.Size 0 to 12, matching AddText/AddTextAt.

Types

type AFRelationship added in v0.10.0

type AFRelationship int

AFRelationship says how an embedded file relates to the document. Mirrors Aspose.PDF for .NET's AFRelationship.

const (
	// AFUnspecified states no particular relationship. The zero value, and
	// what a file with no /AFRelationship reports.
	AFUnspecified AFRelationship = iota
	// AFSource is the original the document was produced from.
	AFSource
	// AFData is data the document's content is built on, such as the table
	// behind a chart.
	AFData
	// AFAlternative is an alternative representation of the content, such as
	// the XML of a hybrid e-invoice.
	AFAlternative
	// AFSupplement is a supplemental representation of the content.
	AFSupplement
)

func (AFRelationship) String added in v0.10.0

func (r AFRelationship) String() string

String names the relationship as PDF writes it, without the slash.

type AbsorbedCell added in v0.7.0

type AbsorbedCell struct {
	// Rect is the cell's rectangle (the full span for spanning cells;
	// covered positions carry the covering cell's rectangle).
	Rect Rectangle
	// RowSpan/ColSpan are >= 1 on a cell's anchor position.
	RowSpan, ColSpan int
	// Covered marks a position occupied by another cell's span.
	Covered bool
	// Shading is the cell's background fill colour, when the page paints one.
	Shading *Color
	// contains filtered or unexported fields
}

AbsorbedCell is one logical grid position.

func (*AbsorbedCell) Text added in v0.7.0

func (c *AbsorbedCell) Text() string

Text returns the cell's text: fragments grouped into visual lines, lines joined with newlines, gap-separated fragments with spaces.

func (*AbsorbedCell) TextFragments added in v0.7.0

func (c *AbsorbedCell) TextFragments() []TextFragment

TextFragments returns the text fragments inside the cell.

type AbsorbedRow added in v0.7.0

type AbsorbedRow struct {
	Rect Rectangle
	// contains filtered or unexported fields
}

AbsorbedRow is one logical table row.

func (*AbsorbedRow) CellList added in v0.7.0

func (r *AbsorbedRow) CellList() []*AbsorbedCell

CellList returns the row's cells, left-to-right (one per logical column; positions covered by a span carry Covered=true).

type AbsorbedTable added in v0.7.0

type AbsorbedTable struct {
	// Rect is the table's bounding rectangle in PDF user space.
	Rect Rectangle
	// PageNumber is the 1-based source page.
	PageNumber int
	// contains filtered or unexported fields
}

AbsorbedTable is one recognized table.

func (*AbsorbedTable) RowList added in v0.7.0

func (t *AbsorbedTable) RowList() []*AbsorbedRow

RowList returns the table's rows, top-to-bottom.

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

	// Flatten bakes this annotation's normal appearance into the page
	// content and removes the annotation, making it non-interactive. See
	// (*annotationBase).Flatten in flatten.go.
	Flatten() error
	// 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.

func (*AnnotationCollection) Flatten added in v0.3.0

func (c *AnnotationCollection) Flatten() error

Flatten bakes every annotation on the page into the page content and removes it. Widget annotations (form-field widgets) are skipped — flatten those via (*Document).Flatten or (*Form).Flatten so the /AcroForm is cleaned up too.

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
	AnnotationTypePolygon
	AnnotationTypePolyLine
	AnnotationTypeCaret
)

type BarcodeField added in v0.10.0

type BarcodeField struct{ TextBoxField }

BarcodeField draws its value as a barcode symbol. Value()/SetValue() (inherited from TextBoxField) get/set the encoded text; every value change re-renders the widget's /AP. Bar colour and background reuse FieldStyle.TextColor / BackgroundColor via SetStyle — there is no separate "ForegroundColor" on this type. Unlike other field types, BarcodeField draws no default border or background fill (a barcode's quiet zone must stay open), so both stay transparent unless SetStyle sets them explicitly.

func (*BarcodeField) Flatten added in v0.10.0

func (b *BarcodeField) Flatten() error

Flatten bakes this single field's appearance (each of its widgets) into the owning page content and removes the field, leaving every other field and the /AcroForm dict intact. Mirrors Aspose.PDF for .NET's Field.Flatten.

After Flatten the field handle is dangling and must not be used.

func (*BarcodeField) FullName added in v0.10.0

func (b *BarcodeField) FullName() string

func (*BarcodeField) IsReadOnly added in v0.10.0

func (b *BarcodeField) IsReadOnly() bool

func (*BarcodeField) IsRequired added in v0.10.0

func (b *BarcodeField) IsRequired() bool

func (*BarcodeField) PageIndex added in v0.10.0

func (b *BarcodeField) PageIndex() int

func (*BarcodeField) PartialName added in v0.10.0

func (b *BarcodeField) PartialName() string

func (*BarcodeField) Rect added in v0.10.0

func (b *BarcodeField) Rect() Rectangle

func (*BarcodeField) SetStyle added in v0.10.0

func (b *BarcodeField) SetStyle(s FieldStyle) error

SetStyle applies s to the field, writing /MK, /BS, /DA, and /Q on the field and its widgets and regenerating each widget's /AP appearance so the new look is visible immediately in every viewer. Returns an error only if the field is detached or a styled font cannot be registered.

func (*BarcodeField) SetSymbology added in v0.10.0

func (bc *BarcodeField) SetSymbology(s BarcodeSymbology) error

SetSymbology changes the barcode encoding and re-renders the appearance. Errors (leaving the field unchanged) if the field's current value cannot be encoded under the new symbology.

func (*BarcodeField) SetValue added in v0.10.0

func (bc *BarcodeField) SetValue(value string) error

SetValue validates that value encodes under the field's current symbology before writing it (leaving the field unchanged on error), then re-renders the barcode appearance.

func (*BarcodeField) Style added in v0.10.0

func (b *BarcodeField) Style() FieldStyle

Style reads back the field's current styling from /DA, /Q, /MK, and /BS. Properties never set return their zero/default value. The first widget is used for /MK and /BS.

func (*BarcodeField) Symbology added in v0.10.0

func (bc *BarcodeField) Symbology() BarcodeSymbology

Symbology returns the field's barcode encoding.

type BarcodeSymbology added in v0.10.0

type BarcodeSymbology int

BarcodeSymbology identifies which barcode encoding a BarcodeField draws.

const (
	BarcodeSymbologyUnknown BarcodeSymbology = iota
	// BarcodeCode128 encodes printable ASCII (0x20-0x7E) via Code Set B
	// (ISO/IEC 15417). Non-ASCII text is rejected — use BarcodeQR instead.
	BarcodeCode128
	// BarcodeQR encodes arbitrary text as its UTF-8 bytes in QR byte mode
	// (ISO/IEC 18004), error-correction level M, version chosen
	// automatically (1-40).
	BarcodeQR
	// BarcodePDF417 encodes arbitrary text as its UTF-8 bytes in PDF417
	// byte compaction (ISO/IEC 15438), with an ECI 000026 designator when
	// the text is not pure ASCII. The error-correction level follows ISO's
	// recommendation for the data size and the column count is chosen to
	// approach the widget rectangle's proportions. Up to 929 codewords
	// (roughly 1,100 bytes) fit in one symbol.
	BarcodePDF417
)

type BmpDevice added in v0.3.0

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

BmpDevice renders a page to BMP. Mirrors Aspose.PDF for .NET's BmpDevice.

func NewBmpDevice added in v0.3.0

func NewBmpDevice(res Resolution) *BmpDevice

NewBmpDevice returns a BmpDevice for the given resolution.

func (*BmpDevice) Process added in v0.3.0

func (d *BmpDevice) Process(page *Page, w io.Writer) error

Process renders page and writes it to w as BMP.

type BookletBinding added in v0.4.0

type BookletBinding int

BookletBinding selects the binding edge of a booklet.

const (
	// BindingLeft places the lower page number on the right (LTR reading).
	BindingLeft BookletBinding = iota
	// BindingRight mirrors the spreads for right-to-left binding.
	BindingRight
)

type BookletOptions added in v0.4.0

type BookletOptions struct {
	// PageSize is the output sheet (a two-page spread). The zero value uses
	// twice the width by the height of the document's first page, so the
	// source pages are placed at 100% with no scaling.
	PageSize PageFormat
	// Binding selects the binding edge (left by default).
	Binding BookletBinding
}

BookletOptions configures Booklet imposition.

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 ButtonAppearance added in v0.3.0

type ButtonAppearance struct {
	Caption      string             // /MK/CA — normal-state caption
	RolloverText string             // /MK/RC — caption while hovered (falls back to Caption)
	DownText     string             // /MK/AC — caption while pressed (falls back to Caption)
	IconPath     string             // optional icon image (PNG/JPEG), baked into the /AP streams
	IconPosition ButtonIconPosition // /MK/TP — icon vs caption layout
	TextColor    *Color             // caption colour (default dark grey)
	FaceColor    *Color             // button face fill (default light grey)
	BorderColor  *Color             // button border (default grey)
}

ButtonAppearance configures a push button's rich appearance: separate captions for the normal / rollover / down states, an optional icon image, and face/border/text colours. Applied via (*ButtonField).SetAppearance, which writes the /MK appearance- characteristics dict and bakes /AP/N, /AP/R, and /AP/D appearance streams so the button reacts to hover and press in every viewer.

Out of scope (follow-up): caption rotation (/MK/R) and exposing the icon as a /MK/I Form XObject for viewer-side regeneration — the icon is rendered directly into the /AP streams here, which renders in any viewer without relying on regeneration.

type ButtonField

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

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

func (*ButtonField) Action added in v0.5.0

func (f *ButtonField) Action() Action

Action returns the button's activation action (/A on its widget), or nil if none is set or the action type is unsupported. Mirrors the LinkAnnotation action surface.

func (*ButtonField) Flatten added in v0.3.0

func (b *ButtonField) Flatten() error

Flatten bakes this single field's appearance (each of its widgets) into the owning page content and removes the field, leaving every other field and the /AcroForm dict intact. Mirrors Aspose.PDF for .NET's Field.Flatten.

After Flatten the field handle is dangling and must not be used.

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) SetAction added in v0.5.0

func (f *ButtonField) SetAction(act Action)

SetAction writes the button's activation action (/A) onto its widget(s) — typically a SubmitFormAction, ResetFormAction, GoTo/URI or JavaScript action. nil clears the action. Mirrors Aspose.PDF for .NET's ButtonField.OnActivated.

func (*ButtonField) SetAppearance added in v0.3.0

func (f *ButtonField) SetAppearance(a ButtonAppearance) error

SetAppearance applies a ButtonAppearance to the push button: it writes the /MK characteristics (/CA, /RC, /AC, /TP) and regenerates the widget's /AP with distinct /N (normal), /R (rollover), and /D (down) appearance streams. Returns an error if the field has no widget or the icon image cannot be read.

func (*ButtonField) SetReadOnly

func (f *ButtonField) SetReadOnly(v bool)

func (*ButtonField) SetStyle added in v0.3.0

func (b *ButtonField) SetStyle(s FieldStyle) error

SetStyle applies s to the field, writing /MK, /BS, /DA, and /Q on the field and its widgets and regenerating each widget's /AP appearance so the new look is visible immediately in every viewer. Returns an error only if the field is detached or a styled font cannot be registered.

func (*ButtonField) SetValue

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

func (*ButtonField) Style added in v0.3.0

func (b *ButtonField) Style() FieldStyle

Style reads back the field's current styling from /DA, /Q, /MK, and /BS. Properties never set return their zero/default value. The first widget is used for /MK and /BS.

func (*ButtonField) Value

func (f *ButtonField) Value() string

type ButtonIconPosition added in v0.3.0

type ButtonIconPosition int

ButtonIconPosition controls how a push button lays out its icon and caption — the /MK /TP entry per ISO 32000-1 §12.5.6.19 Table 189.

const (
	ButtonCaptionOnly      ButtonIconPosition = 0 // /TP 0 — caption only, no icon
	ButtonIconOnly         ButtonIconPosition = 1 // /TP 1 — icon only, no caption
	ButtonIconAboveCaption ButtonIconPosition = 2 // /TP 2 — caption below the icon
	ButtonCaptionOverIcon  ButtonIconPosition = 6 // /TP 6 — caption overlaid on the icon
)

type CaretAnnotation added in v0.4.0

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

CaretAnnotation marks a point of text insertion or deletion, drawn as an upward caret ("^") filled with the annotation colour. Mirrors Aspose.PDF for .NET's CaretAnnotation.

func NewCaretAnnotation added in v0.4.0

func NewCaretAnnotation(page *Page, rect Rectangle) *CaretAnnotation

NewCaretAnnotation builds an unbound caret annotation occupying rect. Page must be non-nil. The caret is drawn to fill the rectangle; set a colour with SetColor (default black).

func (*CaretAnnotation) AnnotationType added in v0.4.0

func (a *CaretAnnotation) AnnotationType() AnnotationType

func (*CaretAnnotation) BorderStyle added in v0.4.0

func (d *CaretAnnotation) BorderStyle() BorderStyle

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

func (*CaretAnnotation) BorderWidth added in v0.4.0

func (d *CaretAnnotation) 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 (*CaretAnnotation) DashPattern added in v0.4.0

func (d *CaretAnnotation) 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 (*CaretAnnotation) RegenerateAppearance added in v0.4.0

func (a *CaretAnnotation) RegenerateAppearance()

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

func (*CaretAnnotation) SetBorderStyle added in v0.4.0

func (d *CaretAnnotation) SetBorderStyle(s BorderStyle)

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

func (*CaretAnnotation) SetBorderWidth added in v0.4.0

func (d *CaretAnnotation) SetBorderWidth(w float64)

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

func (*CaretAnnotation) SetColor added in v0.4.0

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

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

func (*CaretAnnotation) SetDashPattern added in v0.4.0

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

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

func (*CaretAnnotation) SetRect added in v0.4.0

func (d *CaretAnnotation) 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 (*CaretAnnotation) SetSymbol added in v0.4.0

func (a *CaretAnnotation) SetSymbol(s CaretSymbol)

SetSymbol writes /Sy. CaretSymbolNone removes the entry.

func (*CaretAnnotation) Symbol added in v0.4.0

func (a *CaretAnnotation) Symbol() CaretSymbol

Symbol returns the /Sy symbol drawn with the caret.

type CaretSymbol added in v0.4.0

type CaretSymbol int

CaretSymbol is the /Sy entry of a Caret annotation per ISO 32000-1 §12.5.6.11 Table 180 — an optional symbol drawn together with the caret to associate it with an editing action.

const (
	// CaretSymbolNone draws the caret alone (/Sy /None or absent).
	CaretSymbolNone CaretSymbol = iota
	// CaretSymbolParagraph draws a paragraph symbol with the caret (/Sy /P).
	CaretSymbolParagraph
)

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 CertifyPermission added in v0.4.0

type CertifyPermission int

CertifyPermission is the DocMDP permission level of a certification signature (ISO 32000-1 §12.8.2.2 Table 254). Its integer value is the /P entry written to /TransformParams.

const (
	NotCertified       CertifyPermission = iota // ordinary approval signature (default)
	CertifyNoChanges                            // P=1: no changes permitted
	CertifyFillForms                            // P=2: form filling and signing
	CertifyAnnotations                          // P=3: form filling, signing, and annotations
)

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) Flatten added in v0.3.0

func (b *CheckboxField) Flatten() error

Flatten bakes this single field's appearance (each of its widgets) into the owning page content and removes the field, leaving every other field and the /AcroForm dict intact. Mirrors Aspose.PDF for .NET's Field.Flatten.

After Flatten the field handle is dangling and must not be used.

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) SetStyle added in v0.3.0

func (b *CheckboxField) SetStyle(s FieldStyle) error

SetStyle applies s to the field, writing /MK, /BS, /DA, and /Q on the field and its widgets and regenerating each widget's /AP appearance so the new look is visible immediately in every viewer. Returns an error only if the field is detached or a styled font cannot be registered.

func (*CheckboxField) SetValue

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

func (*CheckboxField) Style added in v0.3.0

func (b *CheckboxField) Style() FieldStyle

Style reads back the field's current styling from /DA, /Q, /MK, and /BS. Properties never set return their zero/default value. The first widget is used for /MK and /BS.

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 Collection added in v0.8.0

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

Collection is the document's portfolio view over its embedded files. Always non-nil; IsPortfolio reports whether the document actually carries a /Collection dictionary. Mutating calls create it.

func (*Collection) Files added in v0.8.0

func (c *Collection) Files() []*EmbeddedFile

Files returns the portfolio's attachments — the document's embedded files, which a portfolio is a presentation layer over.

func (*Collection) InitialFile added in v0.8.0

func (c *Collection) InitialFile() string

InitialFile returns the name of the attachment a viewer opens first, or "" when unset.

func (*Collection) IsPortfolio added in v0.8.0

func (c *Collection) IsPortfolio() bool

IsPortfolio reports whether the document presents its attachments as a portfolio.

func (*Collection) Remove added in v0.8.0

func (c *Collection) Remove()

Remove drops the /Collection dictionary: the attachments stay, presented as an ordinary attachment list again.

func (*Collection) Schema added in v0.8.0

func (c *Collection) Schema() *CollectionSchema

Schema returns the portfolio's column schema.

func (*Collection) SetInitialFile added in v0.8.0

func (c *Collection) SetInitialFile(name string)

SetInitialFile names the attachment a viewer should present first; "" clears the entry. The name must match an embedded file's name-tree key.

func (*Collection) SetSort added in v0.8.0

func (c *Collection) SetSort(field string, ascending bool)

SetSort makes the viewer sort the file list by the named schema field; an empty field clears the sort.

func (*Collection) SetView added in v0.8.0

func (c *Collection) SetView(v CollectionView)

SetView sets the presentation mode, turning the document into a portfolio if it is not one already.

func (*Collection) Sort added in v0.8.0

func (c *Collection) Sort() (field string, ascending bool, ok bool)

Sort returns the field the viewer sorts by and its direction; ok is false when no sort is configured.

func (*Collection) View added in v0.8.0

func (c *Collection) View() CollectionView

View returns the presentation mode; CollectionViewDetails when unset.

type CollectionField added in v0.8.0

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

CollectionField is one portfolio column.

func (*CollectionField) DisplayName added in v0.8.0

func (f *CollectionField) DisplayName() string

DisplayName returns the column header text.

func (*CollectionField) IsDerived added in v0.8.0

func (f *CollectionField) IsDerived() bool

IsDerived reports whether the column's values come from the attachment's file specification (file name, description, dates, size) rather than from its collection item — such a column needs no per-file value.

func (*CollectionField) IsEditable added in v0.8.0

func (f *CollectionField) IsEditable() bool

IsEditable reports whether a viewer may edit the values (/E, default false).

func (*CollectionField) IsVisible added in v0.8.0

func (f *CollectionField) IsVisible() bool

IsVisible reports whether the viewer shows the column (/V, default true).

func (*CollectionField) Key added in v0.8.0

func (f *CollectionField) Key() string

Key returns the field key used by collection items.

func (*CollectionField) Order added in v0.8.0

func (f *CollectionField) Order() int

Order returns the column's position (/O); 0 when unset.

func (*CollectionField) SetDisplayName added in v0.8.0

func (f *CollectionField) SetDisplayName(s string)

SetDisplayName sets the column header text.

func (*CollectionField) SetEditable added in v0.8.0

func (f *CollectionField) SetEditable(v bool)

SetEditable allows or forbids viewer-side editing of the column's values.

func (*CollectionField) SetOrder added in v0.8.0

func (f *CollectionField) SetOrder(n int)

SetOrder sets the column's position among the others.

func (*CollectionField) SetVisible added in v0.8.0

func (f *CollectionField) SetVisible(v bool)

SetVisible shows or hides the column.

func (*CollectionField) Type added in v0.8.0

Type returns the column's value type.

type CollectionFieldType added in v0.8.0

type CollectionFieldType int

CollectionFieldType is a schema column's data type (the collection field's /Subtype). The last five are derived fields: their values come from the file specification itself, so they need no per-file collection-item entry.

const (
	// CollectionFieldText holds a text value (/S).
	CollectionFieldText CollectionFieldType = iota
	// CollectionFieldDate holds a date value (/D).
	CollectionFieldDate
	// CollectionFieldNumber holds a numeric value (/N).
	CollectionFieldNumber
	// CollectionFieldFilename shows the attachment's file name (/F).
	CollectionFieldFilename
	// CollectionFieldDescription shows the attachment's description (/Desc).
	CollectionFieldDescription
	// CollectionFieldModDate shows the embedded file's modification date
	// (/ModDate).
	CollectionFieldModDate
	// CollectionFieldCreationDate shows the embedded file's creation date
	// (/CreationDate).
	CollectionFieldCreationDate
	// CollectionFieldSize shows the embedded file's size in bytes (/Size).
	CollectionFieldSize
)

type CollectionItem added in v0.8.0

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

CollectionItem holds one attachment's values for the portfolio's schema fields (the file specification's /CI dictionary).

func (*CollectionItem) Date added in v0.8.0

func (i *CollectionItem) Date(field string) (value time.Time, ok bool)

Date returns the field's date value; ok is false when the field is unset or does not parse as a PDF date.

func (*CollectionItem) Fields added in v0.8.0

func (i *CollectionItem) Fields() []string

Fields returns the keys this item carries values for, sorted.

func (*CollectionItem) Number added in v0.8.0

func (i *CollectionItem) Number(field string) (value float64, ok bool)

Number returns the field's numeric value; ok is false when the field is unset or holds another type.

func (*CollectionItem) Remove added in v0.8.0

func (i *CollectionItem) Remove(field string) bool

Remove deletes the item's value for a field; it reports whether one was removed.

func (*CollectionItem) SetDate added in v0.8.0

func (i *CollectionItem) SetDate(field string, t time.Time)

SetDate stores a date value for the field (written as a PDF date string).

func (*CollectionItem) SetNumber added in v0.8.0

func (i *CollectionItem) SetNumber(field string, value float64)

SetNumber stores a numeric value for the field.

func (*CollectionItem) SetText added in v0.8.0

func (i *CollectionItem) SetText(field, value string)

SetText stores a text value for the field.

func (*CollectionItem) Text added in v0.8.0

func (i *CollectionItem) Text(field string) string

Text returns the field's value as text, or "" when unset.

type CollectionSchema added in v0.8.0

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

CollectionSchema is the portfolio's set of columns.

func (*CollectionSchema) Add added in v0.8.0

func (s *CollectionSchema) Add(key, displayName string, typ CollectionFieldType) *CollectionField

Add defines a column: key identifies the field in collection items, displayName is the header a viewer shows, and typ is the value type. Re-adding an existing key replaces it. The new field is visible, not editable, and ordered after the existing ones.

func (*CollectionSchema) Count added in v0.8.0

func (s *CollectionSchema) Count() int

Count returns the number of columns.

func (*CollectionSchema) Field added in v0.8.0

func (s *CollectionSchema) Field(key string) *CollectionField

Field returns the column with the given key, or nil.

func (*CollectionSchema) Fields added in v0.8.0

func (s *CollectionSchema) Fields() []*CollectionField

Fields returns the columns in display order (by /O, then by key).

func (*CollectionSchema) Keys added in v0.8.0

func (s *CollectionSchema) Keys() []string

Keys returns the column keys in display order.

func (*CollectionSchema) Remove added in v0.8.0

func (s *CollectionSchema) Remove(key string) bool

Remove deletes a column; it reports whether one was removed. Values already stored in collection items are left alone (harmless, and they reappear if the column is added back).

type CollectionView added in v0.8.0

type CollectionView int

CollectionView selects how a viewer presents the portfolio's files (the /Collection /View entry).

const (
	// CollectionViewDetails lists the files in a table of schema columns (/D).
	CollectionViewDetails CollectionView = iota
	// CollectionViewTiles shows one tile per file (/T).
	CollectionViewTiles
	// CollectionViewHidden hides the portfolio pane, showing the cover
	// page only (/H).
	CollectionViewHidden
)

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) Flatten added in v0.3.0

func (b *ComboBoxField) Flatten() error

Flatten bakes this single field's appearance (each of its widgets) into the owning page content and removes the field, leaving every other field and the /AcroForm dict intact. Mirrors Aspose.PDF for .NET's Field.Flatten.

After Flatten the field handle is dangling and must not be used.

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 sets the read-only flag; the choice types share the same setFlag-based mutators as the text field.

func (*ComboBoxField) SetRequired

func (f *ComboBoxField) SetRequired(v bool)

func (*ComboBoxField) SetSelected

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

func (*ComboBoxField) SetStyle added in v0.3.0

func (b *ComboBoxField) SetStyle(s FieldStyle) error

SetStyle applies s to the field, writing /MK, /BS, /DA, and /Q on the field and its widgets and regenerating each widget's /AP appearance so the new look is visible immediately in every viewer. Returns an error only if the field is detached or a styled font cannot be registered.

func (*ComboBoxField) SetValue

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

func (*ComboBoxField) Style added in v0.3.0

func (b *ComboBoxField) Style() FieldStyle

Style reads back the field's current styling from /DA, /Q, /MK, and /BS. Properties never set return their zero/default value. The first widget is used for /MK and /BS.

func (*ComboBoxField) Value

func (f *ComboBoxField) Value() string

type ComparisonOptions added in v0.9.0

type ComparisonOptions struct {
	// ExtractionArea limits the comparison to the words whose centre lies in
	// this rectangle. Cannot be combined with ExcludeTables or ExcludeAreas.
	ExtractionArea *Rectangle
	// ExcludeAreas1 lists regions of the first document to ignore.
	ExcludeAreas1 []Rectangle
	// ExcludeAreas2 lists regions of the second document to ignore.
	ExcludeAreas2 []Rectangle
	// ExcludeTables drops the words inside tables found by the TableAbsorber.
	ExcludeTables bool
	// EditOperationsOrder decides which half of a replacement is reported first.
	EditOperationsOrder EditOperationsOrder
	// IgnoreCase compares words without regard to letter case. This library's
	// addition; Aspose has no equivalent.
	IgnoreCase bool
}

ComparisonOptions narrows what is compared. The zero value compares the whole page, case-sensitively, reporting deletions before insertions. Mirrors Aspose.PDF for .NET's ComparisonOptions, plus IgnoreCase.

type ComparisonResult added in v0.9.0

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

ComparisonResult holds the differences between two documents and can write a marked-up copy of either side.

func CompareDocumentsPageByPage added in v0.9.0

func CompareDocumentsPageByPage(d1, d2 *Document, opts ...ComparisonOptions) (*ComparisonResult, error)

CompareDocumentsPageByPage compares page 1 with page 1, page 2 with page 2 and so on; the pages of the longer document beyond the shorter one are reported wholly inserted or wholly deleted. Mirrors Aspose.PDF for .NET's TextPdfComparer.CompareDocumentsPageByPage.

func CompareFlatDocuments added in v0.9.0

func CompareFlatDocuments(d1, d2 *Document, opts ...ComparisonOptions) (*ComparisonResult, error)

CompareFlatDocuments compares the documents as one continuous text, so content that moved across a page boundary reads as unchanged. Mirrors Aspose.PDF for .NET's TextPdfComparer.CompareFlatDocuments.

func (*ComparisonResult) HasChanges added in v0.9.0

func (r *ComparisonResult) HasChanges() bool

HasChanges reports whether anything differs. Mirrors Aspose.PDF for .NET's SideBySideDocsComparisonResult.HasChanges.

func (*ComparisonResult) Operations added in v0.9.0

func (r *ComparisonResult) Operations() []DiffOperation

Operations returns every operation, differences and unchanged runs alike, in document order. The returned slice is the result's internal storage; the caller must not sort or truncate it in place.

func (*ComparisonResult) PageOperations added in v0.9.0

func (r *ComparisonResult) PageOperations(pageNum int) []DiffOperation

PageOperations returns the operations of one 1-based page. An operation is listed under the page it physically occupies: the second document's page for equal and inserted text, the first document's page for deleted text. In page-by-page mode the returned slice is the result's internal storage; the caller must not sort or truncate it in place.

func (*ComparisonResult) Pages added in v0.10.0

func (r *ComparisonResult) Pages() [][]DiffOperation

Pages returns the operations grouped one slice per page, the shape every diff output generator's *Pages method expects — the same shape CompareDocumentsPageByPage/CompareFlatDocuments return directly in Aspose.PDF for .NET. In page-by-page mode this is the result's own per-page storage; in flat mode it is built from PageOperations, since flat mode keeps only the flat op list.

func (*ComparisonResult) SaveMarkup added in v0.9.0

func (r *ComparisonResult) SaveMarkup(path string, opts ...DiffMarkupOptions) error

SaveMarkup writes a copy of one of the compared documents with every difference marked as an annotation. The documents handed to the comparer are left untouched; the output is a new document, so signatures on the input do not survive the copy. Marking up an encrypted document is not supported — save it without encryption first.

func (*ComparisonResult) Statistics added in v0.9.0

func (r *ComparisonResult) Statistics() ComparisonStatistics

Statistics counts the words on each side of the comparison. Mirrors Aspose.PDF for .NET's TextPdfComparer.CreateComparisonStatistics.

func (*ComparisonResult) WriteMarkup added in v0.9.0

func (r *ComparisonResult) WriteMarkup(w io.Writer, opts ...DiffMarkupOptions) error

WriteMarkup writes the marked-up copy to w. The output is a new document, so signatures on the input do not survive the copy. Marking up an encrypted document is not supported — save it without encryption first.

type ComparisonStatistics added in v0.9.0

type ComparisonStatistics struct {
	EqualWords    int
	InsertedWords int
	DeletedWords  int
	// ChangedPages lists, ascending, the pages carrying a change. Each page
	// number is chosen by the same rule PageOperations uses to place an
	// operation — the destination page for equal and inserted text, the
	// source page for deleted text — but since only non-equal operations
	// contribute, in practice this means the destination page for an
	// insertion and the source page for a deletion. In flat mode source and
	// destination page numbers are independent counters, so this list can
	// mix the two numbering spaces.
	ChangedPages []int
}

ComparisonStatistics summarises a comparison. Mirrors the shape of Aspose.PDF for .NET's DocumentComparisonStatistics.

type DateField added in v0.4.0

type DateField struct{ TextBoxField }

DateField is a text field with a JavaScript date-format action and a format mask (e.g. "mm/dd/yyyy").

func (*DateField) Flatten added in v0.4.0

func (b *DateField) Flatten() error

Flatten bakes this single field's appearance (each of its widgets) into the owning page content and removes the field, leaving every other field and the /AcroForm dict intact. Mirrors Aspose.PDF for .NET's Field.Flatten.

After Flatten the field handle is dangling and must not be used.

func (*DateField) Format added in v0.4.0

func (d *DateField) Format() string

Format returns the date field's format mask (parsed back from its format JS).

func (*DateField) FullName added in v0.4.0

func (b *DateField) FullName() string

func (*DateField) IsReadOnly added in v0.4.0

func (b *DateField) IsReadOnly() bool

func (*DateField) IsRequired added in v0.4.0

func (b *DateField) IsRequired() bool

func (*DateField) PageIndex added in v0.4.0

func (b *DateField) PageIndex() int

func (*DateField) PartialName added in v0.4.0

func (b *DateField) PartialName() string

func (*DateField) Rect added in v0.4.0

func (b *DateField) Rect() Rectangle

func (*DateField) SetStyle added in v0.4.0

func (b *DateField) SetStyle(s FieldStyle) error

SetStyle applies s to the field, writing /MK, /BS, /DA, and /Q on the field and its widgets and regenerating each widget's /AP appearance so the new look is visible immediately in every viewer. Returns an error only if the field is detached or a styled font cannot be registered.

func (*DateField) Style added in v0.4.0

func (b *DateField) Style() FieldStyle

Style reads back the field's current styling from /DA, /Q, /MK, and /BS. Properties never set return their zero/default value. The first widget is used for /MK and /BS.

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 DiffMarkupOptions added in v0.9.0

type DiffMarkupOptions struct {
	Side        DiffMarkupSide
	InsertColor *Color
	DeleteColor *Color
	Title       string
	// Flatten bakes the comparison markup into the page content and removes
	// it, via (*AnnotationCollection).Flatten. That call flattens every
	// non-widget annotation already on the page, not only the ones this
	// writer added — an existing highlight or free-text annotation in the
	// source document is flattened too.
	Flatten bool
}

DiffMarkupOptions styles the marked-up copy. The zero value marks the second document in green and red, titles every annotation "Comparison" and keeps the annotations live.

type DiffMarkupSide added in v0.9.0

type DiffMarkupSide int

DiffMarkupSide selects which document the markup is drawn on.

const (
	// DiffMarkupDestination marks the second document: insertions
	// highlighted, deletions shown as carets carrying the removed text. The
	// zero value.
	DiffMarkupDestination DiffMarkupSide = iota
	// DiffMarkupSource marks the first document: deletions struck out,
	// insertions shown as carets carrying the added text.
	DiffMarkupSource
)

type DiffOperation added in v0.9.0

type DiffOperation struct {
	Operation Operation
	// Text is the run's words joined with single spaces. For OperationEqual
	// it is the first document's spelling, which can differ from the second's
	// when ComparisonOptions.IgnoreCase is set.
	Text string
	// SourcePage is the 1-based page in the first document, 0 for an insertion.
	SourcePage int
	// DestPage is the 1-based page in the second document, 0 for a deletion.
	DestPage int
	// SourceRects holds one rectangle per line the run touches in the first
	// document; empty for an insertion.
	SourceRects []Rectangle
	// DestRects holds one rectangle per line the run touches in the second
	// document; empty for a deletion.
	DestRects []Rectangle
}

DiffOperation is one run of adjacent words sharing an operation. Runs break at line and page boundaries, so every rectangle is a real box on a real page: a run spanning three lines carries three rectangles.

Operation and Text mirror Aspose.PDF for .NET's DiffOperation; the page and rectangle fields are this library's addition.

func ComparePages added in v0.9.0

func ComparePages(p1, p2 *Page, opts ...ComparisonOptions) ([]DiffOperation, error)

ComparePages compares the text of two pages and returns the differences in reading order. Mirrors Aspose.PDF for .NET's TextPdfComparer.ComparePages.

type DiffOutputStyle added in v0.10.0

type DiffOutputStyle struct {
	InsertColor, InsertBackground *Color
	DeleteColor, DeleteBackground *Color
	EqualColor, EqualBackground   *Color
	// StrikethroughDelete draws deleted text with a line through it. Mirrors
	// OutputTextStyle.StrikethroughDeleted; default false. Markdown has no
	// equivalent knob — a deletion is always struck through there, since GFM
	// strikethrough is the only way to represent one at all.
	StrikethroughDelete bool
}

DiffOutputStyle colors the three kinds of text a diff output generator marks. The zero value resolves to the same green/red pair DiffMarkupOptions defaults to, keeping every comparison output visually consistent. Mirrors the intent of Aspose.PDF for .NET's OutputTextStyle (its per-kind TextStyle{Color, BackgroundColor} pairs are flattened here, since TextStyle already names an unrelated type in this library).

type DigestAlgorithm added in v0.10.0

type DigestAlgorithm int

DigestAlgorithm is the hash a signature is computed with. Mirrors Aspose.PDF for .NET's DigestHashAlgorithm; the zero value is SHA-256, which is what every earlier release wrote.

const (
	DigestSHA256   DigestAlgorithm = iota // SHA-256 (default)
	DigestSHA384                          // SHA-384
	DigestSHA512                          // SHA-512
	DigestSHA3_256                        // SHA3-256
	DigestSHA3_384                        // SHA3-384
	DigestSHA3_512                        // SHA3-512
)

func (DigestAlgorithm) String added in v0.10.0

func (a DigestAlgorithm) String() string

String names the algorithm the way the standards do.

type DocRecognitionMode added in v0.7.0

type DocRecognitionMode int

DocRecognitionMode selects the reconstruction algorithm — mirrors Aspose.PDF for .NET's DocSaveOptions.RecognitionMode.

const (
	// DocEnhancedFlow (default) is DocFlow plus table recognition: ruled
	// tables detected by the TableAbsorber become real, editable Word
	// tables (w:tbl with gridSpan/vMerge); tables the detector cannot
	// claim still carry over as pictures. Mirrors Aspose's EnhancedFlow.
	DocEnhancedFlow DocRecognitionMode = iota
	// DocFlow performs full structure recognition (headings, lists, runs)
	// without table reconstruction — ruled tables carry over as pictures
	// (Aspose Flow-mode behaviour).
	DocFlow
	// DocTextbox is the fixed-layout mode: every paragraph becomes an
	// absolutely positioned floating text box at its PDF coordinates and
	// every image an anchored picture — maximal visual fidelity, limited
	// editability, no reconstruction heuristics. Mirrors Aspose's Textbox.
	DocTextbox
)

type DocSaveOptions added in v0.7.0

type DocSaveOptions struct {
	// Pages is a 1-based subset (in the given order); nil = all pages.
	Pages []int
	// Mode is the reconstruction algorithm; the zero value DocEnhancedFlow
	// recognizes ruled tables as real Word tables.
	Mode DocRecognitionMode
	// NoImages skips images.
	NoImages bool
	// NoPageBreaks lets content flow continuously instead of starting a new
	// Word page where each source PDF page started (the default inserts a
	// page break, so the output pagination mirrors the original; exact
	// fit still depends on Word's own line layout).
	NoPageBreaks bool
}

DocSaveOptions configures SaveDocx / WriteDocx. The zero value exports all pages in Flow mode with images, preserving the source pagination.

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

Example

Convert a standalone image into a single-page PDF.

package main

import (
	"fmt"
	"log"

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

func main() {
	doc, err := pdf.ImageToDocument("testdata/Koala.jpg")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("pages:", doc.PageCount())
}
Output:
pages: 1

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 MarkdownToDocument added in v0.6.0

func MarkdownToDocument(path string, opts ...MarkdownOptions) (*Document, error)

MarkdownToDocument renders a Markdown file as a new PDF document.

func MarkdownToDocumentFromStream added in v0.6.0

func MarkdownToDocumentFromStream(r io.Reader, opts ...MarkdownOptions) (*Document, error)

MarkdownToDocumentFromStream renders Markdown read from r as a new PDF document.

Example

Convert Markdown (CommonMark + GFM) into a paginated PDF.

package main

import (
	"fmt"
	"log"
	"strings"

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

func main() {
	md := "# Hello\n\nA paragraph with **bold** text.\n"
	doc, err := pdf.MarkdownToDocumentFromStream(strings.NewReader(md))
	if err != nil {
		log.Fatal(err)
	}
	pages, _ := doc.ExtractText()
	fmt.Println(strings.Split(pages[0], "\n")[0])
}
Output:
Hello

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.

Example

Create a blank A4 document in memory.

package main

import (
	"fmt"

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

func main() {
	doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
	page, _ := doc.Page(1)
	size, _ := page.Size()
	fmt.Printf("%.0fx%.0f pt\n", size.Width, size.Height)
}
Output:
595x842 pt

func Open

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

Open opens a PDF file and returns a Document.

Example:

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

Open a PDF file and inspect its page count.

package main

import (
	"fmt"
	"log"

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

func main() {
	doc, err := pdf.Open("testdata/4pages.pdf")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(doc.PageCount(), "pages")
}
Output:
4 pages

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 OpenStreamWithCertificate added in v0.8.0

func OpenStreamWithCertificate(r io.Reader, cert *x509.Certificate, key crypto.Decrypter) (*Document, error)

OpenStreamWithCertificate reads a certificate-encrypted PDF from r. See OpenWithCertificate.

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 OpenWithCertificate added in v0.8.0

func OpenWithCertificate(path string, cert *x509.Certificate, key crypto.Decrypter) (*Document, error)

OpenWithCertificate opens a PDF encrypted for certificate recipients (the public-key security handler, /Filter /Adobe.PubSec) using the recipient's certificate and its private key. The key is any crypto.Decrypter — an *rsa.PrivateKey satisfies it — so no .p12 file is required. Plain and password-protected files are rejected with a message pointing at the right entry point.

Example:

doc, err := asposepdf.OpenWithCertificate("secret.pdf", cert, key)

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. Returns ErrInvalidPassword if it matches neither.

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

Open an encrypted PDF by trying the password as both user and owner password.

package main

import (
	"bytes"
	"errors"
	"fmt"
	"log"

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

func main() {
	// Build an encrypted document in memory so the example is self-contained.
	src := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
	src.SetEncryption(pdf.EncryptionOptions{UserPassword: "secret"})
	var buf bytes.Buffer
	if _, err := src.WriteTo(&buf); err != nil {
		log.Fatal(err)
	}

	if _, err := pdf.OpenStreamWithPassword(bytes.NewReader(buf.Bytes()), "guess"); errors.Is(err, pdf.ErrInvalidPassword) {
		fmt.Println("wrong password rejected")
	}
	doc, err := pdf.OpenStreamWithPassword(bytes.NewReader(buf.Bytes()), "secret")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("opened:", doc.PageCount(), "pages")
}
Output:
wrong password rejected
opened: 1 pages

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) AddLayer added in v0.4.0

func (d *Document) AddLayer(name string) *Layer

AddLayer creates a new layer (OCG) named name and registers it in the document's optional-content properties. The layer is visible by default; call SetVisible(false) to hide it. Returns the layer for assigning content (Page.BeginLayer) and tuning visibility.

func (*Document) AddSVGObjectWatermark added in v0.2.0

func (d *Document) AddSVGObjectWatermark(svg *SVG, pageNums ...int) error

AddSVGObjectWatermark uses a pre-parsed *SVG for the watermark content. Renders into each target page's full MediaBox.

func (*Document) AddSVGWatermark added in v0.2.0

func (d *Document) AddSVGWatermark(path string, pageNums ...int) error

AddSVGWatermark applies an SVG watermark to all pages (when pageNums is empty) or to the specified 1-based page numbers. The SVG is positioned to fill each page's MediaBox honoring its own preserveAspectRatio attribute.

Example

Stamp an SVG logo as a watermark on every page.

package main

import (
	"bytes"
	"fmt"
	"log"

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

func main() {
	doc, err := pdf.Open("testdata/4pages.pdf")
	if err != nil {
		log.Fatal(err)
	}
	if err := doc.AddSVGWatermark("testdata/aspose-logo.svg"); err != nil {
		log.Fatal(err)
	}
	var buf bytes.Buffer
	if _, err := doc.WriteTo(&buf); err != nil {
		log.Fatal(err)
	}
	fmt.Println("watermarked:", buf.Len() > 0)
}
Output:
watermarked: true

func (*Document) AddSVGWatermarkFromStream added in v0.2.0

func (d *Document) AddSVGWatermarkFromStream(r io.Reader, pageNums ...int) error

AddSVGWatermarkFromStream is the io.Reader variant of AddSVGWatermark.

func (*Document) AddStamp added in v0.4.0

func (d *Document) AddStamp(s Stamp, pageNums ...int) error

AddStamp draws a stamp onto the given 1-based pages (all pages when none are given) — convenient for watermarks, headers, footers, and page numbers. A PageNumberStamp renders the correct number on each page.

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

Example

Apply a diagonal "DRAFT" text watermark behind the content of every page.

package main

import (
	"fmt"
	"log"

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

func main() {
	doc, err := pdf.Open("testdata/4pages.pdf")
	if err != nil {
		log.Fatal(err)
	}
	style := pdf.TextStyle{
		Font:     pdf.FontHelveticaBold,
		Size:     72,
		Color:    &pdf.Color{R: 0.85, G: 0.85, B: 0.85, A: 0.5},
		Rotation: 45,
		HAlign:   pdf.HAlignCenter,
		VAlign:   pdf.VAlignMiddle,
		Behind:   true,
	}
	if err := doc.AddTextWatermark("DRAFT", style); err != nil {
		log.Fatal(err)
	}
	fmt.Println("ok")
}
Output:
ok

func (*Document) AddValidationInfo added in v0.10.0

func (d *Document) AddValidationInfo(opts ...ValidationOptions) error

AddValidationInfo collects the certificates and revocation material for every signature in the document and writes them into the catalog as /DSS, appended as a new revision so signatures already in the file stay valid. This is long-term validation: the evidence travels with the document, so it still verifies once the certificate expires or the responder is gone.

The document must have been opened from a file or stream. Network access is opt-in through ValidationOptions — with the zero value nothing is fetched and only the certificates the signature carries are recorded. Mirrors the intent of Aspose.PDF for .NET's LTV support.

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

Merge two documents by appending all pages of one into another.

package main

import (
	"fmt"
	"log"

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

func main() {
	a, err := pdf.Open("testdata/4pages.pdf")
	if err != nil {
		log.Fatal(err)
	}
	b, err := pdf.Open("testdata/4pages.pdf")
	if err != nil {
		log.Fatal(err)
	}
	a.Append(b)
	fmt.Println("merged:", a.PageCount(), "pages")
}
Output:
merged: 8 pages

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. A glyph's page-space position correctly accounts for the graphics-state CTM a "cm" sets, not just the text matrix — see rewriteTextOperatorsInStream's own doc comment (pdf-go-njbg, closed): text drawn after a non-identity "cm" (the common top-left-origin Y-flip many producers emit once per page) used to be compared against regions at the wrong position and so never matched, even when the region came straight from SearchText's own (correct) answer.

Calls RemoveUnusedObjects once at the end when at least one page was redacted, so the content stream(s) a page's /Contents pointed to before redaction — and any earlier dead copy left by prior drawing calls (image_add.go's appendToContentStream, see pdf-go-qgrn) — are actually gone from the saved file rather than merely unreferenced. Both still carry the redacted content in full, recoverable with any PDF tool, until this runs: replacePageContents (used here and by FlattenTransparency) only repoints /Contents, it was never the writer's job to drop what it replaces. Reported privately by shadowhunter1470-svg via GitHub's private vulnerability reporting (pdf-go-2qkq) — thank you for the careful, considerate report.

This sweep shares RemoveUnusedObjects' usual trade-off: a page/catalog -unreachable object that is not yet "dangerous" — e.g. a Type3 glyph canvas or an XForm the caller built but has not placed on any page yet — is reclaimed too. Call ApplyRedactions only after placing everything you mean to keep, same as any other Optimize-family call.

A Form XObject intersecting a redaction region — fully or partially — is now redacted into, not refused (pdf-go-w5hl, closed; a v0.11.0 safety stopgap until then): the region is mapped from page space into the form's own local content-stream space by inverting the composed placement matrix (the form's /Matrix, then the CTM the Do invocation was under — formPlacementBbox's own convention, run in reverse), and the SAME three rewriters this method uses at the page level then run on the form's content with those local-space regions, recursing into a nested Form XObject the same way (up to maxFormRedactDepth levels, and a total maxFormRedactWork placements per PAGE, not across the whole call — see maxFormRedactWork's own doc comment for why that scope is intentional — a fan-out of region-intersecting placements can exhaust this long before the depth cap, bounding a pathologically fan-out-heavy or self-referential file). Neither cap is a silent blind spot: exceeding either one while a region genuinely intersects an unexamined Do is refused (an error), not left incomplete — an earlier draft of the depth cap skipped silently instead, caught by an independent review. The ORIGINAL form object, and its own /Resources dict, are never mutated: since the same Form XObject (and the same /Resources, shared by every placement of it) can be placed more than once — the same logo stamped on every page, say — only placements that actually need a change are redirected (their one Do operand only) to a freshly cloned, redacted copy with its own private /Resources, PRUNED to exactly the /XObject entries the clone's own (rewritten) content still needs (see neededXObjectNames) — every other placement of the original keeps rendering exactly as before. The same sharing hazard applies one level up too: a PAGE's own /Resources can itself be shared across pages via an indirect reference (another common producer size optimization), so this method gives each redacted page a private copy of its own before redacting into it, pruned the same way — minus whatever an annotation appearance stream with no own /Resources on that page still needs through it (see pagePreservedXObjectNames), since the page-level prune has no visibility into annotations on its own. Three sharing/pruning hazards here — a cloned form's own private resources still forwarding a reference to the very original object it replaces (through an inherited entry its own content never uses), a page-level prune removing a name a SIBLING Form XObject sharing that same dict still calls, and the two levels of resources-dict sharing this paragraph opened with — were all confirmed reachable (an unrelated, non-redacted page or placement silently losing content, or the original secret-bearing object staying reachable and un-collectable) across two rounds of independent review of this fix. Still refused outright, not guessed at: a Form XObject with no resolvable /BBox (formPlacementBbox's own ok=false — ISO 32000-1 §8.10.2 requires one on every conformant form) or a placement matrix that doesn't invert (so a region can't be mapped into the form's space at all) — see redactFormDo/redactFormXObject.

Known gaps (not closed by this sweep, tracked separately). Two MORE SEVERE ones — where the secret used to survive not just forensically (pdf-go-2qkq's class) but through this library's own ORDINARY read APIs on the "redacted" file — are now closed: a Tj/TJ run under a font this pipeline cannot classify now REFUSES (an error) rather than passing through unredacted (pdf-go-oq9i; several such "unknown" cases were still visible when rendered and extractable via ExtractText/SearchText, which substitute Helvetica or read the embedded program's own encoding where this redaction-specific flag gives up); and a BDC marked-content span's /ActualText property (common in accessibility-tagged output from Word, InDesign, etc.) is now scrubbed whenever anything inside its span was redacted, so ExtractText/SearchText on a redacted page can no longer return the original secret text verbatim via that replacement mechanism (pdf-go-1ha8). Both fixed in rewriteTextOperatorsInStream (redact_apply_text.go) — see its own doc comment. A further independent review of those two fixes found and closed two more real gaps in the SAME /ActualText mechanism (both documented in rewriteTextOperatorsInStream's own comment, not repeated here) and one gap in ApplyRedactions' own error handling: returning on the first page that errors used to skip RemoveUnusedObjects entirely, so any EARLIER page that had already redacted successfully still had its pre-redaction stream sitting dead but unswept in d.objects — reachable in practice now that pdf-go-oq9i gives this method a real way to fail partway through a multi-page document, where before every rewriter just silently passed through instead. Fixed by sweeping whatever succeeded so far before returning the error, not only on the all-succeeded path.

An Image XObject fully inside a redaction region has its Do invocation dropped from the content stream, and — closed, pdf-go-ye1z — its /Resources/XObject entry is pruned from the page's own (already privatized, see privateXObjectResources) resources too, so RemoveUnusedObjects' trailing sweep above actually reclaims the image object rather than leaving it graph-reachable with its pixel data still in the file. This closed as a side effect of the general-purpose resource-pruning pass neededXObjectNames already does for the unrelated pdf-go-w5hl Form-XObject fix: it computes which /XObject names the FINAL rewritten content still invokes via ANY Do operator — Image or Form alike, it draws no distinction — and prunes every other name, so a dropped Image Do is pruned exactly the same way a redirected Form XObject's now-stale original name is. The ticket had proposed a separate, image-specific fix; by the time it was picked up, the more general mechanism built for pdf-go-w5hl already covered it, confirmed by a direct forensic test (TestApplyRedactionsRemovesFullyCoveredImageBytes, redact_apply_image_leak_internal_test.go — an image whose raw JPEG bytes carry a marker, redacted, then checked byte-for-byte across every object in the saved file, same method pdf-go-2qkq's own regression test uses) and mutation-tested (temporarily disabling the pruning's delete call reproduces exactly the leak the ticket described).

Two more content paths this method's rewriters never reached are now closed too (pdf-go-xp2u). First, every OTHER annotation's own /AP appearance stream(s) overlapping a redaction region are now redacted into (redactAnnotationAppearances, redact_apply_annot.go) — a FreeText note's drawn text, a Stamp's drawn content, and critically a form Widget's /AP rendering of its OWN FIELD VALUE (a text field showing an SSN, say) all draw through their own appearance stream, completely outside this method's page-content rewriters, and used to survive a covering redaction untouched both visually and forensically. Reuses the Form-XObject redaction machinery from pdf-go-w5hl almost verbatim: an annotation's /AP/N (or /D, /R) stream IS a Form XObject, placed by a fixed ISO 32000-1 §12.5.5 algorithm instead of a content-stream `cm`+`Do`, and that algorithm's own matrix composes with the stream's /Matrix exactly the way a Do's CTM does — so redactFormXObject and formPlacementBbox apply unchanged, this just supplies a different "ctm". Same clone-not-mutate discipline as redactFormDo: nothing here ever mutates an annotation's /AP dict or an appearance stream object in place, since either can in principle be shared across annotations or states. Second, an inline image (BI...ID...EI) fully or partially inside a region is now dropped/clipped the same way a non-Form Do is (emitClassifiedImageOp, redact_apply_image.go) — it used to fall through to the rewriter's default case and pass through completely unexamined, the same class of leak as pdf-go-ye1z's XObject-image case but for pixel data that was never a separate XObject to begin with. A tiling pattern whose every fill was redacted away is now dropped from the page's /Resources/Pattern (pdf-go-ifik, closed; prunePagePatterns, redact_apply_pattern.go), so its cell content — which can hold text — no longer stays reachable in the saved file. A pattern still painted somewhere on the page is kept: its cell repeats the same content everywhere, so what a region clips away is also visible outside it. A pattern used only inside a Form XObject with its own /Resources is not pruned (that dict still names it). Type3 /CharProcs are deliberately left alone: a glyph procedure is shared by every occurrence of that glyph, the text rewriter already drops the Tj/TJ that would run it inside a region, and redacting "into" it would blank every other, legitimately-unredacted occurrence of the same character.

A Form XObject whose own content relies on a font inherited from the page (no Tf of its own, legal per ISO 32000-1 §8.10.1) can now actually be redacted (pdf-go-w7ye, closed): rewriteXObjectDoOperatorsInStream tracks the SAME text-state operators (Tf/Tc/Tw/Tz/TL, saved/restored by q/Q) the page-level text rewriter does, purely to capture the state in effect at each Do, and hands it to redactFormXObject as the form's own rewriter's starting point instead of zero/unknown — closing both the earlier silent-leak failure mode (before pdf-go-oq9i existed) and the later outright-refusal one (after it): a document using this unusual but legal construct is now redacted correctly instead of either leaking or failing outright. The inheritance chain is threaded through nested Form XObjects too, so a form two levels of Do deep continues to resolve correctly. Confirmed by direct reproduction, not just by reading the code — a prior draft of the regression test for this accidentally passed under more than one wrong fix, once because a MERELY PARTIAL redaction broke a secret string's contiguity just as effectively as a complete one for a plain substring-absence check, and once because two hand-picked test secrets happened to share a substring with each other; see redact_apply_inherited_font_internal_test.go's own comments for both.

A page's /Thumb thumbnail, if a producer embedded one, is now dropped (pdf-go-ekp4, closed) rather than left to go on possibly showing a miniature of the pre-redaction page — see this method's step 5a for why dropping rather than regenerating it.

A composite (Type0) font using a non-Identity, variable-width CJK CMap (predefined or embedded) now decodes glyph boundaries through the font's own CMap instead of assuming fixed 2-byte codes, closing a misdecode/mispositioning risk — and a width-lookup-by-raw-code bug that predated it — the same way the text extractor and renderer already did (`pdf-go-eys1`, closed; see `decodeCIDGlyphs`'s own doc comment, `redact_apply_text.go`). This also closes `pdf-go-ifpy`'s word-spacing point as a side effect: Tw now applies only to a single-byte code 32, never a multi-byte one resolving to CID 32, mirroring the extractor exactly. Its other two points are closed too: the renderer now takes `0 Tz` literally (zero-width glyphs) like the extractor and this rewriter, and the q/Q snapshots hold a shared *fontInfo instead of copying the whole font on every q.

The rest: redacting a document that is later saved incrementally (already signed, or AddValidationInfo) keeps the original text in the earlier, byte-preserved revision by design.

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

func (*Document) AttachInvoice added in v0.10.0

func (d *Document) AttachInvoice(xmlData []byte, opts ...InvoiceOptions) (*PDFAValidationReport, error)

AttachInvoice turns the document into a hybrid e-invoice (Factur-X 1.0 / ZUGFeRD 2.1+): it embeds the caller's CII XML as an associated file, writes the Factur-X XMP properties with the extension schema that declares them, and converts the document to PDF/A-3. Calling it again replaces the invoice. The returned report is the PDF/A result; conversion removes any encryption, as PDF/A requires. Mirrors the intent of Aspose.PDF for .NET's PdfFormat.ZUGFeRD conversion.

func (*Document) Booklet added in v0.4.0

func (d *Document) Booklet(opts BookletOptions) (*Document, error)

Booklet returns a new Document that imposes this document's pages two-up, reordered for saddle-stitch binding: print double-sided, fold the stack in half, and the pages read in order. The page count is padded up to a multiple of four with blank halves. The receiver is not modified.

Like NUp, this is a production helper (not an ISO 32000 feature) producing an ordinary PDF; it mirrors the intent of Aspose.PDF for .NET's PdfFileEditor.MakeBooklet, adapted to this library's Document API.

func (*Document) ChangePassword added in v0.4.0

func (d *Document) ChangePassword(newUserPassword, newOwnerPassword string) error

ChangePassword re-encrypts the document with new passwords on the next Save, keeping the current encryption algorithm and permissions. The document must already be open and decrypted (via OpenWithPassword / OpenStreamWithPassword) — the password that unlocked it is the "old" password. If newOwnerPassword is empty it defaults to newUserPassword. Returns an error if the document is not encrypted; to encrypt a plaintext document use SetPassword / SetEncryption. Mirrors Aspose.PDF for .NET's Document.ChangePasswords.

Example:

doc, _ := asposepdf.OpenWithPassword("locked.pdf", "old")
doc.ChangePassword("new", "")
doc.Save("locked.pdf")

func (*Document) ClearInfo added in v0.3.0

func (d *Document) ClearInfo()

ClearInfo removes the Info dictionary entirely.

func (*Document) ClearPageLabels added in v0.3.0

func (d *Document) ClearPageLabels()

ClearPageLabels removes the document's /PageLabels entry. (*Page).Label() then falls back to the decimal page number.

func (*Document) ClearXMP added in v0.3.0

func (d *Document) ClearXMP()

ClearXMP removes the /Catalog/Metadata entry. The underlying stream object becomes unreferenced; call RemoveUnusedObjects to reclaim it.

func (*Document) Collection added in v0.8.0

func (d *Document) Collection() *Collection

Collection returns the document's portfolio facade.

func (*Document) ConvertToGrayscale added in v0.4.0

func (d *Document) ConvertToGrayscale() error

ConvertToGrayscale converts the document to grayscale in place: every device colour set in a content stream (text, vector graphics), every raster image, shading and annotation colour is mapped to its luminance grey. The geometry, text and layout are untouched. Mirrors the intent of Aspose.PDF for .NET's grayscale conversion.

Coverage: DeviceRGB/DeviceGray/DeviceCMYK and ICCBased colours in content streams and via cs/sc/scn; RGB/CMYK/Indexed/ICCBased raster images (re-encoded as DeviceGray); axial/radial (type 2/3) shadings; and annotation /C, /IC and appearance streams — recursing through Form XObjects. Best-effort / left as-is (documented): Separation/DeviceN tints, Pattern fills, and type 0/4 shading functions, whose colours pass through unconverted.

func (*Document) ConvertToPDFA added in v0.4.0

func (d *Document) ConvertToPDFA(format PDFAFormat) (*PDFAValidationReport, error)

ConvertToPDFA adjusts the document toward a PDF/A "b"-level conformance profile and returns a validation report describing any violations that remain. It applies the structural and metadata fixes the library can make safely in place:

  • removes encryption;
  • removes JavaScript and Launch actions (document-level and per-annotation);
  • removes file attachments for PDF/A-1 (including a page-pinned FileAttachmentAnnotation, not just the document-level EmbeddedFiles tree);
  • rasterizes any page using transparency for PDF/A-1 (FlattenTransparency, which PDF/A-1 forbids outright; PDF/A-2 and -3 permit it and are left alone);
  • sets annotation flags (Print on, Hidden/NoView off);
  • embeds non-embedded simple fonts (Standard-14 and other single-byte Type1/TrueType) using the bundled metric-compatible substitutes;
  • adds an sRGB ICC OutputIntent (so device colours are colour-managed);
  • writes an XMP packet carrying the pdfaid identifier (synced from /Info).

Symbol and ZapfDingbats have no Latin substitute and remain a reported violation; composite (Type0/CJK) and Type3 fonts are not auto-fixed. The returned report lists any remaining issues; when Conformant is true the document satisfies the checks in ValidatePDFA. Mirrors the intent of Aspose.PDF for .NET's Document.Convert(PdfFormat).

The changes are applied to the in-memory document; call Save/WriteTo to write the converted file. An error return (from the transparency-flattening step, the only one that can fail) can leave the document partway converted — pages already rasterized before the failing one keep their new raster content, like ApplyRedactions' documented best-effort/partial-state-on-error behavior; re-running FlattenTransparency or ConvertToPDFA is safe (already vector-content pages that raise no error stay untouched, and an already rasterized page is a no-op the second time, per FlattenTransparency's own idempotence guarantee).

func (*Document) CreateForm added in v0.4.0

func (d *Document) CreateForm(width, height float64) *XForm

CreateForm creates an empty Form XObject of the given size (points). Draw its content through Canvas(), then place it on pages with Page.AddForm.

func (*Document) CreateTilingPattern added in v0.4.0

func (d *Document) CreateTilingPattern(width, height float64) *TilingPattern

CreateTilingPattern creates an empty tiling pattern whose cell is width×height points. Draw the cell through Canvas(), then fill shapes with it via ShapeStyle.FillTiling.

func (*Document) CreateType3Font added in v0.8.0

func (d *Document) CreateType3Font() *Type3Font

CreateType3Font returns an empty Type3 font bound to the document.

func (*Document) DeletePage added in v0.3.0

func (d *Document) DeletePage(n int) error

DeletePage removes the page at the given 1-based number. Mirrors Aspose.PDF for .NET's Document.Pages.Delete(int).

Example:

err = doc.DeletePage(2) // drop the second page

func (*Document) DeletePages added in v0.3.0

func (d *Document) DeletePages(pageNums ...int) error

DeletePages removes the pages at the given 1-based page numbers. Repeated numbers are de-duplicated and argument order does not matter; the surviving pages keep their relative order. Every number is validated before any page is removed, so on error the document is left unchanged. Mirrors Aspose.PDF for .NET's Document.Pages.Delete(int[]).

A document must keep at least one page: a call that would remove every page returns an error and changes nothing. Passing no page numbers is an error (unlike .NET's parameterless Pages.Delete(), which clears all pages — that would leave an unusable zero-page document).

Removed pages no longer appear in the document or in saved output. The underlying objects are not eagerly reclaimed (matching Reorder); they fall out of the written page tree and can be garbage-collected by the writer's reachability pass.

Example:

err = doc.DeletePages(1, 3) // drop the first and third pages

func (*Document) EmbeddedFiles added in v0.4.0

func (d *Document) EmbeddedFiles() *EmbeddedFiles

EmbeddedFiles returns the document-level embedded-file collection.

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

Extract selected page ranges into a new document.

package main

import (
	"fmt"
	"log"

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

func main() {
	doc, err := pdf.Open("testdata/4pages.pdf")
	if err != nil {
		log.Fatal(err)
	}
	out, err := doc.Extract(
		pdf.PageRange{From: 1, To: 2},
		pdf.PageRange{From: 4, To: 4},
	)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("extracted:", out.PageCount(), "pages")
}
Output:
extracted: 3 pages

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(opts ...TextExtractOptions) ([]string, error)

ExtractText returns the text content of each page (one entry per page, 0-indexed). An optional TextExtractOptions selects the extraction mode.

Example

Extract text from every page in visual reading order.

package main

import (
	"fmt"
	"log"
	"strings"

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

func main() {
	doc, err := pdf.Open("testdata/Hello world.pdf")
	if err != nil {
		log.Fatal(err)
	}
	pages, err := doc.ExtractText()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(strings.TrimSpace(pages[0]))
}
Output:
Hello, world!

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) FiguresNeedingAltText added in v0.6.0

func (d *Document) FiguresNeedingAltText() ([]*FigureAlt, error)

FiguresNeedingAltText walks the document's logical structure tree and returns every /Figure element that lacks alternate text (/Alt or /ActualText), each paired with the image it brackets when that image can be located. Returns nil for an untagged document. Mirrors the discovery half of Aspose.PDF for .NET's accessibility tooling; the description side lives in the ai subpackage (ImageDescriptionCopilot.FillAltTexts).

func (*Document) Flatten added in v0.3.0

func (d *Document) Flatten() error

Flatten bakes the document's interactive form fields into static page content and removes the AcroForm, so the result renders identically but is no longer fillable. Equivalent to (*Document).Form().Flatten().

Mirrors Aspose.PDF for .NET's Document.Flatten (which flattens form fields). Annotations are not affected here — flatten those via a page's AnnotationCollection.Flatten or an individual Annotation.Flatten.

func (*Document) FlattenTransparency added in v0.10.0

func (d *Document) FlattenTransparency(opts ...FlattenTransparencyOptions) (int, error)

FlattenTransparency rasterizes every page that uses transparency into a single opaque full-page image, leaving pages without transparency untouched. Returns the number of pages rasterized. A flattened page's old content-stream and resource objects (the very transparency constructs this method exists to remove) become unreachable; when at least one page was flattened, FlattenTransparency also calls RemoveUnusedObjects so those orphans are actually gone from the file — otherwise ValidatePDFA's TRANSPARENCY check, which scans every object rather than only reachable ones, would still trip on them.

Example

Rasterize only the pages that actually use transparency (here, a semi-transparent fill), leaving every other page fully vector.

package main

import (
	"fmt"
	"log"

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

func main() {
	doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
	page, _ := doc.Page(1)
	fill := pdf.Color{R: 1, G: 0, B: 0, A: 0.5}
	if err := page.DrawRectangle(pdf.Rectangle{LLX: 50, LLY: 700, URX: 300, URY: 780},
		pdf.ShapeStyle{FillColor: &fill}); err != nil {
		log.Fatal(err)
	}

	n, err := doc.FlattenTransparency()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("pages flattened:", n)
}
Output:
pages flattened: 1

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) GenerateTOC added in v0.4.0

func (d *Document) GenerateTOC(opts ...TOCOptions) (int, error)

GenerateTOC builds a table of contents from the document's outline (bookmark) tree and inserts it as new page(s) at the front of the document. Outline nesting becomes the indent level. Returns the number of pages added (0 when the document has no outline entries).

Page numbers and GoTo links reflect the final page order after the TOC pages are inserted. Mirrors Aspose.PDF for .NET's TocInfo-driven TOC generation, sourced from the document outline.

Example

Generate a table of contents from the document outline. The TOC is inserted as new page(s) at the front; entries link to their targets.

package main

import (
	"fmt"
	"log"

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

func main() {
	doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
	doc.AddBlankPageFromFormat(pdf.PageFormatA4)
	body, _ := doc.Page(1)

	chapter := pdf.NewOutlineItemCollection(doc)
	chapter.SetTitle("Chapter 1")
	chapter.SetDestination(pdf.NewDestinationFit(body))
	if err := doc.Outlines().Add(chapter); err != nil {
		log.Fatal(err)
	}

	added, err := doc.GenerateTOC(pdf.TOCOptions{Title: "Table of Contents"})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("TOC pages added:", added, "| total pages:", doc.PageCount())
}
Output:
TOC pages added: 1 | total pages: 3

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) ImportForm added in v0.4.0

func (d *Document) ImportForm(form *XForm) (*XForm, error)

ImportForm copies a Form XObject (and its whole resource graph: fonts, images, nested forms, …) from another document into this one, returning a new XForm ready to place with Page.AddForm. A form already belonging to this document is returned unchanged.

func (*Document) Info added in v0.3.0

func (d *Document) Info() (DocumentInfo, error)

Info returns the Info-dictionary metadata from this document. Mirrors Aspose.PDF for .NET's Document.Info; the XMP store is XMP().

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) Invoice added in v0.10.0

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

Invoice returns the e-invoice embedded in the document, or (nil, nil) when the document is not one. It reads Factur-X 1.0 / ZUGFeRD 2.1+, ZUGFeRD 2.0 and ZUGFeRD 1.0 files: the attachment is found by the name the XMP gives, else by the names the standards use.

func (*Document) JavaScript added in v0.4.0

func (d *Document) JavaScript() *JavaScriptCollection

JavaScript returns the document-level JavaScript collection. Always non-nil. Mirrors Aspose.PDF for .NET's Document.JavaScript.

func (*Document) Layers added in v0.4.0

func (d *Document) Layers() []*Layer

Layers returns the document's layers (OCGs), in /OCProperties/OCGs order. Empty for a document with no optional content.

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) LoadFontByName added in v0.4.0

func (d *Document) LoadFontByName(family string, bold, italic bool) (Font, error)

LoadFontByName resolves a font by family name (with an optional bold / italic style) through the FontRepository — the folders and files registered with AddFontFolder / AddFontFile first, then the operating system's font directories — embeds the matched face into the document, and returns a Font usable in TextStyle.Font. It is the by-name counterpart to LoadFont(path): callers that know a family ("Calibri", "Verdana", "Arial" bold) need not locate the file themselves. A sub-font of a .ttc collection is re-wrapped as a standalone sfnt before embedding. Standard-14 family names resolve to their installed metric-equivalents (Helvetica → Arial, Times → Times New Roman, …); for a non-embedded Standard-14 font use the package-level vars (FontHelvetica, …) instead. Returns an error if no matching font is registered or installed. Mirrors the intent of Aspose.PDF for .NET's FontRepository.FindFont.

func (*Document) LoadFontFromStream

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

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

func (*Document) LoadSVG added in v0.2.0

func (d *Document) LoadSVG(path string) (*SVG, error)

LoadSVG reads and parses an SVG file once, returning a *SVG that can be passed to Page.AddSVGObject or Document.AddSVGObjectWatermark multiple times without re-parsing.

func (*Document) LoadSVGFromStream added in v0.2.0

func (d *Document) LoadSVGFromStream(r io.Reader) (*SVG, error)

LoadSVGFromStream is the io.Reader variant of LoadSVG.

func (*Document) NUp added in v0.4.0

func (d *Document) NUp(opts NUpOptions) (*Document, error)

NUp returns a new Document that imposes this document's pages onto larger sheets in a Rows×Cols grid (e.g. 2×2 for 4-up). Each source page is wrapped in a Form XObject and scaled to fit its cell, preserving aspect ratio and centered. Sheets are filled until every page is placed; the last sheet may have empty cells. The receiver is not modified.

This is a page-production helper (not an ISO 32000 feature); the output is an ordinary, spec-compliant PDF. It mirrors the intent of Aspose.PDF for .NET's PdfFileEditor.MakeNUp, adapted to this library's Document API.

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) NeedsRepair added in v0.10.0

func (d *Document) NeedsRepair() bool

NeedsRepair reports whether the document was recovered rather than read as written. Saving it writes a clean file, so this is the moment to warn a user that the input was damaged.

func (*Document) NewFlow added in v0.4.0

func (d *Document) NewFlow(opts FlowOptions) *Flow

NewFlow creates a flow that renders into the document d.

Example

Generate a paginated document with the flow layout: headings, paragraphs and tables are laid out top-to-bottom with automatic page breaks.

package main

import (
	"fmt"
	"log"

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

func main() {
	doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
	flow := doc.NewFlow(pdf.FlowOptions{})
	flow.AddHeading(1, "Quarterly Report", pdf.TextStyle{})
	flow.AddParagraph("Revenue grew in every region this quarter.", pdf.TextStyle{Size: 11})
	flow.AddList([]string{"North: +12%", "South: +8%"}, false, pdf.TextStyle{Size: 11})

	pages, err := flow.Render()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("pages:", pages)
}
Output:
pages: 1

func (*Document) OpenAction added in v0.4.0

func (d *Document) OpenAction() Action

OpenAction returns the action the viewer runs when the document is opened (/Catalog/OpenAction per ISO 32000-1 §12.3.2 / §12.6.1), or nil when none is set. A GoTo open-action has its destination page resolved to a 1-based PageNum. When /OpenAction is a bare destination array (a "go to page on open" without an explicit action dict) this returns nil — read the destination via NamedDestinations / the page tree instead.

Mirrors Aspose.PDF for .NET's Document.OpenAction.

func (*Document) Optimize added in v0.6.0

Optimize reduces the document's size in place per opts and returns a report of what changed. Call before Save/WriteTo. Mirrors Aspose.PDF for .NET's Document.OptimizeResources(OptimizationOptions).

Order: remove unused objects (a pre-pass, see below) → images → fonts (unembed, then subset what's left embedded) → compress streams → dedupe streams → remove unused objects again (so anything a transform orphans is reclaimed last). RemovedObjects reports the sum of both passes.

The pre-pass was added because every (*Page).AddText call (and every table cell) used to replace a page's /Contents with a brand-new stream object holding the whole concatenated content, leaving the old one dead in d.objects with nothing referencing it any more — on a page built from many small AddText calls this meant many dead copies piling up, which RemoveDuplicateStreams and CompressStreams would otherwise both walk and hash/compress for nothing before the final pass cleared them away; on a 20-page, 200-calls-per-page document this made Optimize ~25x slower for no change in the end result. Reported with a clear reproduction and a correct diagnosis by Kare-ino (GitHub issue #9) — thank you. That root cause is now closed at the source (appendToContentStream/prependToContentStream, content_append.go, pdf-go-jbiu/GitHub issue #16: an append now adds one array entry to /Contents instead of rewriting a combined stream, so nothing is ever abandoned), so a document built with the current code produces no such copies in the first place — TestOptimizeManyAddTextCallsStaysFast still pins the speed guarantee itself, now trivially satisfied rather than needing the pre-pass's help. The pre-pass is kept anyway as cheap, harmless insurance against OTHER sources of dead objects this method doesn't know about: a third-party file opened with its own pre-existing orphaned content, or this library's own full-content-replace call sites (ApplyRedactions, ConvertToGrayscale, ImageInfo.Remove, FlattenTransparency — all via replacePageContents or an equivalent, which still swap in one new stream and abandon whatever /Contents pointed at before). Running the same removal once at the very start changes nothing about which objects survive Optimize overall, only when the already-dead ones are noticed, since nothing later in this method can make a genuinely unreachable object reachable again.

Example

Shrink a document with the unified lossless optimizer (unused objects, font subsetting, stream compression, duplicate-stream dedup).

package main

import (
	"fmt"
	"log"

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

func main() {
	doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
	font, err := doc.LoadFont("testdata/DejaVuSans.ttf")
	if err != nil {
		log.Fatal(err)
	}
	page, _ := doc.Page(1)
	_ = page.AddText("Привет, мир!", pdf.TextStyle{Font: font, Size: 18},
		pdf.Rectangle{LLX: 50, LLY: 700, URX: 545, URY: 780})

	res, err := doc.Optimize(pdf.DefaultOptimizationOptions())
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("fonts subset:", res.SubsettedFonts)
}
Output:
fonts subset: 1

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.

Example

Build a bookmark (outline) tree with clickable destinations.

package main

import (
	"fmt"
	"log"

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

func main() {
	doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
	page, _ := doc.Page(1)

	item := pdf.NewOutlineItemCollection(doc)
	item.SetTitle("Chapter 1")
	item.SetDestination(pdf.NewDestinationFit(page))
	if err := doc.Outlines().Add(item); err != nil {
		log.Fatal(err)
	}

	fmt.Println(doc.Outlines().Count(), doc.Outlines().At(0).Title())
}
Output:
1 Chapter 1

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) Paragraphs added in v0.4.0

func (d *Document) Paragraphs() ([]PageMarkup, error)

Paragraphs returns the structured text of every page.

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) RemoveOpenAction added in v0.4.0

func (d *Document) RemoveOpenAction()

RemoveOpenAction clears any /Catalog/OpenAction. Equivalent to SetOpenAction(nil).

func (*Document) RemoveUnusedObjects

func (d *Document) RemoveUnusedObjects() int

RemoveUnusedObjects removes objects from the document that are not reachable from any page or from the document catalog (/Root). The catalog is a GC root in its own right — /Metadata, /OutputIntents, /AcroForm, /StructTreeRoot, /Names and similar catalog-only-referenced content is never dropped just because no page happens to reference it too. Returns the number of objects removed.

func (*Document) RenderImage added in v0.3.0

func (d *Document) RenderImage(pageNum int, opts RenderOptions) (image.Image, error)

RenderImage renders the 1-based page number to an image.

Example

Render a page to a raster image with the built-in dependency-free renderer.

package main

import (
	"fmt"
	"log"

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

func main() {
	doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
	page, _ := doc.Page(1)
	_ = page.AddText("Preview me", pdf.TextStyle{Size: 24},
		pdf.Rectangle{LLX: 50, LLY: 700, URX: 545, URY: 780})

	img, err := doc.RenderImage(1, pdf.RenderOptions{DPI: 96})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("rendered:", img.Bounds().Dx() > 0 && img.Bounds().Dy() > 0)
}
Output:
rendered: true

func (*Document) RenderTIFF added in v0.3.0

func (d *Document) RenderTIFF(w io.Writer, opts RenderOptions, pageNums ...int) error

RenderTIFF renders the document to a single multi-page TIFF written to w. With no pageNums every page is rendered in order; otherwise just the listed 1-based pages, in the given order. Pages are rendered one at a time, so peak memory is a single page image. Mirrors Aspose.PDF for .NET's TiffDevice whole-document output.

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) RepairReport added in v0.10.0

func (d *Document) RepairReport() RepairReport

RepairReport returns what had to be reconstructed to open the document. Mirrors the intent of Aspose.PDF for .NET's Document.IsRepairNeeded, which reports the same condition through an out parameter.

func (*Document) ReplaceText added in v0.4.0

func (d *Document) ReplaceText(old, replacement string, opts ...ReplaceOptions) (int, error)

ReplaceText replaces every occurrence of old with replacement across all pages, returning the total number of replacements. See (*Page).ReplaceText for the replacement strategy and limitations.

Example

Find and replace every occurrence of a string across the document.

package main

import (
	"fmt"
	"log"

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

func main() {
	doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
	page, _ := doc.Page(1)
	_ = page.AddText("Draft version. Draft only.",
		pdf.TextStyle{Size: 14}, pdf.Rectangle{LLX: 50, LLY: 700, URX: 545, URY: 780})

	n, err := doc.ReplaceText("Draft", "Final")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("replaced:", n)
}
Output:
replaced: 2

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
Example

Rotate selected pages by 90 degrees clockwise. Subsequent calls accumulate.

package main

import (
	"fmt"
	"log"

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

func main() {
	doc, err := pdf.Open("testdata/4pages.pdf")
	if err != nil {
		log.Fatal(err)
	}
	if err := doc.Rotate(pdf.Rotate90, 1, 3); err != nil {
		log.Fatal(err)
	}
	p1, _ := doc.Page(1)
	p2, _ := doc.Page(2)
	fmt.Println("page1:", p1.Rotation(), "page2:", p2.Rotation())
}
Output:
page1: 90 page2: 0

func (*Document) Sanitize added in v0.11.0

Sanitize removes hidden data per opts and returns a report of what changed. Mirrors the intent of Aspose.PDF for .NET's Aspose.Pdf.Security.HiddenDataSanitization.HiddenDataSanitizer + HiddenDataSanitizationOptions, composed here over this library's existing primitives (ClearInfo/ClearXMP, EmbeddedFiles, JavaScript/action stripping, ApplyRedactions, annotation deletion, Document.Flatten, optional-content removal, page rasterization, OptimizeImages) rather than new mechanics.

Order: metadata -> attachments -> scripts/actions -> search index and private data -> flatten forms -> flatten layers -> apply redactions and remove annotations -> rasterize pages (or recompress existing images). Rasterization runs last, after every other step has already narrowed what there is to rasterize, matching Aspose's own ordering note. RemoveUnusedObjects runs once at the end when anything was removed, reclaiming whatever the steps above orphaned (OCG dictionaries, filespecs, action objects, …).

On error, res still reports whatever an earlier step already completed in this call, including a step that failed partway through (e.g. ConvertPagesToImages: res.PagesRasterized counts the pages already rasterized in place before the failing one) — mirroring FlattenTransparency's own partial-progress-on-error convention.

func (*Document) Save

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

Save writes the document to outputPath.

func (*Document) SaveDocx added in v0.7.0

func (d *Document) SaveDocx(path string, opts ...DocSaveOptions) error

SaveDocx writes the document as a Word (.docx) file.

func (*Document) SaveEpub added in v0.7.0

func (d *Document) SaveEpub(path string, opts ...EpubSaveOptions) error

SaveEpub writes the document as an EPUB file.

func (*Document) SaveHTML added in v0.5.0

func (d *Document) SaveHTML(outputPath string, opts ...HTMLSaveOptions) error

SaveHTML writes the document as an HTML file — self-contained by default; with ResourceDir/ResourceWriter the heavy parts become external files, and with SplitPages each page becomes its own <stem>_p<N>.html.

func (*Document) SaveLinearized added in v0.4.0

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

SaveLinearized writes the document to outputPath as a linearized ("fast web view") PDF (ISO 32000-1 Annex F): the first page's objects and a hint table sit at the front so a viewer can render page 1 before the whole file has downloaded. The result is an ordinary PDF that any reader opens normally. Encryption and signing are not supported together with linearization. Mirrors the intent of Aspose.PDF for .NET's linearized save.

func (*Document) SaveMarkdown added in v0.7.0

func (d *Document) SaveMarkdown(path string, opts ...MarkdownSaveOptions) error

SaveMarkdown writes the document as a Markdown file. Images go to opts.ImageDir (default "<stem>_files") unless EmbedImages/NoImages or an ImageWriter says otherwise. Mirrors the shape of SaveHTML.

func (*Document) SaveSVG added in v0.7.0

func (d *Document) SaveSVG(path string, opts ...SVGSaveOptions) error

SaveSVG exports the document's pages as SVG files. A single selected page is written to path itself; several pages become sibling files "<stem>_pN.svg" (N = the source page number), like the HTML exporter's SplitPages. Mirrors Aspose.PDF for .NET's Document.Save(SaveFormat.Svg).

func (*Document) SaveXlsx added in v0.8.0

func (d *Document) SaveXlsx(path string, opts ...XlsxSaveOptions) error

SaveXlsx writes the document as an Excel (.xlsx) workbook file.

func (*Document) SearchText added in v0.3.0

func (d *Document) SearchText(query string, opts ...SearchOptions) ([]TextMatch, error)

SearchText finds every occurrence of query across all pages of the document, returning matches page by page in reading order. Each TextMatch carries the page it was found on. See (*Page).SearchText for matching semantics.

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

Encrypt a document with AES-128 and a user password.

package main

import (
	"bytes"
	"fmt"
	"log"

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

func main() {
	doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
	doc.SetEncryption(pdf.EncryptionOptions{
		UserPassword:  "secret",
		OwnerPassword: "owner-secret",
		Permissions:   &pdf.Permissions{AllowPrint: true, AllowCopy: true},
		Algorithm:     pdf.EncryptionAlgAES128,
	})

	var buf bytes.Buffer
	if _, err := doc.WriteTo(&buf); err != nil {
		log.Fatal(err)
	}

	// The file is now encrypted; Open returns ErrEncrypted.
	if _, err := pdf.OpenStream(&buf); err != nil {
		fmt.Println("encrypted")
	}
}
Output:
encrypted

func (*Document) SetInfo added in v0.3.0

func (d *Document) SetInfo(info DocumentInfo)

SetInfo replaces the document's Info dictionary with the given metadata. Empty string fields are omitted. This is a full replacement. Mirrors assigning Aspose.PDF for .NET's Document.Info.

func (*Document) SetOpenAction added in v0.4.0

func (d *Document) SetOpenAction(act Action)

SetOpenAction sets the action run when the document opens. A nil action clears /OpenAction. A GoTo action is bound to this document so its destination is written as a proper page reference.

Mirrors Aspose.PDF for .NET's Document.OpenAction setter.

func (*Document) SetPageLabels added in v0.3.0

func (d *Document) SetPageLabels(ranges []PageLabelRange) error

SetPageLabels installs the document's /PageLabels number tree so PDF viewers display labels like "i, ii, 1, 2, …" in the navigation pane and page indicators. (*Page).Label() also reads from this tree.

Ranges must be sorted by StartPage in strictly ascending order and the first range must begin at page 1; otherwise an error is returned. Passing a nil/empty slice clears any existing labels.

Per PDF spec §12.4.2, /PageLabels is a number tree keyed by 0-based page index. This implementation emits a single-leaf number tree with one /Nums array, which is valid for any number of ranges.

Example

Author logical page labels (front matter i, ii, then body 1, 2, …).

package main

import (
	"fmt"
	"log"

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

func main() {
	doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
	_ = doc.AddBlankPageFromFormat(pdf.PageFormatA4)
	_ = doc.AddBlankPageFromFormat(pdf.PageFormatA4)

	err := doc.SetPageLabels([]pdf.PageLabelRange{
		{StartPage: 1, Style: pdf.PageLabelRomanLower},
		{StartPage: 3, Style: pdf.PageLabelDecimal},
	})
	if err != nil {
		log.Fatal(err)
	}
	p2, _ := doc.Page(2)
	p3, _ := doc.Page(3)
	fmt.Println(p2.Label(), p3.Label())
}
Output:
ii 1

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) SetSVGFontResolver added in v0.2.0

func (d *Document) SetSVGFontResolver(fn SVGFontResolver)

SetSVGFontResolver installs a custom resolver. The renderer queries it first for each SVG font-family encountered; on nil return, falls back to the heuristic. Use this to plug in embedded TTF fonts (Cyrillic, etc.) loaded via Document.LoadFont.

Pass nil to clear a previously-set resolver (revert to heuristic-only).

func (*Document) SetXMP added in v0.3.0

func (d *Document) SetXMP(meta XMPMetadata) error

SetXMP serialises meta into a standard XMP packet and stores it as the /Catalog/Metadata stream (uncompressed, /Type /Metadata /Subtype /XML per ISO 32000-1 §14.3.2). Replaces any existing packet. Passing an empty XMPMetadata writes an empty (but valid) packet; use ClearXMP to remove metadata entirely.

func (*Document) SetXMPRaw added in v0.3.0

func (d *Document) SetXMPRaw(data []byte) error

SetXMPRaw stores data verbatim as the /Catalog/Metadata stream — an escape hatch for callers that produce their own XMP packet. The bytes are written uncompressed so external tools can locate the xpacket markers. Reuses the existing Metadata object if present.

func (*Document) Sign added in v0.4.0

func (d *Document) Sign(opts SignOptions) error

Sign configures a digital signature applied on the next Save/WriteTo. Mirrors the intent of Aspose.PDF for .NET's PdfFileSignature.Sign, adapted to this library's options paradigm. Returns an error for a missing certificate or key.

Example

Sign a document with an ECDSA key and verify the signature. Certificates are ordinarily loaded from a key store; here one is generated in memory.

package main

import (
	"bytes"
	"crypto/ecdsa"
	"crypto/elliptic"

	cryptorand "crypto/rand"
	"crypto/x509"
	"crypto/x509/pkix"
	"fmt"
	"log"
	"math/big"
	"time"

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

func main() {
	key, _ := ecdsa.GenerateKey(elliptic.P256(), cryptorand.Reader)
	tmpl := &x509.Certificate{
		SerialNumber: big.NewInt(1),
		Subject:      pkix.Name{CommonName: "Jane Signer"},
		NotBefore:    time.Now().Add(-time.Hour),
		NotAfter:     time.Now().Add(24 * time.Hour),
		KeyUsage:     x509.KeyUsageDigitalSignature,
	}
	der, _ := x509.CreateCertificate(cryptorand.Reader, tmpl, tmpl, &key.PublicKey, key)
	cert, _ := x509.ParseCertificate(der)

	doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
	if err := doc.Sign(pdf.SignOptions{Certificate: cert, PrivateKey: key, Reason: "Approval"}); err != nil {
		log.Fatal(err)
	}
	var buf bytes.Buffer
	if _, err := doc.WriteTo(&buf); err != nil {
		log.Fatal(err)
	}

	signed, _ := pdf.OpenStream(&buf)
	sigs, err := signed.VerifySignatures()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("signatures: %d, valid: %v, reason: %s\n", len(sigs), sigs[0].Valid, sigs[0].Reason)
}
Output:
signatures: 1, valid: true, reason: Approval

func (*Document) SignatureNames added in v0.10.0

func (d *Document) SignatureNames() []string

SignatureNames returns the field name of every signature in the document, in document order. Mirrors Aspose.PDF for .NET's PdfFileSignature.GetSignatureNames.

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

Split a multi-page document into single-page documents.

package main

import (
	"fmt"
	"log"

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

func main() {
	doc, err := pdf.Open("testdata/4pages.pdf")
	if err != nil {
		log.Fatal(err)
	}
	parts, err := doc.Split()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("parts:", len(parts))
}
Output:
parts: 4

func (*Document) SubsetFonts added in v0.3.0

func (d *Document) SubsetFonts() (int, error)

SubsetFonts shrinks every embedded TTF (loaded via LoadFont) to only the glyphs actually drawn, replacing each /FontFile2 with a rebuilt subset program and switching the CIDFont's /CIDToGIDMap from /Identity to a stream that maps the original glyph IDs (still used verbatim as CIDs in content streams) to the compact subset glyph IDs. /W and /ToUnicode are also trimmed to the used glyphs.

Call this once, AFTER all text has been added and just before Save / WriteTo: adding more text that introduces new glyphs after subsetting would reference glyphs the subset no longer contains. Fonts with no drawn glyphs are skipped. Returns the number of fonts subsetted.

Typical reduction is from ~300-700 KB per embedded font down to a few KB, since only the used outlines survive. Mirrors the post-processing shape of (*Document).OptimizeImages.

func (*Document) SyncInfoToXMP added in v0.3.0

func (d *Document) SyncInfoToXMP() error

SyncInfoToXMP builds an XMP packet from the document's current /Info dictionary and installs it, so the two metadata stores agree (ISO 32000-1 §14.3.2 recommends consistency when both are present). Info Title/Author/Subject/Keywords/Creator/Producer/dates map to the corresponding XMP properties. No-op-safe when /Info is absent.

func (*Document) TaggedContent added in v0.4.0

func (d *Document) TaggedContent() *TaggedContent

TaggedContent returns the document's tagged-content facade, creating the structure tree and the /MarkInfo, /ViewerPreferences and /StructTreeRoot catalog entries on first call. Idempotent.

func (*Document) UnembedFonts added in v0.10.0

func (d *Document) UnembedFonts() (int, error)

UnembedFonts drops the embedded font program from every simple font whose name and metrics are those of a Helvetica/Times/Courier Standard-14 face (see unembedFonts for the full eligibility rule), then reclaims the now-orphaned font-program stream objects. Call before Save/WriteTo. Returns the number of fonts unembedded. Mirrors Aspose.PDF for .NET's OptimizationOptions.UnembedFonts (phase 2 of the Optimize epic, pdf-go-o0wy/pdf-go-vb4b) — opt-in (not part of DefaultOptimizationOptions) since, unlike SubsetFonts, it can change how the document actually looks in a viewer that substitutes a different Arial/Times/Courier clone.

func (*Document) ValidatePDFA added in v0.4.0

func (d *Document) ValidatePDFA(format PDFAFormat) *PDFAValidationReport

ValidatePDFA checks the document against a PDF/A "b"-level conformance profile and returns a report of violations. It is a read-only diagnostic — it never mutates the document; use ConvertToPDFA to produce a conformant file.

Checks performed (ISO 19005-1/2/3, basic level): an XMP metadata packet with a matching pdfaid:part/conformance; every font embedded (no Standard-14 reliance); no encryption; no JavaScript or Launch actions; an ICC OutputIntent when device colours are used; no transparency for PDF/A-1; annotation flags (Print set, Hidden/NoView clear) and appearance streams; an uncompressed /Metadata stream; no LZWDecode (PDF/A-1); and no embedded files for PDF/A-1.

Scope: the "a" (tagged/accessible) levels are not validated. This mirrors the intent of Aspose.PDF for .NET's Document.Validate(PdfFormat) but returns a structured report instead of writing an XML log.

func (*Document) ValidatePDFUA added in v0.4.0

func (d *Document) ValidatePDFUA() *PDFUAValidationReport

ValidatePDFUA checks the document against a subset of PDF/UA-1 (ISO 14289-1, universal accessibility) and returns a report of violations. It is a read-only diagnostic — it never mutates the document.

Checks performed: the document is marked as Tagged PDF (/MarkInfo /Marked) and carries a logical structure tree (/StructTreeRoot with kids and a /ParentTree); a natural-language default (/Lang); a document title (in /Info or XMP) that is shown rather than the file name (/ViewerPreferences /DisplayDocTitle); every /Figure (and /Formula) structure element has alternate text (/Alt or /ActualText); and accessibility is not blocked by encryption permissions.

Scope: this validates the structural prerequisites of PDF/UA. It does not verify full reading-order correctness, heading nesting, table-cell scoping or that every content item is tagged — those need deeper semantic analysis (and a real validator such as PAC or veraPDF for final sign-off). Mirrors the intent of Aspose.PDF for .NET's Document.Validate(PdfFormat.PDF_UA_1).

func (*Document) ValidateRedactions

func (d *Document) ValidateRedactions() error

ValidateRedactions performs a pre-flight dry-run check on every page that has at least one RedactAnnotation: its content stream must parse, and every Form XObject a redaction region intersects must be one ApplyRedactions can safely redact into — a resolvable /BBox, an invertible placement matrix, and nesting/work within maxFormRedactDepth/maxFormRedactWork (see unsafeFormXObjectName; most intersecting Form XObjects ARE safely redactable since pdf-go-w5hl — this only flags the genuinely unsafe cases). Also checks every non-/Redact annotation's own /AP appearance stream(s) overlapping a region the same way (unsafeAnnotationAppearance; pdf-go-xp2u) — an annotation's placement matrix is always invertible by construction (it comes from ISO 32000-1 §12.5.5's scale+translate algorithm, not an arbitrary `cm`), so only a missing/malformed /BBox can make one unsafe here. Returns the first problem found, or nil if every redact-bearing page is safe to process. Pages without redact annotations are not inspected.

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

func (*Document) VerifySignature added in v0.10.0

func (d *Document) VerifySignature(fieldName string, opts ...ValidationOptions) (SignatureVerification, error)

VerifySignature verifies the one signature held by the named field. The error reports a missing field or missing source bytes; a signature that is present but invalid comes back in the result, with the reason in Err — there is nothing exceptional about a document failing to verify. Mirrors Aspose.PDF for .NET's PdfFileSignature.VerifySignature(sigName).

func (*Document) VerifySignatures added in v0.4.0

func (d *Document) VerifySignatures(opts ...ValidationOptions) ([]SignatureVerification, error)

VerifySignatures verifies every digital signature in the document and returns one result per signature field, in document order. The document must have been opened from a file or stream (the raw bytes are needed to resolve each /ByteRange). Trust-chain validation is left to the caller — Certificate is returned so it can be checked against a trust store.

Mirrors the intent of Aspose.PDF for .NET's PdfFileSignature.VerifySignature.

func (*Document) WriteDocx added in v0.7.0

func (d *Document) WriteDocx(w io.Writer, opts ...DocSaveOptions) error

WriteDocx writes the document as a Word (.docx) package to w.

func (*Document) WriteEpub added in v0.7.0

func (d *Document) WriteEpub(w io.Writer, opts ...EpubSaveOptions) error

WriteEpub writes the document as an EPUB 3 package to w.

func (*Document) WriteHTML added in v0.5.0

func (d *Document) WriteHTML(w io.Writer, opts ...HTMLSaveOptions) error

WriteHTML writes the document as a single self-contained HTML file to w: per page, a raster background under a text layer (transparent in HTMLModeFaithful, visible in HTMLModeText) and link-annotation overlays.

Example

Export the document as self-contained HTML with a selectable text layer.

package main

import (
	"bytes"
	"fmt"
	"log"

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

func main() {
	doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
	page, _ := doc.Page(1)
	_ = page.AddText("Hello HTML", pdf.TextStyle{Size: 18},
		pdf.Rectangle{LLX: 50, LLY: 700, URX: 545, URY: 780})

	var html bytes.Buffer
	if err := doc.WriteHTML(&html, pdf.HTMLSaveOptions{Mode: pdf.HTMLModeText}); err != nil {
		log.Fatal(err)
	}
	fmt.Println("has text spans:", bytes.Contains(html.Bytes(), []byte("<span")))
}
Output:
has text spans: true

func (*Document) WriteMarkdown added in v0.7.0

func (d *Document) WriteMarkdown(w io.Writer, opts ...MarkdownSaveOptions) error

WriteMarkdown writes the document as Markdown to w. Without an ImageWriter and with EmbedImages unset, images are skipped (a stream has no natural place for files).

Example

Export a document as GFM Markdown (the reverse of the Markdown renderer).

package main

import (
	"fmt"
	"log"
	"strings"

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

func main() {
	doc, err := pdf.MarkdownToDocumentFromStream(strings.NewReader("# Title\n\nBody text.\n"))
	if err != nil {
		log.Fatal(err)
	}
	var out strings.Builder
	if err := doc.WriteMarkdown(&out); err != nil {
		log.Fatal(err)
	}
	fmt.Println(strings.Split(out.String(), "\n")[0])
}
Output:
# Title

func (*Document) WriteTo

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

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

func (*Document) WriteToLinearized added in v0.4.0

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

WriteToLinearized writes the document as a linearized PDF to w (implements an io.WriterTo-style contract). See SaveLinearized.

func (*Document) WriteXlsx added in v0.8.0

func (d *Document) WriteXlsx(w io.Writer, opts ...XlsxSaveOptions) error

WriteXlsx writes the document as an Excel (.xlsx) workbook to w.

func (*Document) XMP added in v0.3.0

func (d *Document) XMP() (XMPMetadata, error)

XMP returns the document's XMP metadata parsed from the /Catalog/Metadata stream. Returns a zero XMPMetadata (IsEmpty) when the document has no XMP packet. Parse errors in a malformed packet are returned; recognised properties parsed before the error are discarded.

func (*Document) XMPRaw added in v0.3.0

func (d *Document) XMPRaw() ([]byte, error)

XMPRaw returns the raw bytes of the XMP packet from /Catalog/Metadata, or nil when the document has no XMP stream.

type DocumentInfo added in v0.3.0

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

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

Mirrors Aspose.PDF for .NET's DocumentInfo (Document.Info). Note the cross-API naming: in Aspose.PDF for .NET, Document.Info is this Info dictionary while Document.Metadata is the XMP store — which here is (*Document).XMP, not this type.

type EditOperationsOrder added in v0.9.0

type EditOperationsOrder int

EditOperationsOrder decides how the two halves of a replacement are ordered. Mirrors Aspose.PDF for .NET's EditOperationsOrder.

const (
	// EditOperationsDeleteFirst reports the removed text before the added
	// text. This is the zero value.
	EditOperationsDeleteFirst EditOperationsOrder = iota
	// EditOperationsInsertFirst reports the added text first. This only
	// reorders the delete/insert pair at their adjacent junction: a
	// replacement split across a page boundary (the deletion on one page,
	// the insertion on the next) is not reordered and comes out interleaved.
	EditOperationsInsertFirst
)

type EmbeddedFile added in v0.4.0

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

EmbeddedFile is one attachment: a /Filespec dictionary with an embedded stream. Read its metadata and content, or set its description.

func (*EmbeddedFile) AFRelationship added in v0.10.0

func (f *EmbeddedFile) AFRelationship() AFRelationship

AFRelationship reports how the file relates to the document; a file with no /AFRelationship reports AFUnspecified.

func (*EmbeddedFile) CollectionItem added in v0.8.0

func (f *EmbeddedFile) CollectionItem() *CollectionItem

CollectionItem returns the attachment's portfolio field values.

func (*EmbeddedFile) Data added in v0.4.0

func (f *EmbeddedFile) Data() ([]byte, error)

Data returns the attachment's decoded content bytes.

func (*EmbeddedFile) Description added in v0.4.0

func (f *EmbeddedFile) Description() string

Description returns the /Filespec /Desc text, or "" if none.

func (*EmbeddedFile) MIMEType added in v0.4.0

func (f *EmbeddedFile) MIMEType() string

MIMEType returns the embedded stream's /Subtype as a MIME type (e.g. "application/pdf"), or "" if absent.

func (*EmbeddedFile) Name added in v0.4.0

func (f *EmbeddedFile) Name() string

Name returns the attachment's name (its name-tree key).

func (*EmbeddedFile) Save added in v0.4.0

func (f *EmbeddedFile) Save(path string) error

Save writes the attachment's content to a file.

func (*EmbeddedFile) SetAFRelationship added in v0.10.0

func (f *EmbeddedFile) SetAFRelationship(r AFRelationship)

SetAFRelationship records how the file relates to the document and lists it in the catalog's /AF array — both of which PDF/A-3 requires of every embedded file.

func (*EmbeddedFile) SetDescription added in v0.4.0

func (f *EmbeddedFile) SetDescription(s string)

SetDescription sets (or, for "", removes) the /Filespec /Desc text.

func (*EmbeddedFile) Size added in v0.4.0

func (f *EmbeddedFile) Size() int

Size returns the attachment's size in bytes (0 if no content).

func (*EmbeddedFile) WriteTo added in v0.4.0

func (f *EmbeddedFile) WriteTo(w io.Writer) (int64, error)

WriteTo writes the attachment's content to w (implements io.WriterTo).

type EmbeddedFiles added in v0.4.0

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

EmbeddedFiles is the document's collection of attached (embedded) files — the /Catalog/Names/EmbeddedFiles name tree (ISO 32000-1 §7.11.4). Each entry is a /Filespec whose /EF points at an /EmbeddedFile stream, letting a PDF carry arbitrary companion files (source code, datasets, the original of a scan). Always non-nil; a document with no attachments yields an empty collection. Mirrors Aspose.PDF for .NET's Document.EmbeddedFiles.

This is the document-level counterpart to FileAttachmentAnnotation (a file pinned to a page); both share the same /EmbeddedFile + /Filespec machinery.

func (*EmbeddedFiles) Add added in v0.4.0

func (e *EmbeddedFiles) Add(path string) (*EmbeddedFile, error)

Add embeds the file at path under its base name, detecting the MIME type from its extension, and returns the new attachment. An existing attachment with the same name is replaced.

func (*EmbeddedFiles) AddFromStream added in v0.4.0

func (e *EmbeddedFiles) AddFromStream(name string, r io.Reader) (*EmbeddedFile, error)

AddFromStream embeds the bytes read from r under the given name (the MIME type is detected from the name's extension), and returns the new attachment.

func (*EmbeddedFiles) All added in v0.4.0

func (e *EmbeddedFiles) All() []*EmbeddedFile

All returns every attachment, in sorted-name order.

func (*EmbeddedFiles) Clear added in v0.4.0

func (e *EmbeddedFiles) Clear()

Clear removes every attachment.

func (*EmbeddedFiles) Count added in v0.4.0

func (e *EmbeddedFiles) Count() int

Count returns the number of embedded files.

func (*EmbeddedFiles) Get added in v0.4.0

func (e *EmbeddedFiles) Get(name string) *EmbeddedFile

Get returns the named attachment, or nil if absent.

func (*EmbeddedFiles) Has added in v0.4.0

func (e *EmbeddedFiles) Has(name string) bool

Has reports whether an attachment with the given name exists.

func (*EmbeddedFiles) Names added in v0.4.0

func (e *EmbeddedFiles) Names() []string

Names returns the attachment names (name-tree keys), lexicographically sorted.

func (*EmbeddedFiles) Remove added in v0.4.0

func (e *EmbeddedFiles) Remove(name string) bool

Remove deletes the named attachment, returning whether it existed. The orphaned objects are reclaimed by RemoveUnusedObjects.

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

	// EncryptionAlgRC4_40 — RC4-40, the original Standard Security Handler
	// V=1 R=2. Present for interoperability with old readers and archives
	// that only understand it; a 40-bit key is breakable by brute force in
	// minutes, so never choose it to protect anything.
	EncryptionAlgRC4_40
)

type EncryptionOptions

type EncryptionOptions struct {
	UserPassword  string
	OwnerPassword string
	Permissions   *Permissions
	Algorithm     EncryptionAlgorithm
	// Recipients switches to the public-key security handler
	// (/Filter /Adobe.PubSec): the document is encrypted for these
	// certificates and opens with OpenWithCertificate instead of a
	// password. The password fields are ignored when it is non-empty, and
	// a recipient's own Permissions override the document-wide ones.
	Recipients []Recipient
}

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 EpubSaveOptions added in v0.7.0

type EpubSaveOptions struct {
	// Pages is a 1-based subset (in the given order); nil = all pages.
	Pages []int
	// Title sets dc:title; empty falls back to the Info title, then "Document".
	Title string
	// NoImages skips images (raster, vector patches and inline icons alike).
	NoImages bool
}

EpubSaveOptions configures SaveEpub / WriteEpub. The zero value exports all pages with images, titled from the document's /Info.

type Field

type Field interface {
	PartialName() string
	FullName() string
	Value() string
	SetValue(s string) error
	IsReadOnly() bool
	IsRequired() bool
	PageIndex() int
	Rect() Rectangle
	// SetStyle applies visual styling (colours, border, font, alignment)
	// and regenerates the widget appearance. Style reads it back.
	SetStyle(s FieldStyle) error
	Style() FieldStyle
	// Flatten bakes this single field's appearance into its page content
	// and removes the field, leaving other fields and the /AcroForm intact.
	// See (*fieldBase).Flatten in flatten.go.
	Flatten() error
}

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

type FieldStyle added in v0.3.0

type FieldStyle struct {
	BorderColor     *Color      // /MK /BC — nil = no border colour set
	BackgroundColor *Color      // /MK /BG — nil = transparent/white default
	TextColor       *Color      // /DA fill colour — nil = black
	BorderWidth     float64     // /BS /W in points — 0 = hairline default
	BorderStyle     BorderStyle // /BS /S — BorderSolid (default), Dashed, Beveled, Inset, Underline
	DashPattern     []float64   // /BS /D — used only when BorderStyle == BorderDashed
	TextFont        Font        // /DA font — nil = Helvetica
	TextSize        float64     // /DA size in points — 0 = 12pt
	TextAlign       HAlign      // /Q — HAlignLeft (default), HAlignCenter, HAlignRight
}

FieldStyle is the visual styling applied to a form field's widget(s). A zero value means "leave at the library default" for every property: nil colour pointers, zero BorderWidth, BorderSolid, nil DashPattern, nil TextFont (→ Helvetica), zero TextSize (→ 12pt), HAlignLeft.

Styling is persisted into the PDF the way ISO 32000-1 specifies, so it round-trips and is also honoured by viewers that regenerate appearances:

  • BorderColor / BackgroundColor → /MK /BC, /MK /BG (§12.5.6.19)
  • BorderWidth / BorderStyle / DashPattern → /BS /W, /S, /D (§12.5.4)
  • TextFont / TextSize / TextColor → /DA default-appearance string (§12.7.3.3)
  • TextAlign → /Q quadding (0 left, 1 centre, 2 right)

Because the library also pre-generates the widget /AP appearance stream from these same values, a styled field renders identically across Acrobat, Foxit, browser PDF viewers, MuPDF, and Poppler.

type FigureAlt added in v0.6.0

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

FigureAlt is a /Figure structure element that has no alternate text, paired with the image it brackets (when resolvable). Set the text with SetAltText.

func (*FigureAlt) Image added in v0.6.0

func (f *FigureAlt) Image() (*Image, bool)

Image returns the figure's image and whether one was resolved. The image is decoded (Data holds PNG/JPEG bytes).

func (*FigureAlt) SetAltText added in v0.6.0

func (f *FigureAlt) SetAltText(alt string)

SetAltText sets the figure's /Alt (alternate text). Empty input is ignored.

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) AFRelationship added in v0.10.0

func (a *FileAttachmentAnnotation) AFRelationship() AFRelationship

AFRelationship reports how the attached file relates to the document; a file with no /AFRelationship (including an annotation with no attachment yet) reports AFUnspecified. Mirrors EmbeddedFile.AFRelationship.

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) Flatten added in v0.3.0

func (b *FileAttachmentAnnotation) Flatten() error

Flatten bakes this annotation's normal appearance (/AP/N, honoring the /AS state) into its page's content stream at the annotation's /Rect, then removes the annotation. The annotation handle is dangling afterwards.

An annotation with no normal appearance (e.g. a sticky-note Text annotation, which viewers render as an icon) is simply removed — nothing is drawn.

Mirrors Aspose.PDF for .NET's Annotation.Flatten. For form-field widgets prefer (*Form).Flatten, which also clears the /AcroForm entry.

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) SetAFRelationship added in v0.10.0

func (a *FileAttachmentAnnotation) SetAFRelationship(r AFRelationship)

SetAFRelationship records how the attached file relates to the document and lists its file specification in the catalog's /AF array — both of which PDF/A-3 requires of every embedded file (ISO 19005-3 §6.8), and a page-pinned FileAttachmentAnnotation's filespec is otherwise invisible to that rule (pdfaCheckAssociatedFiles only walked the document-level EmbeddedFiles name tree before pdf-go-tdx5). A no-op if the annotation has no attached file yet — call it after SetFile/SetFileFromStream.

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 FileDiffOutputGenerator added in v0.10.0

type FileDiffOutputGenerator interface {
	SaveOutput(path string, ops []DiffOperation) error
	SaveOutputPages(path string, pages [][]DiffOperation) error
	WriteOutput(w io.Writer, ops []DiffOperation) error
	WriteOutputPages(w io.Writer, pages [][]DiffOperation) error
}

FileDiffOutputGenerator writes comparison output to a file or writer. Mirrors Aspose.PDF for .NET's IFileOutputGenerator; the io.Writer variants are this library's addition, following the SaveXxx/WriteXxx convention used throughout the package.

type FileSelectBoxField added in v0.4.0

type FileSelectBoxField struct{ TextBoxField }

FileSelectBoxField is a text field whose value is a file path (FileSelect flag), used to attach a local file on submit.

func (*FileSelectBoxField) Flatten added in v0.4.0

func (b *FileSelectBoxField) Flatten() error

Flatten bakes this single field's appearance (each of its widgets) into the owning page content and removes the field, leaving every other field and the /AcroForm dict intact. Mirrors Aspose.PDF for .NET's Field.Flatten.

After Flatten the field handle is dangling and must not be used.

func (*FileSelectBoxField) FullName added in v0.4.0

func (b *FileSelectBoxField) FullName() string

func (*FileSelectBoxField) IsReadOnly added in v0.4.0

func (b *FileSelectBoxField) IsReadOnly() bool

func (*FileSelectBoxField) IsRequired added in v0.4.0

func (b *FileSelectBoxField) IsRequired() bool

func (*FileSelectBoxField) PageIndex added in v0.4.0

func (b *FileSelectBoxField) PageIndex() int

func (*FileSelectBoxField) PartialName added in v0.4.0

func (b *FileSelectBoxField) PartialName() string

func (*FileSelectBoxField) Rect added in v0.4.0

func (b *FileSelectBoxField) Rect() Rectangle

func (*FileSelectBoxField) SetStyle added in v0.4.0

func (b *FileSelectBoxField) SetStyle(s FieldStyle) error

SetStyle applies s to the field, writing /MK, /BS, /DA, and /Q on the field and its widgets and regenerating each widget's /AP appearance so the new look is visible immediately in every viewer. Returns an error only if the field is detached or a styled font cannot be registered.

func (*FileSelectBoxField) Style added in v0.4.0

func (b *FileSelectBoxField) Style() FieldStyle

Style reads back the field's current styling from /DA, /Q, /MK, and /BS. Properties never set return their zero/default value. The first widget is used for /MK and /BS.

type FlattenTransparencyOptions added in v0.10.0

type FlattenTransparencyOptions struct {
	DPI   float64 // dots per inch for the replacement raster; 0 -> DefaultDPI
	Pages []int   // 1-based page numbers to consider; empty -> every page
}

FlattenTransparencyOptions configures FlattenTransparency.

type FloatSide added in v0.4.0

type FloatSide int

FloatSide selects which edge a floated box hugs while text wraps around it.

const (
	// FloatLeft pins the box to the left of the column; text flows to its right.
	FloatLeft FloatSide = iota
	// FloatRight pins the box to the right of the column; text flows to its left.
	FloatRight
)

type FloatingBox added in v0.4.0

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

FloatingBox is a positioned content container (Tier 2 of the flow model): a box with an optional border, background and padding that lays its own content (paragraphs, headings, images, lists) inside its width. Place it absolutely on a page with (*Page).AddFloatingBox, or insert it into a flow with (*Flow).AddFloatingBox (where it takes its measured height). Mirrors the intent of Aspose.PDF for .NET's FloatingBox. Text flow-around and multi-column layout are not implemented (Tier 3).

func NewFloatingBox added in v0.4.0

func NewFloatingBox() *FloatingBox

NewFloatingBox creates an empty floating box.

func (*FloatingBox) AddHeading added in v0.4.0

func (b *FloatingBox) AddHeading(level int, text string, style TextStyle) *FloatingBox

AddHeading appends a heading (level 1–6) to the box.

func (*FloatingBox) AddImage added in v0.4.0

func (b *FloatingBox) AddImage(path string, width, height float64) *FloatingBox

AddImage appends an image (height ≤ 0 preserves aspect) to the box.

func (*FloatingBox) AddImageAlt added in v0.4.0

func (b *FloatingBox) AddImageAlt(path string, width, height float64, alt string) *FloatingBox

AddImageAlt appends an image with alternate text to the box.

func (*FloatingBox) AddList added in v0.4.0

func (b *FloatingBox) AddList(items []string, ordered bool, style TextStyle) *FloatingBox

AddList appends a bulleted/numbered list to the box.

func (*FloatingBox) AddParagraph added in v0.4.0

func (b *FloatingBox) AddParagraph(text string, style TextStyle) *FloatingBox

AddParagraph appends a paragraph to the box.

func (*FloatingBox) AddSpacer added in v0.4.0

func (b *FloatingBox) AddSpacer(height float64) *FloatingBox

AddSpacer appends vertical space to the box.

func (*FloatingBox) SetBackground added in v0.4.0

func (b *FloatingBox) SetBackground(c *Color) *FloatingBox

SetBackground sets the box fill colour (nil = none).

func (*FloatingBox) SetBorder added in v0.4.0

func (b *FloatingBox) SetBorder(border BorderInfo) *FloatingBox

SetBorder sets the box border.

func (*FloatingBox) SetPadding added in v0.4.0

func (b *FloatingBox) SetPadding(m MarginInfo) *FloatingBox

SetPadding sets the inner padding between the border and the content.

func (*FloatingBox) SetSpacing added in v0.4.0

func (b *FloatingBox) SetSpacing(gap float64) *FloatingBox

SetSpacing sets the vertical gap between the box's elements (default 6pt). Set it to 0 for a single-paragraph box so the content sits flush with the padding (and symmetric padding then centres it vertically).

type Flow added in v0.4.0

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

Flow is a document generator that lays content out top-to-bottom and paginates automatically — the "flow" counterpart to the Rectangle-based drawing API. Add paragraphs, headings, images, tables, lists and spacers, then Render lays them into the document, appending pages as needed and (optionally) tagging each element for accessibility. Mirrors the intent of Aspose.PDF for .NET's generator / Paragraphs flow model. Obtain one with (*Document).NewFlow.

func (*Flow) AddColumnBreak added in v0.4.0

func (f *Flow) AddColumnBreak() *Flow

AddColumnBreak forces the following content to start in the next column (or, from the last column, on the next page). A no-op in a single-column flow that is already at the top of a page.

func (*Flow) AddFloatBox added in v0.4.0

func (f *Flow) AddFloatBox(box *FloatingBox, side FloatSide, width float64) *Flow

AddFloatBox appends a floated box pinned to the given side at width points; the paragraphs that follow wrap around it until the text passes its bottom. Designed for single-column flows (in a multi-column flow the box floats within the current column).

func (*Flow) AddFloatingBox added in v0.4.0

func (f *Flow) AddFloatingBox(box *FloatingBox) *Flow

AddFloatingBox appends a floating box, which takes its measured height in the flow (moving to a new page if it does not fit).

func (*Flow) AddHeading added in v0.4.0

func (f *Flow) AddHeading(level int, text string, style TextStyle) *Flow

AddHeading appends a heading of the given level (1–6). Empty style fields get level-appropriate bold defaults.

func (*Flow) AddImage added in v0.4.0

func (f *Flow) AddImage(path string, width, height float64) *Flow

AddImage appends an image scaled to width×height points. If height <= 0 the image's aspect ratio is preserved.

func (*Flow) AddImageAlt added in v0.4.0

func (f *Flow) AddImageAlt(path string, width, height float64, alt string) *Flow

AddImageAlt is AddImage with alternate text (used when the flow is tagged).

func (*Flow) AddList added in v0.4.0

func (f *Flow) AddList(items []string, ordered bool, style TextStyle) *Flow

AddList appends a bulleted (ordered=false) or numbered list.

func (*Flow) AddMarkdown added in v0.6.0

func (f *Flow) AddMarkdown(md string) *Flow

AddMarkdown appends a Markdown fragment to the flow: its blocks become flow elements (headings, paragraphs, lists, tables, images, …) rendered with the flow's Markdown options.

func (*Flow) AddParagraph added in v0.4.0

func (f *Flow) AddParagraph(text string, style TextStyle) *Flow

AddParagraph appends a paragraph of flowing text (wraps and splits across pages).

func (*Flow) AddSpacer added in v0.4.0

func (f *Flow) AddSpacer(height float64) *Flow

AddSpacer appends vertical space.

func (*Flow) AddTable added in v0.4.0

func (f *Flow) AddTable(t *Table) *Flow

AddTable appends a table (paginated when taller than a page).

func (*Flow) Render added in v0.4.0

func (f *Flow) Render() (int, error)

Render lays out the queued elements into the document and returns the number of pages the flow occupies.

func (*Flow) SetMarkdownOptions added in v0.6.0

func (f *Flow) SetMarkdownOptions(o MarkdownOptions) *Flow

SetMarkdownOptions sets the theme/options used by subsequent AddMarkdown calls on this flow (fonts, base size, image base path).

type FlowOptions added in v0.4.0

type FlowOptions struct {
	Format                                           PageFormat     // zero → A4
	MarginLeft, MarginRight, MarginTop, MarginBottom float64        // zero → 54pt
	ParagraphSpacing                                 float64        // gap after each block; zero → 6pt
	Columns                                          int            // ≤1 → single column; >1 → multi-column flow
	ColumnGap                                        float64        // gap between columns; zero → 18pt
	Tagged                                           *TaggedContent // non-nil → auto-tag elements (Tagged PDF / PDF/UA)
}

FlowOptions configures a Flow. Zero values pick sensible defaults.

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 FontMetrics added in v0.13.0

type FontMetrics struct {
	// Ascent is the distance AddText subtracts from a rectangle's top
	// edge (or AddTextAt's caller would subtract from a desired top) to
	// place the baseline: rect.URY - Ascent. Always >= 0.
	Ascent float64
	// Descent is how far the font's descender reaches below the
	// baseline, as a negative value (0 if not tracked for this font —
	// see below). Mirrors the existing internal descent convention
	// (text.go) of a non-positive distance.
	Descent float64
}

FontMetrics holds the vertical metrics AddText/AddTextAt use for a font at a given size, in points. Mirrors Aspose.PDF for .NET's Font.MeasureString returning the same kind of layout metrics.

func GetFontMetrics added in v0.13.0

func GetFontMetrics(f Font, size float64) (FontMetrics, error)

GetFontMetrics returns the ascent/descent AddText/AddTextAt use for f at size, in points — the quantity a caller doing its own vertical positioning with AddTextAt would otherwise have to reverse-engineer from AddText's rect.URY - ascent*size placement formula. size 0 is treated as 12, matching AddText/AddTextAt/MeasureText.

Descent is only tracked for an embedded TrueType font (its real hhea descender); AddText's own placement never consults a descent value for the Standard-14/Type3 fallback (a fixed 0.8 em ascent, no separate descender), so none is fabricated here either — Descent comes back 0 for those.

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) AddBarcodeField added in v0.10.0

func (f *Form) AddBarcodeField(pageNum int, rect Rectangle, name string, symbology BarcodeSymbology, value string) (*BarcodeField, error)

AddBarcodeField adds a barcode field: value is the text encoded into the symbol (a URL or short text for QR/PDF417; printable ASCII for Code128), and symbology selects the encoding. Errors (without creating the field) if value cannot be encoded under symbology.

Example

Draw a QR code in place of text: the widget's value is the encoded text, so it reads/writes exactly like any other field.

package main

import (
	"fmt"
	"log"

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

func main() {
	doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
	form := doc.Form()
	field, err := form.AddBarcodeField(1, pdf.Rectangle{LLX: 50, LLY: 650, URX: 150, URY: 750},
		"sku", pdf.BarcodeQR, "https://example.com/sku/123")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(field.Symbology() == pdf.BarcodeQR, field.Value())
}
Output:
true https://example.com/sku/123

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) AddDateField added in v0.4.0

func (f *Form) AddDateField(pageNum int, rect Rectangle, name, format string) (*DateField, error)

AddDateField adds a date field with the given format mask (e.g. "mm/dd/yyyy"; empty defaults to "mm/dd/yyyy").

func (*Form) AddFileSelectField added in v0.4.0

func (f *Form) AddFileSelectField(pageNum int, rect Rectangle, name string) (*FileSelectBoxField, error)

AddFileSelectField adds a file-select text field.

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) AddNumberField added in v0.4.0

func (f *Form) AddNumberField(pageNum int, rect Rectangle, name string, opts NumberFormatOptions) (*NumberField, error)

AddNumberField adds a number field formatted per opts.

func (*Form) AddPasswordField added in v0.4.0

func (f *Form) AddPasswordField(pageNum int, rect Rectangle, name string) (*PasswordBoxField, error)

AddPasswordField adds a masked text field.

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) AddRichTextField added in v0.4.0

func (f *Form) AddRichTextField(pageNum int, rect Rectangle, name string) (*RichTextBoxField, error)

AddRichTextField adds a rich-text field.

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.

Example

Create a text form field, fill it, and read the value back.

package main

import (
	"fmt"
	"log"

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

func main() {
	doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
	form := doc.Form()
	field, err := form.AddTextField(1, pdf.Rectangle{LLX: 50, LLY: 700, URX: 300, URY: 725}, "customer")
	if err != nil {
		log.Fatal(err)
	}
	_ = field.SetValue("ACME Corp")

	fmt.Println(form.Field("customer").Value())
}
Output:
ACME Corp

func (*Form) ExportFDF added in v0.4.0

func (f *Form) ExportFDF() ([]byte, error)

ExportFDF serialises the form's field values as an FDF (Forms Data Format) document — a small PDF-syntax file (`%FDF-1.2` … `/FDF /Fields [ … ]`) that Acrobat and other readers import. Field names are written flat (the full name in each `/T`); push buttons are skipped. Mirrors Aspose.PDF for .NET's `Facades.Form.ExportFdf`.

func (*Form) ExportJSON added in v0.4.0

func (f *Form) ExportJSON(opts ...JSONExportOptions) ([]byte, error)

ExportJSON serialises the form's field values to a typed JSON document keyed by each field's full name: `{"name": {"type": "...", "value": ...}}`. The value's JSON kind follows the field type — text/radio/combobox → string, checkbox → bool, listbox → array of strings. Push buttons (which hold no value) are skipped. Keys are emitted in sorted order. Mirrors the intent of Aspose.PDF for .NET's `Document.Form.ExportToJson`.

func (*Form) ExportXFDF added in v0.4.0

func (f *Form) ExportXFDF() ([]byte, error)

ExportXFDF serialises the form's field values as an XFDF document. Field names are written flat (the full name in each `name` attribute); push buttons are skipped. Mirrors Aspose.PDF for .NET's `Facades.Form.ExportXfdf`.

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) Flatten added in v0.3.0

func (f *Form) Flatten() error

Flatten bakes every form field's current appearance into its page's content stream and then removes all fields, their widgets, and the /AcroForm dict, producing a non-interactive document that renders the same. A field whose widget has no normal appearance is removed without drawing.

Mirrors Aspose.PDF for .NET's Form.Flatten. After Flatten the Form is empty; previously returned Field handles are dangling and must not be used.

func (*Form) HasField

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

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

func (*Form) ImportFDF added in v0.4.0

func (f *Form) ImportFDF(data []byte) (int, error)

ImportFDF applies field values from an FDF document and returns the number of fields set. Names are matched by full name (FDF `/Kids` nesting is resolved to dotted names); unknown names and non-applying values are skipped. Mirrors Aspose.PDF for .NET's `Facades.Form.ImportFdf`.

func (*Form) ImportJSON added in v0.4.0

func (f *Form) ImportJSON(data []byte) (int, error)

ImportJSON applies field values from a typed JSON document (the shape ExportJSON produces) and returns the number of fields actually set. Each key is matched against the form by full name; unknown names and values that don't apply to their target field are skipped (not an error). Values are interpreted by the matching field's concrete type, so a checkbox accepts a bool or a boolean string and a listbox accepts an array or a single string. Setting a value regenerates the widget appearance, so imported values render in any viewer. Mirrors the intent of Aspose.PDF for .NET's `Document.Form.ImportFromJson`.

func (*Form) ImportXFDF added in v0.4.0

func (f *Form) ImportXFDF(data []byte) (int, error)

ImportXFDF applies field values from an XFDF document and returns the number of fields set. Names are matched by full name (nested `<field>` elements are resolved to dotted names); unknown names and non-applying values are skipped. Mirrors Aspose.PDF for .NET's `Facades.Form.ImportXfdf`.

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) ReadFDF added in v0.4.0

func (f *Form) ReadFDF(r io.Reader) (int, error)

ReadFDF reads an FDF document from r and applies it via ImportFDF.

func (*Form) ReadJSON added in v0.4.0

func (f *Form) ReadJSON(r io.Reader) (int, error)

ReadJSON reads a JSON document from r and applies it via ImportJSON.

func (*Form) ReadXFDF added in v0.4.0

func (f *Form) ReadXFDF(r io.Reader) (int, error)

ReadXFDF reads an XFDF document from r and applies it via ImportXFDF.

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. When set, viewers regenerate the /AP appearance stream on display instead of trusting the pre-generated one (which Acrobat treats as a document modification). The library auto-builds /AP for every field on creation and on every value mutation, so the default (false) is correct for nearly all cases; callers only need this for niche workflows where viewer-side regeneration is required.

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.

func (*Form) WriteFDF added in v0.4.0

func (f *Form) WriteFDF(w io.Writer) error

WriteFDF writes ExportFDF output to w.

func (*Form) WriteJSON added in v0.4.0

func (f *Form) WriteJSON(w io.Writer, opts ...JSONExportOptions) error

WriteJSON writes ExportJSON output to w.

func (*Form) WriteXFDF added in v0.4.0

func (f *Form) WriteXFDF(w io.Writer) error

WriteXFDF writes ExportXFDF output to w.

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
	FormFieldTypePassword
	FormFieldTypeFileSelect
	FormFieldTypeRichText
	FormFieldTypeNumber
	FormFieldTypeDate
	FormFieldTypeBarcode
)

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) Flatten added in v0.3.0

func (b *GenericAnnotation) Flatten() error

Flatten bakes this annotation's normal appearance (/AP/N, honoring the /AS state) into its page's content stream at the annotation's /Rect, then removes the annotation. The annotation handle is dangling afterwards.

An annotation with no normal appearance (e.g. a sticky-note Text annotation, which viewers render as an icon) is simply removed — nothing is drawn.

Mirrors Aspose.PDF for .NET's Annotation.Flatten. For form-field widgets prefer (*Form).Flatten, which also clears the /AcroForm entry.

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 GifDevice added in v0.3.0

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

GifDevice renders a page to GIF. Mirrors Aspose.PDF for .NET's GifDevice.

func NewGifDevice added in v0.3.0

func NewGifDevice(res Resolution) *GifDevice

NewGifDevice returns a GifDevice for the given resolution.

func (*GifDevice) Process added in v0.3.0

func (d *GifDevice) Process(page *Page, w io.Writer) error

Process renders page and writes it to w as GIF.

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 Gradient added in v0.3.0

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

Gradient is a fill that varies colour across a shape: either a LinearGradient or a RadialGradient. Assign one to ShapeStyle.FillGradient to fill a DrawRectangle / DrawRoundedRectangle / DrawCircle / DrawEllipse / DrawPolygon / DrawPath shape with it.

Coordinates are PDF user space (points; origin at the page bottom-left, Y up) — the same space as the shape being filled. Implemented as PDF axial (Type 2) and radial (Type 3) shading patterns. Limitations mirror the SVG renderer: the spread method is pad (the end colours extend past the gradient vector) and per-stop alpha is not rendered (shadings are opaque DeviceRGB).

type GradientStop added in v0.3.0

type GradientStop struct {
	Offset float64
	Color  Color
}

GradientStop is one colour stop in a gradient, positioned at Offset (0 at the gradient's start, 1 at its end). Stops should be supplied in ascending Offset order.

type GraphicalPdfComparer added in v0.10.0

type GraphicalPdfComparer struct {
	// Threshold is the per-pixel colour-distance percentage (0-100) below
	// which a difference is ignored — a way to ignore small changes (JPEG
	// recompression noise, anti-aliasing). The zero value compares exactly.
	// Mirrors GraphicalPdfComparer.Threshold.
	Threshold float64
	// Color marks differing pixels in the default DifferenceToImage call and
	// in CompareDocumentsToPdf/ComparePagesToImage output. The zero value is
	// red. Mirrors GraphicalPdfComparer.Color.
	Color Color
	// Resolution is the DPI both pages are rasterized at before comparing.
	// The zero value is 150 DPI. Mirrors GraphicalPdfComparer.Resolution.
	Resolution Resolution
}

GraphicalPdfComparer compares PDF pages/documents pixel by pixel. Mirrors Aspose.PDF for .NET's GraphicalPdfComparer. Construct with NewGraphicalPdfComparer, or use the zero value (equivalent defaults).

func NewGraphicalPdfComparer added in v0.10.0

func NewGraphicalPdfComparer() *GraphicalPdfComparer

NewGraphicalPdfComparer returns a comparer with Aspose's defaults: exact comparison, red highlight, 150 DPI.

func (*GraphicalPdfComparer) CompareDocumentsToPdf added in v0.10.0

func (c *GraphicalPdfComparer) CompareDocumentsToPdf(doc1, doc2 *Document, outputPath string) error

CompareDocumentsToPdf compares every page pair by index (mirroring CompareDocumentsPageByPage's pairing; the longer document's tail pages are compared against a blank white page of the same size, so a page added or removed reports whatever fraction of it isn't blank/white as different, rather than erroring — a page that is itself mostly white reports a correspondingly small ratio despite being a genuine page-count change) and writes a new PDF with one page per pair: the difference image full-page, captioned with the changed-pixel ratio. Mirrors GraphicalPdfComparer.CompareDocumentsToPdf.

func (*GraphicalPdfComparer) ComparePagesToImage added in v0.10.0

func (c *GraphicalPdfComparer) ComparePagesToImage(page1, page2 *Page, path string) error

ComparePagesToImage renders the two pages' difference (DifferenceToImage with this comparer's Color as foreground, white as background) and saves it as a PNG. Mirrors GraphicalPdfComparer.ComparePagesToImage.

func (*GraphicalPdfComparer) GetDifference added in v0.10.0

func (c *GraphicalPdfComparer) GetDifference(page1, page2 *Page) (*ImagesDifference, error)

GetDifference rasterizes both pages at Resolution and compares them pixel by pixel. Mirrors GraphicalPdfComparer.GetDifference.

func (*GraphicalPdfComparer) WriteDocumentsToPdf added in v0.10.0

func (c *GraphicalPdfComparer) WriteDocumentsToPdf(doc1, doc2 *Document, w io.Writer) error

WriteDocumentsToPdf is the io.Writer variant of CompareDocumentsToPdf.

func (*GraphicalPdfComparer) WritePagesToImage added in v0.10.0

func (c *GraphicalPdfComparer) WritePagesToImage(page1, page2 *Page, w io.Writer) error

WritePagesToImage is the io.Writer variant of ComparePagesToImage (PNG).

type HAlign

type HAlign int

HAlign specifies horizontal text alignment within a rectangle.

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

type HTMLDiffOutputGenerator added in v0.10.0

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

HTMLDiffOutputGenerator renders comparison differences as an HTML fragment — colored spans for insertions/deletions, meant to be embedded into the caller's own page or email, not a standalone document. Mirrors Aspose.PDF for .NET's HtmlDiffOutputGenerator.

func NewHTMLDiffOutputGenerator added in v0.10.0

func NewHTMLDiffOutputGenerator(opts ...DiffOutputStyle) *HTMLDiffOutputGenerator

NewHTMLDiffOutputGenerator creates a generator with the given style (last one wins); the zero value uses DiffOutputStyle's defaults.

func (*HTMLDiffOutputGenerator) GenerateOutput added in v0.10.0

func (g *HTMLDiffOutputGenerator) GenerateOutput(ops []DiffOperation) (string, error)

GenerateOutput renders ops as one HTML fragment, operations joined by a single space (matching AssembleSourceText/AssembleDestinationText). Equal text is emitted plain unless DiffOutputStyle.EqualColor/EqualBackground is set.

func (*HTMLDiffOutputGenerator) GenerateOutputPages added in v0.10.0

func (g *HTMLDiffOutputGenerator) GenerateOutputPages(pages [][]DiffOperation) (string, error)

GenerateOutputPages renders one <div class="cmp-page"> section per page, each headed by "Page N".

func (*HTMLDiffOutputGenerator) SaveOutput added in v0.10.0

func (g *HTMLDiffOutputGenerator) SaveOutput(path string, ops []DiffOperation) error

SaveOutput writes GenerateOutput's fragment to path.

func (*HTMLDiffOutputGenerator) SaveOutputPages added in v0.10.0

func (g *HTMLDiffOutputGenerator) SaveOutputPages(path string, pages [][]DiffOperation) error

SaveOutputPages writes GenerateOutputPages's fragment to path.

func (*HTMLDiffOutputGenerator) WriteOutput added in v0.10.0

func (g *HTMLDiffOutputGenerator) WriteOutput(w io.Writer, ops []DiffOperation) error

WriteOutput writes GenerateOutput's fragment to w.

func (*HTMLDiffOutputGenerator) WriteOutputPages added in v0.10.0

func (g *HTMLDiffOutputGenerator) WriteOutputPages(w io.Writer, pages [][]DiffOperation) error

WriteOutputPages writes GenerateOutputPages's fragment to w.

type HTMLMode added in v0.5.0

type HTMLMode int

HTMLMode selects how SaveHTML / WriteHTML represents page text.

const (
	// HTMLModeFaithful (default) renders each page fully as a raster image
	// under a transparent selectable text layer — pixel-identical to
	// RenderPNG by construction.
	HTMLModeFaithful HTMLMode = iota
	// HTMLModeText renders the page background without glyphs and draws the
	// text as visible HTML spans (real colour/size/style, width-fitted to
	// the PDF layout) — crisp at any zoom, accessible, smaller output.
	HTMLModeText
	// HTMLModeNative drops the raster background entirely: page graphics
	// become one inline SVG layer per page (true-curve paths, native
	// strokes, clips, images with JPEG passthrough, blend modes), with
	// per-element raster patches only for content SVG cannot express
	// (shadings, patterns, soft masks, transparency groups). Text is the
	// same visible span layer as HTMLModeText (WOFF fonts included).
	HTMLModeNative
	// HTMLModeFlow produces reflowable HTML instead of positioned page
	// replicas: paragraphs and columns (from the Paragraphs() extractor)
	// become real <p>/<h1>-<h3> elements in reading order in a responsive
	// centered column, images flow between them. Position-based features
	// (link overlays, interactive forms) and DPI do not apply; tables and
	// vector graphics are not reconstructed — their text flows as
	// paragraphs. Mirrors Aspose.PDF for .NET's FixedLayout=false.
	HTMLModeFlow
)

type HTMLSaveOptions added in v0.5.0

type HTMLSaveOptions struct {
	// DPI is the raster resolution of the page backgrounds (0 → 144, crisp on
	// high-density screens since pages display at their natural point size).
	DPI float64
	// Title overrides the HTML <title> (default: the document's Info title,
	// else "Document").
	Title string
	// Mode selects faithful (default) or visible-text page representation.
	Mode HTMLMode
	// Pages selects which pages to export as 1-based numbers, in the given
	// order (repeats allowed). Empty exports every page. Page anchors keep
	// their source numbers, so cross-page links stay stable in a subset.
	Pages []int
	// NoFontEmbedding disables the WOFF @font-face embedding of the
	// document's fonts in HTMLModeText (spans then always use the metric
	// substitutes + width fitting). No effect in faithful mode.
	NoFontEmbedding bool
	// InteractiveForms converts AcroForm fields into real, fillable HTML
	// controls (inputs, textareas, selects) positioned over the page, and
	// removes their widget appearances from the background render. Text,
	// checkbox, radio, combo and list fields convert; push buttons and
	// signatures keep their static look. The form can be filled in and
	// printed in a browser without JavaScript; writing values back into
	// the PDF is out of scope. HTMLModeText / HTMLModeNative only.
	InteractiveForms bool
	// ResourceWriter externalizes the heavy binary parts — page background
	// rasters, WOFF fonts, images and raster patches: it is called with a
	// unique file name and the content and returns the URL to write into
	// the HTML. nil keeps everything inlined as base64 data: URLs (the
	// default single self-contained file). Mirrors the intent of Aspose
	// .PDF for .NET's CustomResourceSavingStrategy / PartsEmbeddingMode.
	ResourceWriter func(name string, data []byte) (url string, err error)
	// ResourceDir (SaveHTML only) is the convenience form of
	// ResourceWriter: resources are written as files into this directory
	// (created on demand, relative to the output HTML) and referenced by
	// relative URL. Ignored when ResourceWriter is set. Mirrors Aspose's
	// SpecialFolderForAllImages.
	ResourceDir string
	// SplitPages (SaveHTML only) writes one HTML document per exported
	// page as <stem>_p<N>.html instead of one big file; in-document links
	// point across the files. Mirrors Aspose's SplitIntoPages.
	SplitPages bool
	// OutlineNav adds a fixed sidebar built from the document outline
	// (bookmark) tree, linking to the page anchors — collapsible with pure
	// HTML, no JavaScript. No-op for documents without outlines and in
	// HTMLModeFlow (which has no page anchors).
	OutlineNav bool
	// contains filtered or unexported fields
}

HTMLSaveOptions configures SaveHTML / WriteHTML. The zero value exports all pages in faithful mode at 144 DPI with the document title taken from the Info dictionary.

type HiddenDataSanitizationOptions added in v0.11.0

type HiddenDataSanitizationOptions struct {
	// RemoveMetadata clears the /Info dictionary and the XMP packet.
	RemoveMetadata bool
	// RemoveAttachments drops every embedded file, document-level and
	// page-pinned.
	RemoveAttachments bool
	// RemoveJavaScriptsAndActions strips document-level and per-annotation
	// JavaScript and Launch actions.
	RemoveJavaScriptsAndActions bool
	// RemoveAnnotations applies any pending redactions (ApplyRedactions)
	// and then removes every remaining annotation from every page, except
	// form-field widgets: those are FlattenForms's job (deleting a widget
	// without also removing its field from /AcroForm/Fields would leave a
	// dangling reference). Set FlattenForms too to also clear forms.
	RemoveAnnotations bool
	// RemoveSearchIndexAndPrivateInfo removes /PieceInfo private
	// application data (a known privacy leak: Illustrator/InDesign's "PDF
	// compatibility" mode keeps the original editable artwork here even
	// in an otherwise-flattened PDF) from the catalog and every page, and
	// drops any embedded file named like an Acrobat Catalog full-text
	// search index (a *.pdx attachment). Best-effort: Aspose does not
	// document this option's exact scope, so this is a defensible
	// narrower reading, not a byte-for-byte mirror.
	RemoveSearchIndexAndPrivateInfo bool
	// FlattenForms bakes every form field's current appearance into page
	// content and removes the AcroForm (Document.Flatten).
	FlattenForms bool
	// FlattenLayers removes the optional-content (layer) configuration
	// and every layer-scoped resource reference, so content that used to
	// be conditionally hidden under a layer is unconditionally visible
	// and the layer dictionaries (including their /Name) become
	// unreachable. Limitation: only checks each page's own
	// /Resources/Properties, not a nested Form XObject's.
	FlattenLayers bool
	// ConvertPagesToImages replaces every page's content with a single
	// rasterized image at ImageDPI, discarding whatever vector/text
	// content survived every option above as a last line of defense. It
	// does not touch annotations (a sticky note's /Contents, an
	// attachment's bytes, an annotation's own /AA JavaScript) — combine
	// with RemoveAnnotations/RemoveAttachments/RemoveJavaScriptsAndActions
	// if those must go too. Runs after every other option. When set,
	// ImageCompressionOptions is ignored.
	ConvertPagesToImages bool
	// ImageDPI is the resolution used by ConvertPagesToImages; 0 -> 150.
	ImageDPI float64
	// ImageCompressionOptions, used only when ConvertPagesToImages is
	// false, recompresses the document's existing images in place.
	ImageCompressionOptions *ImageCompressionOptions
}

HiddenDataSanitizationOptions configures (*Document).Sanitize. Mirrors Aspose.PDF for .NET's Aspose.Pdf.Security.HiddenDataSanitization. HiddenDataSanitizationOptions; this library composes it as a Document method (like Optimize/ConvertToPDFA/FlattenTransparency) rather than a separate executor object, since every operation the .NET HiddenDataSanitizer class performs already exists here as a primitive this type composes.

func AllHiddenDataSanitizationOptions added in v0.11.0

func AllHiddenDataSanitizationOptions() HiddenDataSanitizationOptions

AllHiddenDataSanitizationOptions returns every removal and flattening option enabled, leaving page rasterization and image compression off — either can noticeably change how the document looks, so the caller opts into ConvertPagesToImages/ImageDPI or ImageCompressionOptions separately. Mirrors Aspose.PDF for .NET's static HiddenDataSanitizationOptions.All().

type HiddenDataSanitizationResult added in v0.11.0

type HiddenDataSanitizationResult struct {
	MetadataRemoved    bool
	AttachmentsRemoved int
	ActionsRemoved     bool
	PrivateInfoRemoved int
	FormsFlattened     bool
	LayersRemoved      int
	RedactionsApplied  bool
	AnnotationsRemoved int
	PagesRasterized    int
	ImagesOptimized    int
}

HiddenDataSanitizationResult reports what Sanitize changed.

func SanitizeAllToImages added in v0.11.0

func SanitizeAllToImages(doc *Document, dpi float64) (HiddenDataSanitizationResult, error)

SanitizeAllToImages rasterizes every page of doc at dpi (0 -> 150) after removing every other kind of hidden data first. Mirrors Aspose.PDF for .NET's static HiddenDataSanitizer.SanitizeAllToImages.

type HighlightAnnotation

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

HighlightAnnotation marks a region with a semi-transparent highlight colour, washed over the text the quads cover.

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

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

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

func (*HighlightAnnotation) RegenerateAppearance added in v0.9.0

func (a *HighlightAnnotation) RegenerateAppearance()

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

func (*HighlightAnnotation) SetColor

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

SetColor writes /C and redraws the appearance in the new colour.

func (*HighlightAnnotation) SetQuadPoints

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

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

func (*HighlightAnnotation) SetRect

func (m *HighlightAnnotation) SetRect(r Rectangle)

SetRect moves the annotation and redraws its appearance, whose coordinates are relative to the rectangle.

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 ImageCompressionOptions added in v0.11.0

type ImageCompressionOptions struct {
	// ResizeImages downscales images above MaxResolution DPI. Leaving
	// MaxResolution at its zero value together with ResizeImages true is
	// rejected by Sanitize (it would otherwise silently downscale nothing).
	ResizeImages bool
	// MaxResolution is the DPI ceiling used when ResizeImages is set.
	MaxResolution float64
	// CompressImages converts opaque PNG images to JPEG.
	CompressImages bool
}

ImageCompressionOptions configures the lossy recompression Sanitize applies to a document's existing images when ConvertPagesToImages is not set. Mirrors Aspose.PDF for .NET's ImageCompressionOptions (consumed by HiddenDataSanitizationOptions.ImageCompressionOptions); implemented here as a thin mapping onto the existing (*Document).OptimizeImages.

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 ImageStamp added in v0.4.0

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

ImageStamp overlays a raster image (PNG or JPEG), stretched to fill Rect. Mirrors Aspose.Pdf.ImageStamp. Construct with NewImageStamp / NewImageStampFromStream.

func NewImageStamp added in v0.4.0

func NewImageStamp(path string) (*ImageStamp, error)

NewImageStamp creates an image stamp from a PNG/JPEG file. Mirrors Aspose's ImageStamp(string).

func NewImageStampFromStream added in v0.4.0

func NewImageStampFromStream(r io.Reader) (*ImageStamp, error)

NewImageStampFromStream creates an image stamp from a PNG/JPEG reader. Mirrors Aspose's ImageStamp(Stream).

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 ImagesDifference added in v0.10.0

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

ImagesDifference is the result of comparing two rendered pages pixel by pixel. Mirrors Aspose.PDF for .NET's ImagesDifference; DifferentPixels / TotalPixels / Ratio are this library's addition (the design goal the backlog names it by: "difference image plus the changed-pixel ratio") — Aspose instead exposes the raw LockBits-style difference array plus its Height/Stride, a .NET Bitmap implementation detail with no Go equivalent worth mirroring literally when image.Image already carries that shape.

func (*ImagesDifference) DestinationImage added in v0.10.0

func (d *ImagesDifference) DestinationImage() image.Image

DestinationImage returns the second page's rendered image (padded to the compared canvas size, see newImagesDifference). Mirrors ImagesDifference.GetDestinationImage.

func (*ImagesDifference) DifferenceToImage added in v0.10.0

func (d *ImagesDifference) DifferenceToImage(foreground, background Color) image.Image

DifferenceToImage renders a bitmap the size of the compared canvas: foreground where pixels differ, background where they agree. Mirrors ImagesDifference.DifferenceToImage.

func (*ImagesDifference) DifferentPixels added in v0.10.0

func (d *ImagesDifference) DifferentPixels() int

DifferentPixels returns the number of pixels whose colour distance exceeded Threshold.

func (*ImagesDifference) HasDifferences added in v0.10.0

func (d *ImagesDifference) HasDifferences() bool

HasDifferences reports whether any pixel differs.

func (*ImagesDifference) Ratio added in v0.10.0

func (d *ImagesDifference) Ratio() float64

Ratio returns DifferentPixels/TotalPixels in [0,1]; 0 for an empty canvas.

func (*ImagesDifference) SourceImage added in v0.10.0

func (d *ImagesDifference) SourceImage() image.Image

SourceImage returns the first page's rendered image (padded to the compared canvas size, see newImagesDifference). Mirrors ImagesDifference.SourceImage.

func (*ImagesDifference) TotalPixels added in v0.10.0

func (d *ImagesDifference) TotalPixels() int

TotalPixels returns the pixel count of the compared (union) canvas.

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 Invoice added in v0.10.0

type Invoice struct {
	XML      []byte         // the embedded invoice, byte for byte
	FileName string         // the attachment name
	Profile  InvoiceProfile // from the XMP ConformanceLevel, else from the XML
	Standard string         // "Factur-X 1.0 / ZUGFeRD 2.1+", "ZUGFeRD 2.0" or "ZUGFeRD 1.0"
	Version  string         // the XMP Version property; "" when absent
}

Invoice is an e-invoice found in a document.

type InvoiceOptions added in v0.10.0

type InvoiceOptions struct {
	FileName string         // default: "factur-x.xml", or "xrechnung.xml" for XRechnung
	Profile  InvoiceProfile // default: read from the XML's guideline ID
	Format   PDFAFormat     // PDFA3B or PDFA3A; the zero value (PDFA1B, never valid here) means PDFA3B
}

InvoiceOptions configures AttachInvoice. The zero value detects the profile from the XML, names the file as the standard prescribes, and produces PDF/A-3b.

type InvoiceProfile added in v0.10.0

type InvoiceProfile int

InvoiceProfile is the Factur-X / ZUGFeRD conformance level of an invoice.

const (
	InvoiceProfileUnknown   InvoiceProfile = iota
	InvoiceProfileMinimum                  // MINIMUM
	InvoiceProfileBasicWL                  // BASIC WL (without lines)
	InvoiceProfileBasic                    // BASIC
	InvoiceProfileEN16931                  // EN 16931 (ZUGFeRD 1.0 COMFORT)
	InvoiceProfileExtended                 // EXTENDED
	InvoiceProfileXRechnung                // XRECHNUNG
)

func (InvoiceProfile) String added in v0.10.0

func (p InvoiceProfile) String() string

String gives the Factur-X spelling, as written to fx:ConformanceLevel.

type JSONDiffOutputGenerator added in v0.10.0

type JSONDiffOutputGenerator struct{}

JSONDiffOutputGenerator renders comparison differences as JSON. Mirrors Aspose.PDF for .NET's JsonDiffOutputGenerator.

func NewJSONDiffOutputGenerator added in v0.10.0

func NewJSONDiffOutputGenerator() *JSONDiffOutputGenerator

NewJSONDiffOutputGenerator creates a generator. It takes no options — the operation data speaks for itself in JSON, unlike HTML/PDF which need colors to mark differences visually.

func (*JSONDiffOutputGenerator) GenerateOutput added in v0.10.0

func (g *JSONDiffOutputGenerator) GenerateOutput(ops []DiffOperation) (string, error)

GenerateOutput renders ops as a flat JSON array of operations.

func (*JSONDiffOutputGenerator) GenerateOutputPages added in v0.10.0

func (g *JSONDiffOutputGenerator) GenerateOutputPages(pages [][]DiffOperation) (string, error)

GenerateOutputPages renders pages as a JSON array of {"page","operations"} objects, one per page.

func (*JSONDiffOutputGenerator) SaveOutput added in v0.10.0

func (g *JSONDiffOutputGenerator) SaveOutput(path string, ops []DiffOperation) error

SaveOutput writes GenerateOutput's JSON to path.

func (*JSONDiffOutputGenerator) SaveOutputPages added in v0.10.0

func (g *JSONDiffOutputGenerator) SaveOutputPages(path string, pages [][]DiffOperation) error

SaveOutputPages writes GenerateOutputPages's JSON to path.

func (*JSONDiffOutputGenerator) WriteOutput added in v0.10.0

func (g *JSONDiffOutputGenerator) WriteOutput(w io.Writer, ops []DiffOperation) error

WriteOutput writes GenerateOutput's JSON to w.

func (*JSONDiffOutputGenerator) WriteOutputPages added in v0.10.0

func (g *JSONDiffOutputGenerator) WriteOutputPages(w io.Writer, pages [][]DiffOperation) error

WriteOutputPages writes GenerateOutputPages's JSON to w.

type JSONExportOptions added in v0.4.0

type JSONExportOptions struct {
	// Indent pretty-prints the JSON with two-space indentation.
	Indent bool
	// OmitEmpty skips fields with no value (empty text, unchecked checkbox,
	// unselected radio/choice). By default every non-button field is exported,
	// producing a full snapshot of the form.
	OmitEmpty bool
}

JSONExportOptions controls (*Form).ExportJSON / WriteJSON.

type JavaScriptAction

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

JavaScriptAction holds a JavaScript snippet attached to an annotation. JS actions are both parsed from existing PDFs and constructable via NewJavaScriptAction; a constructed action is encoded back on Save.

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 JavaScriptCollection added in v0.4.0

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

JavaScriptCollection is the document-level JavaScript store, backed by the /Catalog/Names/JavaScript name tree (ISO 32000-1 §7.7.4 / §8.5.1). Each entry is a named script that the viewer executes when the document opens (after any /OpenAction). Always non-nil; empty for documents without document-level JavaScript. Lazy-parsed on first call.

Mirrors Aspose.PDF for .NET's Document.JavaScript (a named-script collection). Note this is distinct from action-level JavaScriptAction, which runs on a specific annotation/field event.

SECURITY WARNING: document-level JavaScript executes in the recipient's viewer when the file is opened. Embed only scripts you authored or audited; viewers commonly disable JavaScript by default.

func (*JavaScriptCollection) Add added in v0.4.0

func (c *JavaScriptCollection) Add(name, script string) error

Add registers (or replaces) a named script and writes it through to the /Catalog/Names/JavaScript name tree. An empty name is rejected.

func (*JavaScriptCollection) Clear added in v0.4.0

func (c *JavaScriptCollection) Clear()

Clear removes every named script.

func (*JavaScriptCollection) Count added in v0.4.0

func (c *JavaScriptCollection) Count() int

Count reports how many named scripts are in the collection.

func (*JavaScriptCollection) Get added in v0.4.0

func (c *JavaScriptCollection) Get(name string) string

Get returns the script registered under name, or "" if absent.

func (*JavaScriptCollection) Has added in v0.4.0

func (c *JavaScriptCollection) Has(name string) bool

Has reports whether a script with the given name exists.

func (*JavaScriptCollection) Names added in v0.4.0

func (c *JavaScriptCollection) Names() []string

Names returns the script names in lexical order (the order they are written to the name tree).

func (*JavaScriptCollection) Remove added in v0.4.0

func (c *JavaScriptCollection) Remove(name string) bool

Remove deletes the named script. Returns true if it existed.

type JpegDevice added in v0.3.0

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

JpegDevice renders a page to JPEG. Mirrors Aspose.PDF for .NET's JpegDevice.

func NewJpegDevice added in v0.3.0

func NewJpegDevice(res Resolution, quality int) *JpegDevice

NewJpegDevice returns a JpegDevice; quality outside 1..100 defaults to 90.

func (*JpegDevice) Process added in v0.3.0

func (d *JpegDevice) Process(page *Page, w io.Writer) error

Process renders page and writes it to w as JPEG.

type Layer added in v0.4.0

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

Layer is one Optional Content Group (OCG) in the document.

func (*Layer) IsVisible added in v0.4.0

func (l *Layer) IsVisible() bool

IsVisible reports whether the layer is shown by default (not listed in the default configuration's /OFF set).

func (*Layer) Name added in v0.4.0

func (l *Layer) Name() string

Name returns the layer's display name (its /Name).

func (*Layer) SetName added in v0.4.0

func (l *Layer) SetName(name string)

SetName sets the layer's display name.

func (*Layer) SetVisible added in v0.4.0

func (l *Layer) SetVisible(visible bool)

SetVisible sets the layer's default visibility (its membership in the default configuration's /OFF set). Viewers can still toggle it interactively.

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 LinearGradient added in v0.3.0

type LinearGradient struct {
	X1, Y1, X2, Y2 float64
	Stops          []GradientStop
}

LinearGradient interpolates colour along the line from (X1, Y1) to (X2, Y2). Use NewLinearGradient for the common case.

func NewLinearGradient added in v0.3.0

func NewLinearGradient(x1, y1, x2, y2 float64, stops ...GradientStop) LinearGradient

NewLinearGradient builds a linear gradient from (x1, y1) to (x2, y2) with the given stops.

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.

Example

Add a clickable link annotation that opens an external URL.

package main

import (
	"fmt"
	"log"

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

func main() {
	doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
	page, _ := doc.Page(1)

	link := pdf.NewLinkAnnotation(page, pdf.Rectangle{LLX: 50, LLY: 700, URX: 300, URY: 720})
	link.SetAction(pdf.NewGoToURIAction("https://pkg.go.dev/github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"))
	if err := page.Annotations().Add(link); err != nil {
		log.Fatal(err)
	}
	fmt.Println("annotations:", page.Annotations().Count())
}
Output:
annotations: 1

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) BorderWidth added in v0.3.0

func (a *LinkAnnotation) BorderWidth() float64

BorderWidth returns the width (in points) of the rectangular border drawn around the link annotation. Returns the PDF default of 1pt when /Border is absent, matching the behaviour of viewers like Acrobat.

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) Flatten added in v0.3.0

func (b *LinkAnnotation) Flatten() error

Flatten bakes this annotation's normal appearance (/AP/N, honoring the /AS state) into its page's content stream at the annotation's /Rect, then removes the annotation. The annotation handle is dangling afterwards.

An annotation with no normal appearance (e.g. a sticky-note Text annotation, which viewers render as an icon) is simply removed — nothing is drawn.

Mirrors Aspose.PDF for .NET's Annotation.Flatten. For form-field widgets prefer (*Form).Flatten, which also clears the /AcroForm entry.

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) SetBorderWidth added in v0.3.0

func (a *LinkAnnotation) SetBorderWidth(width float64)

SetBorderWidth writes the /Border entry — [horiz-corner-radius vert-corner-radius border-width]. Pass 0 to suppress the rectangle PDF viewers otherwise draw around the link by default.

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) Flatten added in v0.3.0

func (b *ListBoxField) Flatten() error

Flatten bakes this single field's appearance (each of its widgets) into the owning page content and removes the field, leaving every other field and the /AcroForm dict intact. Mirrors Aspose.PDF for .NET's Field.Flatten.

After Flatten the field handle is dangling and must not be used.

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) SetStyle added in v0.3.0

func (b *ListBoxField) SetStyle(s FieldStyle) error

SetStyle applies s to the field, writing /MK, /BS, /DA, and /Q on the field and its widgets and regenerating each widget's /AP appearance so the new look is visible immediately in every viewer. Returns an error only if the field is detached or a styled font cannot be registered.

func (*ListBoxField) SetValue

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

func (*ListBoxField) Style added in v0.3.0

func (b *ListBoxField) Style() FieldStyle

Style reads back the field's current styling from /DA, /Q, /MK, and /BS. Properties never set return their zero/default value. The first widget is used for /MK and /BS.

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 MarkdownDiffOutputGenerator added in v0.10.0

type MarkdownDiffOutputGenerator struct{}

MarkdownDiffOutputGenerator renders comparison differences as GFM Markdown: **inserted** text bold, ~~deleted~~ text struck through. Mirrors Aspose.PDF for .NET's MarkdownDiffOutputGenerator. As in Aspose, it takes no style options — Markdown's syntax already fixes how insert/delete are marked, and it cannot represent a whitespace-only change at all.

func NewMarkdownDiffOutputGenerator added in v0.10.0

func NewMarkdownDiffOutputGenerator() *MarkdownDiffOutputGenerator

NewMarkdownDiffOutputGenerator creates a generator.

func (*MarkdownDiffOutputGenerator) GenerateOutput added in v0.10.0

func (g *MarkdownDiffOutputGenerator) GenerateOutput(ops []DiffOperation) (string, error)

GenerateOutput renders ops as one Markdown fragment, operations joined by a single space (matching AssembleSourceText/AssembleDestinationText).

func (*MarkdownDiffOutputGenerator) GenerateOutputPages added in v0.10.0

func (g *MarkdownDiffOutputGenerator) GenerateOutputPages(pages [][]DiffOperation) (string, error)

GenerateOutputPages renders one "## Page N" section per page.

func (*MarkdownDiffOutputGenerator) SaveOutput added in v0.10.0

func (g *MarkdownDiffOutputGenerator) SaveOutput(path string, ops []DiffOperation) error

SaveOutput writes GenerateOutput's Markdown to path.

func (*MarkdownDiffOutputGenerator) SaveOutputPages added in v0.10.0

func (g *MarkdownDiffOutputGenerator) SaveOutputPages(path string, pages [][]DiffOperation) error

SaveOutputPages writes GenerateOutputPages's Markdown to path.

func (*MarkdownDiffOutputGenerator) WriteOutput added in v0.10.0

func (g *MarkdownDiffOutputGenerator) WriteOutput(w io.Writer, ops []DiffOperation) error

WriteOutput writes GenerateOutput's Markdown to w.

func (*MarkdownDiffOutputGenerator) WriteOutputPages added in v0.10.0

func (g *MarkdownDiffOutputGenerator) WriteOutputPages(w io.Writer, pages [][]DiffOperation) error

WriteOutputPages writes GenerateOutputPages's Markdown to w.

type MarkdownOptions added in v0.6.0

type MarkdownOptions struct {
	Format PageFormat // zero → A4
	Margin float64    // page margin; zero → 54pt

	// Fonts. BaseFont nil → Helvetica (Standard-14, Latin-1 text only —
	// load a Unicode face with Document.LoadFont for Cyrillic, Greek, …).
	// The style variants default to the matching Standard-14 faces when
	// BaseFont is nil, and to BaseFont itself otherwise.
	BaseFont, BoldFont, ItalicFont, BoldItalicFont Font
	CodeFont                                       Font    // nil → Courier
	BaseSize                                       float64 // body size; zero → 11pt (headings scale from it)

	// FontFamily resolves and embeds a font family by name (registered
	// folders/files first, then the OS fonts — see LoadFontByName) for the
	// regular/bold/italic/bold-italic styles, giving full Unicode text
	// (e.g. "Arial", "DejaVu Sans"). Styles that fail to resolve fall back
	// to the regular face. Explicit BaseFont/BoldFont/… win over it.
	// CodeFontFamily does the same for the code face (e.g. "Consolas").
	FontFamily     string
	CodeFontFamily string

	// BasePath resolves relative image paths. Empty → the .md file's
	// directory (MarkdownToDocument) or the current directory.
	BasePath string

	// Tagged builds a logical structure tree while rendering (headings,
	// paragraphs, lists, tables, figures) for accessible (PDF/UA) output.
	Tagged bool
	// Title and Language feed the tagged document's metadata (PDF/UA
	// requires both). Title empty → derived from the first heading;
	// Language empty → "en". Ignored when Tagged is false.
	Title    string
	Language string
}

MarkdownOptions configures Markdown rendering. The zero value gives A4, 54pt margins, Helvetica/Courier at 11pt.

type MarkdownSaveOptions added in v0.7.0

type MarkdownSaveOptions struct {
	// Pages is a 1-based subset (in the given order); nil = all pages.
	Pages []int
	// ImageDir (SaveMarkdown only) is the directory, relative to the output
	// file, that images are written into. Empty → "<stem>_files".
	ImageDir string
	// ImageWriter externalizes images anywhere (S3, CDN, …): it receives a
	// unique name + bytes and returns the URL to reference. Byte-identical
	// images are written once (SHA-256 dedup).
	ImageWriter func(name string, data []byte) (url string, err error)
	// EmbedImages inlines images as data: URLs instead of files. Note that
	// some renderers (e.g. GitHub) do not display data: images.
	EmbedImages bool
	// NoImages skips images entirely.
	NoImages bool
}

MarkdownSaveOptions configures SaveMarkdown / WriteMarkdown. The zero value exports all pages; SaveMarkdown writes images into "<stem>_files" next to the output.

type MarkupParagraph added in v0.4.0

type MarkupParagraph struct {
	Text      string     // the paragraph text (its lines joined with spaces)
	Rectangle Rectangle  // bounding box in PDF user space
	Lines     []TextLine // the paragraph's lines (with per-fragment positions)
}

MarkupParagraph is a run of consecutive lines forming one paragraph.

type MarkupSection added in v0.4.0

type MarkupSection struct {
	Rectangle  Rectangle
	Paragraphs []MarkupParagraph
}

MarkupSection is a column of paragraphs (left-to-right across the page).

type MissingGlyphPolicy added in v0.14.0

type MissingGlyphPolicy int

MissingGlyphPolicy is TextStyle.MissingGlyph's type. See its doc comment for what each value does.

const (
	// MissingGlyphAllow draws .notdef (or, for Type3, nothing) for a
	// character the font has no glyph for — today's existing behavior,
	// and the zero value, so no caller is affected unless it opts in.
	MissingGlyphAllow MissingGlyphPolicy = iota
	// MissingGlyphError makes the draw/measure call fail, naming the
	// first character the font cannot show.
	MissingGlyphError
	// MissingGlyphReplace substitutes TextStyle.ReplacementRune for
	// every character the font cannot show, drawing that instead of
	// .notdef.
	MissingGlyphReplace
)

type NUpOptions added in v0.4.0

type NUpOptions struct {
	// Rows and Cols define the grid; both must be >= 1.
	Rows, Cols int
	// PageSize is the output sheet size. The zero value uses A4.
	PageSize PageFormat
	// Margin is the blank border around the whole grid, in points.
	Margin float64
	// Gutter is the spacing between adjacent cells, in points.
	Gutter float64
	// Order is the cell-filling order (row-major by default).
	Order NUpOrder
	// DrawBorder draws a thin frame around each placed page.
	DrawBorder bool
}

NUpOptions configures NUp imposition.

type NUpOrder added in v0.4.0

type NUpOrder int

NUpOrder controls the order in which source pages fill the grid cells of an N-up sheet.

const (
	// NUpRowMajor fills left-to-right, then top-to-bottom (the default).
	NUpRowMajor NUpOrder = iota
	// NUpColumnMajor fills top-to-bottom, then left-to-right.
	NUpColumnMajor
)

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 NumberField added in v0.4.0

type NumberField struct{ TextBoxField }

NumberField is a text field with a JavaScript number-format action, so viewers display and validate the value as a formatted number.

func (*NumberField) Flatten added in v0.4.0

func (b *NumberField) Flatten() error

Flatten bakes this single field's appearance (each of its widgets) into the owning page content and removes the field, leaving every other field and the /AcroForm dict intact. Mirrors Aspose.PDF for .NET's Field.Flatten.

After Flatten the field handle is dangling and must not be used.

func (*NumberField) FullName added in v0.4.0

func (b *NumberField) FullName() string

func (*NumberField) IsReadOnly added in v0.4.0

func (b *NumberField) IsReadOnly() bool

func (*NumberField) IsRequired added in v0.4.0

func (b *NumberField) IsRequired() bool

func (*NumberField) PageIndex added in v0.4.0

func (b *NumberField) PageIndex() int

func (*NumberField) PartialName added in v0.4.0

func (b *NumberField) PartialName() string

func (*NumberField) Rect added in v0.4.0

func (b *NumberField) Rect() Rectangle

func (*NumberField) SetStyle added in v0.4.0

func (b *NumberField) SetStyle(s FieldStyle) error

SetStyle applies s to the field, writing /MK, /BS, /DA, and /Q on the field and its widgets and regenerating each widget's /AP appearance so the new look is visible immediately in every viewer. Returns an error only if the field is detached or a styled font cannot be registered.

func (*NumberField) Style added in v0.4.0

func (b *NumberField) Style() FieldStyle

Style reads back the field's current styling from /DA, /Q, /MK, and /BS. Properties never set return their zero/default value. The first widget is used for /MK and /BS.

type NumberFormatOptions added in v0.4.0

type NumberFormatOptions struct {
	Decimals        int    // number of decimal places (0 = integer)
	UseSeparator    bool   // group thousands (1,234)
	CurrencySymbol  string // e.g. "$", "€" (empty = none)
	CurrencyPrepend bool   // symbol before the number ("$1" vs "1$")
}

NumberFormatOptions configures a NumberField's display formatting (maps to Acrobat's AFNumber_Format). The zero value is a plain integer.

type Operation added in v0.9.0

type Operation int

Operation is the kind of a difference. Mirrors Aspose.PDF for .NET's Aspose.Pdf.Comparison.Operation.

const (
	// OperationEqual marks text present in both documents.
	OperationEqual Operation = iota
	// OperationInsert marks text present only in the second document.
	OperationInsert
	// OperationDelete marks text present only in the first document.
	OperationDelete
)

func (Operation) String added in v0.9.0

func (o Operation) String() string

String returns "equal", "insert" or "delete".

type OptimizationOptions added in v0.6.0

type OptimizationOptions struct {
	// RemoveUnusedObjects drops objects that neither a page nor the
	// document catalog uses.
	RemoveUnusedObjects bool
	// SubsetFonts rebuilds embedded TrueType fonts to the glyphs used.
	SubsetFonts bool
	// UnembedFonts drops the embedded program from a simple font whose name
	// and metrics match a Helvetica/Times/Courier Standard-14 face, relying
	// on the renderer's substitution instead. Opt-in: unlike the other
	// options this can change how the document looks in a viewer whose
	// installed substitute differs from what was embedded.
	UnembedFonts bool
	// CompressStreams Flate-compresses source streams stored uncompressed
	// (lossless).
	CompressStreams bool
	// RemoveDuplicateStreams merges byte-identical stream objects into one
	// and repoints references (lossless).
	RemoveDuplicateStreams bool
	// CompressObjects packs non-stream objects into object streams and writes
	// a cross-reference stream on Save/WriteTo (lossless; the file becomes
	// PDF 1.5 or later). Ignored by SaveLinearized.
	CompressObjects bool
	// Images, when non-nil, downscales/recodes images per the options
	// (potentially lossy — opt-in).
	Images *OptimizeImageOptions
}

OptimizationOptions selects which reductions Document.Optimize applies. The zero value does nothing; use DefaultOptimizationOptions for the safe lossless preset. Mirrors Aspose.PDF for .NET's OptimizationOptions consumed by Document.OptimizeResources.

func DefaultOptimizationOptions added in v0.6.0

func DefaultOptimizationOptions() OptimizationOptions

DefaultOptimizationOptions returns the safe, lossless preset: remove unused objects, subset fonts, compress uncompressed streams, dedupe identical streams, and pack objects into object streams. Image recompression is left off (opt-in via Images because it can be lossy).

type OptimizationResult added in v0.6.0

type OptimizationResult struct {
	RemovedObjects      int
	SubsettedFonts      int
	UnembeddedFonts     int
	OptimizedImages     int
	CompressedStreams   int
	DeduplicatedStreams int
	// CompressedObjects is the number of objects eligible for packing when
	// Optimize ran; the packing itself happens on Save/WriteTo.
	CompressedObjects int
}

OptimizationResult reports what Document.Optimize changed.

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 PDFAFormat added in v0.4.0

type PDFAFormat int

PDFAFormat identifies a PDF/A conformance level. The "b" (basic) levels cover visual reproducibility; the "a" (accessible) levels add the PDF/A "a" requirement of a Tagged PDF logical structure tree (author one with (*Document).TaggedContent). Mirrors the PDF/A members of Aspose.PDF for .NET's PdfFormat enum.

const (
	PDFA1B PDFAFormat = iota // PDF/A-1b (ISO 19005-1, PDF 1.4)
	PDFA2B                   // PDF/A-2b (ISO 19005-2, PDF 1.7)
	PDFA3B                   // PDF/A-3b (ISO 19005-3, PDF 1.7; allows embedded files)
	PDFA1A                   // PDF/A-1a (ISO 19005-1, accessible/tagged)
	PDFA2A                   // PDF/A-2a (ISO 19005-2, accessible/tagged)
	PDFA3A                   // PDF/A-3a (ISO 19005-3, accessible/tagged)
)

func (PDFAFormat) String added in v0.4.0

func (f PDFAFormat) String() string

String returns the human-readable conformance name, e.g. "PDF/A-1B".

type PDFAIssue added in v0.4.0

type PDFAIssue struct {
	Rule    string // short stable code, e.g. "FONT_NOT_EMBEDDED"
	Message string
}

PDFAIssue describes a single PDF/A conformance violation.

type PDFAValidationReport added in v0.4.0

type PDFAValidationReport struct {
	Format PDFAFormat
	// Conformant is true when no violations were found for the requested level.
	Conformant bool
	Issues     []PDFAIssue
}

PDFAValidationReport is returned by (*Document).ValidatePDFA.

type PDFDiffOutputGenerator added in v0.10.0

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

PDFDiffOutputGenerator renders comparison differences as a generated PDF report — colored, word-wrapped, paginated text — built through this library's Flow layer rather than Aspose's own (presumably fixed-layout) renderer. Mirrors Aspose.PDF for .NET's PdfOutputGenerator. Unlike HTML/JSON/Markdown, a PDF cannot be produced as a string, so this type only implements FileDiffOutputGenerator, matching Aspose (PdfOutputGenerator does not implement IStringOutputGenerator either).

func NewPDFDiffOutputGenerator added in v0.10.0

func NewPDFDiffOutputGenerator(opts ...PDFDiffReportOptions) *PDFDiffOutputGenerator

NewPDFDiffOutputGenerator creates a generator with the given options (last one wins); the zero value uses PDFDiffReportOptions's defaults.

func (*PDFDiffOutputGenerator) SaveOutput added in v0.10.0

func (g *PDFDiffOutputGenerator) SaveOutput(path string, ops []DiffOperation) error

SaveOutput writes a single-section report to path.

func (*PDFDiffOutputGenerator) SaveOutputPages added in v0.10.0

func (g *PDFDiffOutputGenerator) SaveOutputPages(path string, pages [][]DiffOperation) error

SaveOutputPages writes a report with one heading section per page to path.

func (*PDFDiffOutputGenerator) WriteOutput added in v0.10.0

func (g *PDFDiffOutputGenerator) WriteOutput(w io.Writer, ops []DiffOperation) error

WriteOutput writes a single-section report to w.

func (*PDFDiffOutputGenerator) WriteOutputPages added in v0.10.0

func (g *PDFDiffOutputGenerator) WriteOutputPages(w io.Writer, pages [][]DiffOperation) error

WriteOutputPages writes a report with one heading section per page to w.

type PDFDiffReportOptions added in v0.10.0

type PDFDiffReportOptions struct {
	DiffOutputStyle
	Format PageFormat // zero → A4
	Title  string     // zero → "Comparison Report"
}

PDFDiffReportOptions configures PDFDiffOutputGenerator. The zero value resolves to A4, the default DiffOutputStyle colors, and the title "Comparison Report". Mirrors the constructor overloads of Aspose.PDF for .NET's PdfOutputGenerator (OutputTextStyle, PageInfo), folded into one options struct since Go has no overloading.

type PDFUAIssue added in v0.4.0

type PDFUAIssue struct {
	Rule    string // short stable code, e.g. "UA_FIGURE_NO_ALT"
	Message string
}

PDFUAIssue describes a single PDF/UA (accessibility) conformance violation.

type PDFUAValidationReport added in v0.4.0

type PDFUAValidationReport struct {
	// Conformant is true when no violations were found.
	Conformant bool
	Issues     []PDFUAIssue
}

PDFUAValidationReport is returned by (*Document).ValidatePDFUA.

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) AddFloatingBox added in v0.4.0

func (p *Page) AddFloatingBox(box *FloatingBox, rect Rectangle) error

AddFloatingBox draws box at an absolute position inside rect: it paints the background and border, then lays out the box content within rect minus padding (content that overflows the box is clipped). When the document is tagged the box becomes a /Div structure element and its decoration an artifact.

func (*Page) AddForm added in v0.4.0

func (p *Page) AddForm(form *XForm, rect Rectangle) error

AddForm places the form on the page so its box maps onto rect, preserving the form's own scale per axis. The form is built (frozen) on the first call and reused for every subsequent placement — one /Form XObject, many Do invocations across pages and positions. A zero-size rect is rejected.

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.

Example

Place a JPEG image on a blank page.

package main

import (
	"bytes"
	"fmt"
	"log"

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

func main() {
	doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
	page, _ := doc.Page(1)
	rect := pdf.Rectangle{LLX: 50, LLY: 50, URX: 300, URY: 300}
	if err := page.AddImage("testdata/Koala.jpg", rect); err != nil {
		log.Fatal(err)
	}

	var buf bytes.Buffer
	if _, err := doc.WriteTo(&buf); err != nil {
		log.Fatal(err)
	}
	fmt.Println("ok")
}
Output:
ok

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) AddInlineImage added in v0.4.0

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

AddInlineImage draws a small image directly into the page content stream as an inline image (BI … ID … EI, ISO 32000-1 §8.9.7) rather than an Image XObject. Inline images suit tiny, one-off pictures (icons, rules); for anything larger, AddImage (an XObject) is the better choice and the recommended default. PNG and JPEG inputs are supported; PNG transparency is dropped (inline images cannot carry a soft mask). The image is scaled to fill rect. Mirrors the inline-image idiom of ISO 32000-1 §8.9.7.

func (*Page) AddInlineImageFromStream added in v0.4.0

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

AddInlineImageFromStream is the io.Reader variant of AddInlineImage.

func (*Page) AddMarkdown added in v0.6.0

func (p *Page) AddMarkdown(md string, rect Rectangle, opts ...MarkdownOptions) error

AddMarkdown renders a Markdown fragment inside the rectangle. Content that does not fit is clipped (same convention as FloatingBox).

func (*Page) AddSVG added in v0.2.0

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

AddSVG reads an SVG file and renders it into the given rectangle on the page. Unsupported elements (text, image, gradients, masks) are skipped silently per Phase 2 scope.

Returns error only on XML parse failure, invalid numeric attributes, or I/O errors.

func (*Page) AddSVGFromStream added in v0.2.0

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

AddSVGFromStream renders an SVG from any io.Reader into the given rectangle on the page. Best-effort: unsupported elements are silently skipped.

func (*Page) AddSVGObject added in v0.2.0

func (p *Page) AddSVGObject(svg *SVG, rect Rectangle) error

AddSVGObject renders a pre-parsed SVG into the given rectangle on the page. Useful when the same SVG is rendered on multiple pages without re-parsing.

func (*Page) AddStamp added in v0.4.0

func (p *Page) AddStamp(s Stamp) error

AddStamp draws a stamp onto the page. Mirrors Aspose.PDF for .NET's Page.AddStamp(Stamp).

func (*Page) AddTOC added in v0.4.0

func (p *Page) AddTOC(entries []TOCEntry, rect Rectangle, opts ...TOCOptions) (int, error)

AddTOC renders a table of contents from a supplied list of entries into rect on this page. Entries flow top-to-bottom; long titles are truncated to fit before the page-number column. When the entries overflow rect, continuation pages of the same size are appended to the document and the number of pages added is returned (0 if everything fits in rect).

Each entry with a non-nil Page is drawn with its page number and a clickable GoTo link (unless disabled in TOCOptions). Mirrors building a TOC region by hand in Aspose.PDF for .NET.

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) AddTaggedList added in v0.4.0

func (p *Page) AddTaggedList(tc *TaggedContent, parent *StructElement, items []string, style TextStyle, rect Rectangle, ordered bool) (*StructElement, error)

AddTaggedList draws a bulleted (ordered=false) or numbered (ordered=true) list of items inside rect and builds its accessible structure: an /L element under parent (nil = the document root), with an /LI per item containing an /Lbl (the bullet/number) and an /LBody (the item text). Each item's text wraps within the body column; items are stacked top-down and any that would fall below rect are dropped (no auto-pagination in this version). Returns the /L element. Requires Document.TaggedContent.

func (*Page) AddTaggedTable added in v0.4.0

func (p *Page) AddTaggedTable(tc *TaggedContent, parent *StructElement, t *Table, rect Rectangle) (*StructElement, int, error)

AddTaggedTable renders t inside rect like AddTable, and at the same time builds the table's logical structure (/Table → /TR → /TH/TD) under parent (nil = the document root), tagging each cell's content as marked content and bracketing cell backgrounds and borders as /Artifact. The first RepeatingRowsCount rows are tagged as header cells (/TH). Returns the /Table structure element and the number of continuation pages appended. Requires Document.TaggedContent to have been called. Mirrors the table tagging of Aspose.PDF for .NET's tagged content.

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.

Example

Draw "Hello, world!" centered on a blank A4 page and write the resulting PDF to an in-memory buffer.

package main

import (
	"bytes"
	"fmt"
	"log"

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

func main() {
	doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
	page, _ := doc.Page(1)
	size, _ := page.Size()

	style := pdf.TextStyle{
		Font:   pdf.FontHelveticaBold,
		Size:   24,
		HAlign: pdf.HAlignCenter,
		VAlign: pdf.VAlignMiddle,
	}
	rect := pdf.Rectangle{LLX: 0, LLY: 0, URX: size.Width, URY: size.Height}
	if err := page.AddText("Hello, world!", style, rect); err != nil {
		log.Fatal(err)
	}

	var buf bytes.Buffer
	if _, err := doc.WriteTo(&buf); err != nil {
		log.Fatal(err)
	}
	fmt.Println("wrote:", buf.Len() > 0)
}
Output:
wrote: true

func (*Page) AddTextAt added in v0.13.0

func (p *Page) AddTextAt(text string, style TextStyle, x, y float64) error

AddTextAt draws text as a single line whose baseline starts at (x, y): no word-wrapping, no clipping to any rectangle, and whitespace is kept exactly as given — unlike AddText, which normalizes runs of whitespace through strings.Fields while wrapping. For a caller that already does its own line-breaking and positioning and only needs this library to place and shape individual lines (GitHub issue #18, `pdf-go-xe3l`). Uses the same font resources, OpenType shaping (GSUB/GPOS) and bidi reordering as AddText, so MeasureText/GetFontMetrics below always agree with what this draws.

HAlign anchors the line at x the way SVG's text-anchor does: HAlignLeft (the default) starts the line at x, HAlignCenter centers it on x, HAlignRight ends it at x. y is always the exact baseline — no ascent-based offset is applied, unlike AddText's rect-relative vertical placement (see GetFontMetrics to compute that offset yourself, the same way AddText does internally).

Color, Underline, Strikethrough, Rotation (pivot = (x, y) instead of a rectangle corner), Skew, Invisible, Behind and RTL from TextStyle all apply the same way they do in AddText. Background and VAlign have no meaning without a rectangle to fill or align within and are ignored.

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() (Rectangle, error)

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

func (*Page) BeginLayer added in v0.4.0

func (p *Page) BeginLayer(layer *Layer) error

BeginLayer starts a marked-content section on the page assigned to layer: content drawn after this call (AddText, Draw*, AddImage, …) belongs to the layer until EndLayer. Pair every BeginLayer with an EndLayer.

func (*Page) BleedBox

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

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

func (*Page) CropBox

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

CropBox returns the crop box of the page as a Rectangle. Falls back to MediaBox if not set. Mirrors Aspose.PDF for .NET's Page.CropBox.

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.

Example

Draw a filled rectangle with a stroked border on a blank page.

package main

import (
	"fmt"
	"log"

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

func main() {
	doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
	page, _ := doc.Page(1)

	style := pdf.ShapeStyle{
		LineStyle: pdf.LineStyle{
			Color: &pdf.Color{R: 0.1, G: 0.3, B: 0.6, A: 1},
			Width: 2,
		},
		FillColor: &pdf.Color{R: 0.85, G: 0.92, B: 1, A: 1},
	}
	rect := pdf.Rectangle{LLX: 100, LLY: 600, URX: 400, URY: 750}
	if err := page.DrawRectangle(rect, style); err != nil {
		log.Fatal(err)
	}
	fmt.Println("ok")
}
Output:
ok

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) EndLayer added in v0.4.0

func (p *Page) EndLayer() error

EndLayer closes the marked-content section opened by BeginLayer.

func (*Page) ExtractImages

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

ExtractImages returns all images found on the page.

func (*Page) ExtractText

func (p *Page) ExtractText(opts ...TextExtractOptions) (string, error)

ExtractText returns the text content of the page. Characters from fonts with unrecognized encodings are replaced with U+FFFD. An optional TextExtractOptions selects reading order (default) or raw content-stream order.

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) Forms added in v0.4.0

func (p *Page) Forms() []*XForm

Forms returns the Form XObjects referenced by the page's resources — the reusable content groups already present (e.g. parsed from a loaded PDF or placed earlier). Each can be re-placed on any page of the same document with AddForm, or imported into another document with Document.ImportForm.

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) MediaBox added in v0.3.0

func (p *Page) MediaBox() (Rectangle, error)

MediaBox returns the page's MediaBox as a Rectangle in PDF user space. If not set on the page itself, it is inherited from the page tree. Mirrors Aspose.PDF for .NET's Page.MediaBox.

func (*Page) Number

func (p *Page) Number() int

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

func (*Page) Paragraphs added in v0.4.0

func (p *Page) Paragraphs() (PageMarkup, error)

Paragraphs returns the page's text grouped into columns (sections) and paragraphs. Mirrors Aspose.PDF for .NET's ParagraphAbsorber.

func (*Page) RenderBMP added in v0.3.0

func (p *Page) RenderBMP(w io.Writer, opts RenderOptions) error

RenderBMP renders the page and writes it as an uncompressed BMP.

func (*Page) RenderGIF added in v0.3.0

func (p *Page) RenderGIF(w io.Writer, opts RenderOptions) error

RenderGIF renders the page and writes it as GIF (256 colours, quantized).

func (*Page) RenderImage added in v0.3.0

func (p *Page) RenderImage(opts RenderOptions) (image.Image, error)

RenderImage rasterizes the page to an *image.RGBA at the requested DPI. The rendered region is the CropBox intersected with the MediaBox per ISO 32000-1 §7.7.3.3 (a stray CropBox larger than the page would otherwise shrink the content into a corner of an oversized canvas). Content the renderer does not yet support is skipped rather than erroring, so a page always produces an image.

func (*Page) RenderJPEG added in v0.3.0

func (p *Page) RenderJPEG(w io.Writer, opts RenderOptions, quality int) error

RenderJPEG renders the page and writes it as JPEG. quality is 1..100; values outside that range use 90.

func (*Page) RenderPNG added in v0.3.0

func (p *Page) RenderPNG(w io.Writer, opts RenderOptions) error

RenderPNG renders the page and writes it as PNG.

func (*Page) RenderTIFF added in v0.3.0

func (p *Page) RenderTIFF(w io.Writer, opts RenderOptions) error

RenderTIFF renders the page and writes it as a single-page Deflate TIFF.

func (*Page) ReplaceText added in v0.4.0

func (p *Page) ReplaceText(old, replacement string, opts ...ReplaceOptions) (int, error)

ReplaceText replaces every occurrence of old with replacement on the page and returns the number of replacements made. The matched glyphs are removed and the replacement is drawn at the same baseline, size, and colour in a metric-compatible Standard-14 face chosen from the original's family and style (so any replacement text renders, even when the original used an embedded subset font that lacks the new glyphs). The line is not re-flowed: a much longer replacement may overrun following content. Matches are located within a single line, like SearchText. Mirrors the find-and-replace idiom of Aspose.PDF for .NET's TextFragmentAbsorber + TextFragment.Text.

Removing the old text reuses the SAME content-stream rewriter ApplyRedactions does (rewriteTextOperatorsInStream), so it shares that function's one hard limit: a match drawn with a font this pipeline cannot resolve (an undeclared font name, or a simple font with no usable /Encoding/ToUnicode) makes this call return an error instead of replacing it — rather than, as before, silently leaving the OLD text underneath the new replacement text it still drew on top (a real, if cosmetic, bug this change trades for a clear error; found during an independent review of pdf-go-oq9i, the ApplyRedactions fix this inherited). Also removes the dead, now-unreferenced ORIGINAL content stream from the document once at least one match was replaced (RemoveUnusedObjects, the same reason ApplyRedactions calls it — pdf-go-2qkq's class of leak otherwise applies here too, since old text containing whatever was just "replaced" would stay recoverable in the saved file) — so, like ApplyRedactions, call ReplaceText only after placing everything else you mean to keep.

func (*Page) Rotation

func (p *Page) Rotation() RotationAngle

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

func (*Page) SaveSVG added in v0.7.0

func (p *Page) SaveSVG(path string, opts ...SVGSaveOptions) error

SaveSVG writes the page as a standalone SVG file.

func (*Page) SearchText added in v0.3.0

func (p *Page) SearchText(query string, opts ...SearchOptions) ([]TextMatch, error)

SearchText finds every occurrence of query on the page and returns the matches in visual reading order (top-to-bottom, left-to-right). Each match carries the matched text and a bounding rectangle in PDF user space.

By default the query is a case-sensitive literal string; pass a SearchOptions to enable case-insensitive and/or regular-expression matching. At most one SearchOptions is honored (the last, if several are passed).

This mirrors Aspose.PDF for .NET's TextFragmentAbsorber + page.Accept flow. Matches are located within a single text line: a query that would straddle a line break is not found. An empty query, or an invalid regular expression, returns an error.

Example

Search for text on a page and get the bounding box of each match.

package main

import (
	"fmt"
	"log"

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

func main() {
	doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
	page, _ := doc.Page(1)
	_ = page.AddText("The quick brown fox jumps over the lazy dog.",
		pdf.TextStyle{Size: 14}, pdf.Rectangle{LLX: 50, LLY: 700, URX: 545, URY: 780})

	matches, err := page.SearchText("brown fox")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%d match: %q\n", len(matches), matches[0].Text)
}
Output:
1 match: "brown fox"

func (*Page) SetArtBox added in v0.3.0

func (p *Page) SetArtBox(rect Rectangle) error

SetArtBox sets the page's ArtBox (meaningful content extent).

func (*Page) SetBleedBox added in v0.3.0

func (p *Page) SetBleedBox(rect Rectangle) error

SetBleedBox sets the page's BleedBox (production bleed region).

func (*Page) SetCropBox added in v0.3.0

func (p *Page) SetCropBox(rect Rectangle) error

SetCropBox sets the page's CropBox (the visible region). Mirrors Page.CropBox.

func (*Page) SetMediaBox added in v0.3.0

func (p *Page) SetMediaBox(rect Rectangle) error

SetMediaBox sets the page's MediaBox (the full page rectangle) in PDF user space. The box is written directly on the page, overriding any inherited or referenced value. Mirrors Aspose.PDF for .NET's Page.MediaBox setter.

func (*Page) SetPageSize added in v0.3.0

func (p *Page) SetPageSize(width, height float64) error

SetPageSize resizes the page by setting its MediaBox to [0 0 width height] (points). Existing content is not scaled or moved — only the page rectangle changes. Mirrors Aspose.PDF for .NET's Page.SetPageSize.

func (*Page) SetTrimBox added in v0.3.0

func (p *Page) SetTrimBox(rect Rectangle) error

SetTrimBox sets the page's TrimBox (intended finished dimensions).

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) TagArtifact added in v0.4.0

func (p *Page) TagArtifact(draw func() error) error

TagArtifact brackets a block of page drawing as an /Artifact marked-content sequence, so it is treated as decoration and excluded from the logical structure tree. Use it for running headers/footers, page numbers, backgrounds and rules in a Tagged PDF — PDF/UA requires every content item to be either tagged as structure or marked as an artifact. Requires Document.TaggedContent.

func (*Page) TagContent added in v0.4.0

func (p *Page) TagContent(parent *StructElement, t StructType, draw func() error) (*StructElement, error)

TagContent draws a block of page content (everything the draw callback emits) inside a marked-content sequence and adds a corresponding leaf structure element of type t as a child of parent (nil = the document root). The returned element can carry alternate text (e.g. for a Figure). Returns an error if the document is not set up for tagging or the draw callback fails.

func (*Page) TrimBox

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

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

func (*Page) WriteSVG added in v0.7.0

func (p *Page) WriteSVG(w io.Writer, opts ...SVGSaveOptions) error

WriteSVG writes the page as one standalone SVG document to w.

Example

Export a page as a standalone true-vector SVG file.

package main

import (
	"fmt"
	"log"
	"strings"

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

func main() {
	doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
	page, _ := doc.Page(1)
	_ = page.DrawCircle(pdf.Point{X: 200, Y: 600}, 50,
		pdf.ShapeStyle{FillColor: &pdf.Color{R: 1, G: 0.8, A: 1}})

	var svg strings.Builder
	if err := page.WriteSVG(&svg); err != nil {
		log.Fatal(err)
	}
	fmt.Println("vector output:", strings.Contains(svg.String(), "<svg"))
}
Output:
vector output: true

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 PageLabelRange added in v0.3.0

type PageLabelRange struct {
	StartPage int            // 1-based page where this range begins
	Style     PageLabelStyle // numbering style
	Prefix    string         // optional label prefix (e.g. "A-")
	StartNum  int            // first number for this range; treated as 1 if ≤ 0
}

PageLabelRange describes a contiguous run of pages that share a numbering style. The first range must start at page 1; subsequent ranges inherit every preceding range's style/prefix until overridden. Mirrors the entries of a /PageLabels /Nums leaf per PDF spec §12.4.2.

type PageLabelStyle added in v0.3.0

type PageLabelStyle int

PageLabelStyle is the numbering style applied within a PageLabelRange. Mirrors the /S values from PDF spec §12.4.2 Table 159.

const (
	PageLabelStyleNone       PageLabelStyle = iota // no /S — only the prefix is rendered
	PageLabelDecimal                               // /D — 1, 2, 3, …
	PageLabelRomanLower                            // /r — i, ii, iii, …
	PageLabelRomanUpper                            // /R — I, II, III, …
	PageLabelAlphabeticLower                       // /a — a, b, …, z, aa, ab, …
	PageLabelAlphabeticUpper                       // /A — A, B, …, Z, AA, AB, …
)

type PageMarkup added in v0.4.0

type PageMarkup struct {
	PageNumber int
	Sections   []MarkupSection
}

PageMarkup is the structured text of one page.

type PageNumberStamp added in v0.4.0

type PageNumberStamp struct {

	// Format is the template. "{0}" is replaced by the current page number and
	// "{1}" by the total page count — e.g. "Page {0} of {1}". Empty = "{0}".
	// Mirrors Aspose PageNumberStamp.Format (which uses "#").
	Format string
	// StartingNumber is the number shown on page 1 (default 1); page n shows
	// StartingNumber-1+n. Mirrors Aspose PageNumberStamp.StartingNumber.
	StartingNumber int
	// TextStyle controls font, size, and colour.
	TextStyle TextStyle
	// contains filtered or unexported fields
}

PageNumberStamp stamps the page number (and optionally the total), formatted by Format. Mirrors Aspose.Pdf.PageNumberStamp. Construct with NewPageNumberStamp; typically placed as a footer (set VAlign = VAlignBottom).

func NewPageNumberStamp added in v0.4.0

func NewPageNumberStamp(format string, style TextStyle) *PageNumberStamp

NewPageNumberStamp creates a page-number stamp. Mirrors Aspose's PageNumberStamp(format, ...).

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 PasswordBoxField added in v0.4.0

type PasswordBoxField struct{ TextBoxField }

PasswordBoxField is a text field whose input is masked (Password flag). Its value is not stored in a saved file by conforming viewers.

func (*PasswordBoxField) Flatten added in v0.4.0

func (b *PasswordBoxField) Flatten() error

Flatten bakes this single field's appearance (each of its widgets) into the owning page content and removes the field, leaving every other field and the /AcroForm dict intact. Mirrors Aspose.PDF for .NET's Field.Flatten.

After Flatten the field handle is dangling and must not be used.

func (*PasswordBoxField) FullName added in v0.4.0

func (b *PasswordBoxField) FullName() string

func (*PasswordBoxField) IsReadOnly added in v0.4.0

func (b *PasswordBoxField) IsReadOnly() bool

func (*PasswordBoxField) IsRequired added in v0.4.0

func (b *PasswordBoxField) IsRequired() bool

func (*PasswordBoxField) PageIndex added in v0.4.0

func (b *PasswordBoxField) PageIndex() int

func (*PasswordBoxField) PartialName added in v0.4.0

func (b *PasswordBoxField) PartialName() string

func (*PasswordBoxField) Rect added in v0.4.0

func (b *PasswordBoxField) Rect() Rectangle

func (*PasswordBoxField) SetStyle added in v0.4.0

func (b *PasswordBoxField) SetStyle(s FieldStyle) error

SetStyle applies s to the field, writing /MK, /BS, /DA, and /Q on the field and its widgets and regenerating each widget's /AP appearance so the new look is visible immediately in every viewer. Returns an error only if the field is detached or a styled font cannot be registered.

func (*PasswordBoxField) Style added in v0.4.0

func (b *PasswordBoxField) Style() FieldStyle

Style reads back the field's current styling from /DA, /Q, /MK, and /BS. Properties never set return their zero/default value. The first widget is used for /MK and /BS.

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 PdfPageStamp added in v0.4.0

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

PdfPageStamp overlays (or underlays) a page from another PDF document as a stamp — the source page is imported once as a Form XObject and drawn into the stamp's Rect, scaled to fit while preserving aspect ratio, positioned by HAlign/VAlign, and honoring Opacity, RotateAngle and Background. Mirrors Aspose.PDF for .NET's PdfPageStamp. Construct with NewPdfPageStamp.

func NewPdfPageStamp added in v0.4.0

func NewPdfPageStamp(srcDoc *Document, srcPageNum int) (*PdfPageStamp, error)

NewPdfPageStamp creates a stamp that draws page srcPageNum (1-based) of srcDoc.

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 PngDevice added in v0.3.0

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

PngDevice renders a page to PNG at a fixed resolution. Mirrors Aspose.PDF for .NET's PngDevice.

func NewPngDevice added in v0.3.0

func NewPngDevice(res Resolution) *PngDevice

NewPngDevice returns a PngDevice for the given resolution.

func (*PngDevice) Process added in v0.3.0

func (d *PngDevice) Process(page *Page, w io.Writer) error

Process renders page and writes it to w as PNG.

type Point

type Point struct {
	X, Y float64
}

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

type PolygonAnnotation added in v0.4.0

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

PolygonAnnotation draws a closed polygon through a list of vertices, with a stroked border and optional interior fill. Mirrors Aspose.PDF for .NET's PolygonAnnotation.

func NewPolygonAnnotation added in v0.4.0

func NewPolygonAnnotation(page *Page, vertices []Point) *PolygonAnnotation

NewPolygonAnnotation builds an unbound polygon annotation through the given vertices (PDF user space). Page must be non-nil. The /Rect is auto-computed from the vertices; the annotation is not added to the document until page.Annotations().Add(poly) succeeds.

func (*PolygonAnnotation) AnnotationType added in v0.4.0

func (a *PolygonAnnotation) AnnotationType() AnnotationType

func (*PolygonAnnotation) InteriorColor added in v0.4.0

func (a *PolygonAnnotation) InteriorColor() *Color

InteriorColor returns the /IC fill colour, or nil if absent. For a Polygon this fills the closed shape; for a PolyLine it fills any closed line endings (ClosedArrow/Square/Circle/Diamond).

func (*PolygonAnnotation) RegenerateAppearance added in v0.4.0

func (a *PolygonAnnotation) RegenerateAppearance()

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

func (*PolygonAnnotation) SetBorderWidth added in v0.4.0

func (a *PolygonAnnotation) SetBorderWidth(w float64)

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

func (*PolygonAnnotation) SetInteriorColor added in v0.4.0

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

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

func (*PolygonAnnotation) SetVertices added in v0.4.0

func (a *PolygonAnnotation) SetVertices(v []Point)

SetVertices writes /Vertices (a flat x y x y … array), recomputes /Rect, and regenerates /AP/N. The slice is copied; the caller may safely mutate it after this returns.

func (*PolygonAnnotation) Vertices added in v0.4.0

func (a *PolygonAnnotation) Vertices() []Point

Vertices returns a copy of the annotation's vertices in PDF user space. Mutating the result does not affect the annotation.

type PolylineAnnotation added in v0.4.0

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

PolylineAnnotation draws an open polyline through a list of vertices, with a stroked border, optional line endings at the first and last vertex, and optional interior fill for closed endings. Mirrors Aspose.PDF for .NET's PolylineAnnotation.

func NewPolylineAnnotation added in v0.4.0

func NewPolylineAnnotation(page *Page, vertices []Point) *PolylineAnnotation

NewPolylineAnnotation builds an unbound polyline annotation through the given vertices (PDF user space). Page must be non-nil. The /Rect is auto-computed from the vertices.

func (*PolylineAnnotation) AnnotationType added in v0.4.0

func (a *PolylineAnnotation) AnnotationType() AnnotationType

func (*PolylineAnnotation) EndLineEnding added in v0.4.0

func (a *PolylineAnnotation) EndLineEnding() LineEndingStyle

EndLineEnding returns the style applied to the last vertex.

func (*PolylineAnnotation) InteriorColor added in v0.4.0

func (a *PolylineAnnotation) InteriorColor() *Color

InteriorColor returns the /IC fill colour, or nil if absent. For a Polygon this fills the closed shape; for a PolyLine it fills any closed line endings (ClosedArrow/Square/Circle/Diamond).

func (*PolylineAnnotation) RegenerateAppearance added in v0.4.0

func (a *PolylineAnnotation) RegenerateAppearance()

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

func (*PolylineAnnotation) SetBorderWidth added in v0.4.0

func (a *PolylineAnnotation) SetBorderWidth(w float64)

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

func (*PolylineAnnotation) SetEndLineEnding added in v0.4.0

func (a *PolylineAnnotation) SetEndLineEnding(s LineEndingStyle)

SetEndLineEnding sets the end-side (last vertex) line-ending style.

func (*PolylineAnnotation) SetInteriorColor added in v0.4.0

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

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

func (*PolylineAnnotation) SetStartLineEnding added in v0.4.0

func (a *PolylineAnnotation) SetStartLineEnding(s LineEndingStyle)

SetStartLineEnding sets the start-side (first vertex) line-ending style.

func (*PolylineAnnotation) SetVertices added in v0.4.0

func (a *PolylineAnnotation) SetVertices(v []Point)

SetVertices writes /Vertices (a flat x y x y … array), recomputes /Rect, and regenerates /AP/N. The slice is copied; the caller may safely mutate it after this returns.

func (*PolylineAnnotation) StartLineEnding added in v0.4.0

func (a *PolylineAnnotation) StartLineEnding() LineEndingStyle

StartLineEnding returns the style applied to the first vertex.

func (*PolylineAnnotation) Vertices added in v0.4.0

func (a *PolylineAnnotation) Vertices() []Point

Vertices returns a copy of the annotation's vertices in PDF user space. Mutating the result does not affect the annotation.

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 RadialGradient added in v0.3.0

type RadialGradient struct {
	CX, CY, R, FX, FY float64
	Stops             []GradientStop
}

RadialGradient interpolates colour from the focal point (FX, FY) out to the circle centred at (CX, CY) with radius R. NewRadialGradient sets the focal point to the centre (the common case); set FX/FY explicitly for an off-centre highlight.

func NewRadialGradient added in v0.3.0

func NewRadialGradient(cx, cy, r float64, stops ...GradientStop) RadialGradient

NewRadialGradient builds a radial gradient on the circle centred at (cx, cy) with radius r, focal point at the centre.

type RadioButtonField

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

RadioButtonField is a group of mutually exclusive options.

func (*RadioButtonField) Flatten added in v0.3.0

func (b *RadioButtonField) Flatten() error

Flatten bakes this single field's appearance (each of its widgets) into the owning page content and removes the field, leaving every other field and the /AcroForm dict intact. Mirrors Aspose.PDF for .NET's Field.Flatten.

After Flatten the field handle is dangling and must not be used.

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) SetStyle added in v0.3.0

func (b *RadioButtonField) SetStyle(s FieldStyle) error

SetStyle applies s to the field, writing /MK, /BS, /DA, and /Q on the field and its widgets and regenerating each widget's /AP appearance so the new look is visible immediately in every viewer. Returns an error only if the field is detached or a styled font cannot be registered.

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) Style added in v0.3.0

func (b *RadioButtonField) Style() FieldStyle

Style reads back the field's current styling from /DA, /Q, /MK, and /BS. Properties never set return their zero/default value. The first widget is used for /MK and /BS.

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 selects this option and clears all siblings (true), or 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 Recipient added in v0.8.0

type Recipient struct {
	// Certificate is the recipient's X.509 certificate (RSA public key).
	Certificate *x509.Certificate
	// Permissions limits what this recipient may do; nil grants everything.
	Permissions *Permissions
}

Recipient is one certificate that may open a public-key-encrypted document, optionally with its own permission set.

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 RenderOptions added in v0.3.0

type RenderOptions struct {
	DPI        float64 // dots per inch; 0 → DefaultDPI
	Background *Color  // page backdrop; nil → opaque white
}

RenderOptions controls page rasterization.

type RepairReport added in v0.10.0

type RepairReport struct {
	// XRefReconstructed is set when the cross-reference table was rebuilt by
	// scanning the file for "N G obj" headers, because the one in the file
	// was missing, unparseable, or did not lead to a usable catalog.
	XRefReconstructed bool
	// ObjectsRecovered is how many objects that scan found. Zero unless
	// XRefReconstructed is set.
	ObjectsRecovered int
	// TrailerRecovered is set when the trailer had to be synthesised from a
	// /Type /Catalog object because the file's own trailer was missing or
	// carried no /Root.
	TrailerRecovered bool
}

RepairReport describes what had to be reconstructed to open the document. The zero value means the file parsed as written.

Scope: this reports structural recovery, decided while the file is being opened. Per-stream tolerance — a wrong /Length resolved by scanning for "endstream", a Flate stream with a bad checksum whose inflated bytes are kept — happens deep in the parser without a document in reach and is not counted here.

type ReplaceOptions added in v0.4.0

type ReplaceOptions struct {
	// CaseInsensitive folds case when matching.
	CaseInsensitive bool
	// Regex treats the search string as an RE2 regular expression.
	Regex bool
}

ReplaceOptions tunes how ReplaceText matches the search text. The zero value matches the literal string, case-sensitively. Mirrors the matching half of Aspose.PDF for .NET's TextReplaceOptions / TextSearchOptions.

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 Resolution added in v0.3.0

type Resolution struct{ DPI float64 }

Resolution is a rendering resolution in DPI. Mirrors Aspose.PDF for .NET's Aspose.Pdf.Devices.Resolution.

func NewResolution added in v0.3.0

func NewResolution(dpi float64) Resolution

NewResolution returns a Resolution of the given DPI.

type RevocationCheck added in v0.10.0

type RevocationCheck int

RevocationCheck selects how far verification goes in establishing whether a signing certificate was revoked.

const (
	// RevocationNone performs no check. The zero value.
	RevocationNone RevocationCheck = iota
	// RevocationOffline uses only revocation material the document carries.
	RevocationOffline
	// RevocationOnline additionally fetches what the document lacks, from the
	// OCSP responder and CRL distribution points named in the certificate.
	RevocationOnline
)

type RevocationFetcher added in v0.10.0

type RevocationFetcher interface {
	// FetchOCSP posts a DER OCSPRequest to url and returns the DER response.
	FetchOCSP(ctx context.Context, url string, req []byte) ([]byte, error)
	// FetchCRL retrieves the DER CRL at url.
	FetchCRL(ctx context.Context, url string) ([]byte, error)
}

RevocationFetcher retrieves revocation material. Implement it to route through a proxy, serve from a cache, or refuse the network entirely.

func DefaultRevocationFetcher added in v0.10.0

func DefaultRevocationFetcher(timeout time.Duration) RevocationFetcher

DefaultRevocationFetcher returns the built-in HTTP fetcher, the one used when ValidationOptions.Fetcher is nil. Exported so a caller can wrap it — to add a cache, or to log what is fetched — rather than reimplement it. timeout bounds each request; zero means 10 seconds.

type RevocationSource added in v0.10.0

type RevocationSource int

RevocationSource records where an answer came from.

const (
	// RevocationFromDocument — material embedded in the PDF.
	RevocationFromDocument RevocationSource = iota
	// RevocationFromOCSP — a responder answered.
	RevocationFromOCSP
	// RevocationFromCRL — a revocation list was consulted.
	RevocationFromCRL
)

func (RevocationSource) String added in v0.10.0

func (s RevocationSource) String() string

String names the source, for messages and test failures.

type RevocationState added in v0.10.0

type RevocationState int

RevocationState is what a responder or a CRL says about a certificate.

const (
	// RevocationUnknown means no usable answer was obtained — no responder,
	// an unparseable or stale response, a signature that did not check out.
	RevocationUnknown RevocationState = iota
	// RevocationGood means the issuer states the certificate is not revoked.
	RevocationGood
	// RevocationRevoked means the issuer states it is revoked.
	RevocationRevoked
)

func (RevocationState) String added in v0.10.0

func (s RevocationState) String() string

String names the state, for messages and test failures.

type RevocationStatus added in v0.10.0

type RevocationStatus struct {
	Status     RevocationState
	Source     RevocationSource
	RevokedAt  time.Time // set only when Status is RevocationRevoked
	Reason     int       // CRL reason code (RFC 5280 §5.3.1); 0 when unspecified
	ProducedAt time.Time // when the answer was produced
	Err        error     // why the status is unknown
}

RevocationStatus is what the issuer says about a signing certificate.

type RichTextBoxField added in v0.4.0

type RichTextBoxField struct{ TextBoxField }

RichTextBoxField is a text field that carries a rich-text value (RichText flag + /RV) in addition to its plain /V.

func (*RichTextBoxField) Flatten added in v0.4.0

func (b *RichTextBoxField) Flatten() error

Flatten bakes this single field's appearance (each of its widgets) into the owning page content and removes the field, leaving every other field and the /AcroForm dict intact. Mirrors Aspose.PDF for .NET's Field.Flatten.

After Flatten the field handle is dangling and must not be used.

func (*RichTextBoxField) FullName added in v0.4.0

func (b *RichTextBoxField) FullName() string

func (*RichTextBoxField) IsReadOnly added in v0.4.0

func (b *RichTextBoxField) IsReadOnly() bool

func (*RichTextBoxField) IsRequired added in v0.4.0

func (b *RichTextBoxField) IsRequired() bool

func (*RichTextBoxField) PageIndex added in v0.4.0

func (b *RichTextBoxField) PageIndex() int

func (*RichTextBoxField) PartialName added in v0.4.0

func (b *RichTextBoxField) PartialName() string

func (*RichTextBoxField) Rect added in v0.4.0

func (b *RichTextBoxField) Rect() Rectangle

func (*RichTextBoxField) RichValue added in v0.4.0

func (r *RichTextBoxField) RichValue() string

RichValue returns the field's /RV rich-text value.

func (*RichTextBoxField) SetRichValue added in v0.4.0

func (r *RichTextBoxField) SetRichValue(rv, plain string) error

SetRichValue sets the rich-text value (/RV, XHTML) and mirrors a plain-text fallback into /V.

func (*RichTextBoxField) SetStyle added in v0.4.0

func (b *RichTextBoxField) SetStyle(s FieldStyle) error

SetStyle applies s to the field, writing /MK, /BS, /DA, and /Q on the field and its widgets and regenerating each widget's /AP appearance so the new look is visible immediately in every viewer. Returns an error only if the field is detached or a styled font cannot be registered.

func (*RichTextBoxField) Style added in v0.4.0

func (b *RichTextBoxField) Style() FieldStyle

Style reads back the field's current styling from /DA, /Q, /MK, and /BS. Properties never set return their zero/default value. The first widget is used for /MK and /BS.

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 SVG added in v0.2.0

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

SVG is the pre-parsed SVG document.

func (*SVG) Size added in v0.2.0

func (s *SVG) Size() (width, height float64)

Size returns the intrinsic width and height as parsed from the <svg> root element's width and height attributes. Returns (0, 0) if neither is present.

func (*SVG) ViewBox added in v0.2.0

func (s *SVG) ViewBox() (x, y, w, h float64)

ViewBox returns the viewBox attribute as (x, y, width, height). If no viewBox is set, returns (0, 0, intrinsicWidth, intrinsicHeight).

type SVGFontResolver added in v0.2.0

type SVGFontResolver func(family string, bold, italic bool) Font

SVGFontResolver maps an SVG font-family + style to a pdf.Font. Return nil to fall back to the library's built-in heuristic (Standard 14 mapping based on family keyword).

type SVGSaveOptions added in v0.7.0

type SVGSaveOptions struct {
	// DPI sets the coordinate scale (the viewBox is the page at this
	// resolution) and the resolution of raster patches. 0 → 150. The vector
	// content itself is resolution-independent.
	DPI float64
	// Pages is a 1-based subset for Document.SaveSVG; nil = all pages.
	Pages []int
	// ResourceWriter externalizes binary parts (images, raster patches)
	// instead of embedding them as data: URLs: it receives a unique name +
	// bytes and returns the URL to reference from the SVG.
	ResourceWriter func(name string, data []byte) (url string, err error)
}

SVGSaveOptions configures SaveSVG / WriteSVG. The zero value exports all pages at 150 DPI with images embedded as data: URLs (self-contained files).

type SearchOptions added in v0.3.0

type SearchOptions struct {
	// CaseInsensitive folds case when matching (literal and regex alike).
	CaseInsensitive bool
	// Regex treats the query as an RE2 regular expression instead of a literal
	// string. Invalid patterns are reported as an error by SearchText.
	Regex bool
	// Rectangle, when non-nil, limits results to matches whose bounding box
	// intersects this region (PDF user space, applied to every page). nil
	// searches the whole page. Mirrors Aspose.PDF for .NET's
	// TextSearchOptions.Rectangle.
	Rectangle *Rectangle
	// SearchInAnnotations also searches the text content (/Contents) of the
	// page's annotations — sticky notes, free text, markup, etc. Each match's
	// Rect is the annotation's rectangle. Mirrors Aspose.PDF for .NET's
	// TextSearchOptions.SearchInAnnotations.
	SearchInAnnotations bool
}

SearchOptions tunes how SearchText interprets the query. The zero value is a case-sensitive literal search, matching the default of Aspose.PDF for .NET's TextFragmentAbsorber.

type ShapeStyle

type ShapeStyle struct {
	LineStyle
	FillColor    *Color         // nil = no fill
	FillPattern  string         // optional PDF pattern resource name (e.g. "/P0"); overrides FillColor when set
	FillGradient Gradient       // optional linear/radial gradient fill; overrides FillColor
	FillTiling   *TilingPattern // optional repeating tiling-pattern fill; overrides FillColor
}

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.

FillPattern, when non-empty, overrides FillColor: the fill uses a PDF /Pattern colorspace with the named pattern resource (e.g. "/P0"). Used internally by the SVG renderer to wire gradient fills.

FillGradient, when non-nil, fills the shape with a LinearGradient or RadialGradient. It takes precedence over FillColor; the draw call registers the necessary PDF shading pattern on the page automatically.

FillTiling, when non-nil, fills the shape with a repeating TilingPattern (a user-drawn cell tiled across the shape). It takes precedence over FillColor; the draw call registers the PatternType 1 pattern automatically. Precedence on fill: FillTiling → FillGradient → FillPattern → FillColor.

Mirrors Aspose.PDF for .NET's GraphInfo (stroke + fill).

type SideBySideComparisonOptions added in v0.10.0

type SideBySideComparisonOptions struct {
	ComparisonOptions
	// InsertColor / DeleteColor style the markup on each pane, same meaning
	// as DiffMarkupOptions. Defaults: green insertions, red deletions.
	InsertColor *Color
	DeleteColor *Color
}

SideBySideComparisonOptions configures a side-by-side spread. Embeds ComparisonOptions — phase 1's word-diff options (ExtractionArea, ExcludeAreas1/2, ExcludeTables, EditOperationsOrder, IgnoreCase) apply here too, since the spread is built on the same word-diff engine. Mirrors Aspose.PDF for .NET's SideBySideComparisonOptions, minus ComparisonMode (this library's tokenizer already splits words on whitespace, so behaviour already matches Aspose's IgnoreSpaces mode; the Normal/ParseSpaces whitespace-sensitivity distinction is out of scope for v1) and AdditionalChangeMarks (margin change bars — out of scope for v1).

type SideBySideDocsComparisonResult added in v0.10.0

type SideBySideDocsComparisonResult struct {
	*ComparisonResult
}

SideBySideDocsComparisonResult reports a document-level side-by-side comparison. Mirrors Aspose.PDF for .NET's SideBySideDocsComparisonResult; embeds *ComparisonResult, so HasChanges/Operations/PageOperations/ Statistics all apply directly to the spread's underlying comparison.

func SideBySideCompareDocuments added in v0.10.0

func SideBySideCompareDocuments(doc1, doc2 *Document, outputPath string, opts ...SideBySideComparisonOptions) (*SideBySideDocsComparisonResult, error)

SideBySideCompareDocuments lays every page pair of doc1 and doc2 side by side — paired by index like CompareDocumentsPageByPage, so the longer document's tail pages get an empty pane on the missing side — one output page per pair, and saves the spread as a new PDF at outputPath. Mirrors Aspose.PDF for .NET's SideBySidePdfComparer.Compare(Document, Document, string, SideBySideComparisonOptions).

func WriteSideBySideDocuments added in v0.10.0

func WriteSideBySideDocuments(doc1, doc2 *Document, w io.Writer, opts ...SideBySideComparisonOptions) (*SideBySideDocsComparisonResult, error)

WriteSideBySideDocuments is the io.Writer variant of SideBySideCompareDocuments.

type SideBySidePagesComparisonResult added in v0.10.0

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

SideBySidePagesComparisonResult reports a page-level side-by-side comparison. Mirrors Aspose.PDF for .NET's SideBySidePagesComparisonResult.

func SideBySideComparePages added in v0.10.0

func SideBySideComparePages(page1, page2 *Page, outputPath string, opts ...SideBySideComparisonOptions) (*SideBySidePagesComparisonResult, error)

SideBySideComparePages lays page1 and page2 side by side on one output page — page1 (deletions struck through) on the left, page2 (insertions highlighted) on the right — and saves it as a new PDF at outputPath. Mirrors Aspose.PDF for .NET's SideBySidePdfComparer.Compare(Page, Page, string, SideBySideComparisonOptions).

func WriteSideBySidePages added in v0.10.0

func WriteSideBySidePages(page1, page2 *Page, w io.Writer, opts ...SideBySideComparisonOptions) (*SideBySidePagesComparisonResult, error)

WriteSideBySidePages is the io.Writer variant of SideBySideComparePages.

func (*SideBySidePagesComparisonResult) HasChanges added in v0.10.0

func (r *SideBySidePagesComparisonResult) HasChanges() bool

HasChanges reports whether the two pages differ.

func (*SideBySidePagesComparisonResult) Operations added in v0.10.0

Operations returns the underlying word-level differences (the same model ComparePages returns).

type SignOptions added in v0.4.0

type SignOptions struct {
	Certificate *x509.Certificate
	PrivateKey  crypto.Signer
	Chain       []*x509.Certificate // optional intermediates, embedded alongside the signer cert
	Reason      string              // optional /Reason
	Location    string              // optional /Location
	ContactInfo string              // optional /ContactInfo
	Name        string              // optional /Name (signer name shown by viewers)
	SigningTime time.Time           // zero → time of signing

	// Visible draws the signature on the page as a widget in Rect with a
	// generated appearance (mirrors Aspose.PDF for .NET's
	// PdfFileSignature.Sign(..., visible, rect, ...)). The zero value keeps
	// the signature invisible.
	Visible bool
	// Rect is the widget rectangle in PDF user space (required when Visible).
	Rect Rectangle
	// Page is the 1-based page for the visible widget; 0 means page 1.
	Page int
	// Appearance customizes the visible block's text and style (mirrors
	// Aspose.PDF for .NET's SignatureCustomAppearance). nil = a sensible
	// default (signer name + date, plus reason/location when set).
	Appearance *SignatureAppearance

	// SignHash signs a digest instead of holding the key: the alternative to
	// PrivateKey for a hardware module or a remote signing service that only
	// ever sees the hash. It is handed the digest and the hash that produced
	// it, and returns the raw signature — PKCS#1 v1.5 for an RSA
	// certificate, ASN.1 ECDSA for an elliptic-curve one, matching what
	// crypto.Signer would have produced. Exactly one of PrivateKey and
	// SignHash must be set; Certificate is required either way, since the
	// SignerInfo is built from it. Mirrors the intent of Aspose.PDF for
	// .NET's CustomSignHash.
	SignHash func(digest []byte, hash crypto.Hash) ([]byte, error)

	// Digest selects the hash used for the message digest and the signature
	// itself. The zero value is SHA-256. Mirrors Aspose.PDF for .NET's
	// DigestHashAlgorithm.
	Digest DigestAlgorithm

	// PAdES produces an ETSI.CAdES.detached (PAdES baseline) signature: the
	// CMS carries the ESS signing-certificate-v2 attribute and /SubFilter is
	// /ETSI.CAdES.detached. The zero value produces a classic
	// /adbe.pkcs7.detached signature.
	PAdES bool

	// Certify makes this a certification (author / DocMDP) signature that
	// records which later changes are permitted without invalidating it.
	// The zero value (NotCertified) is an ordinary approval signature.
	// Mirrors Aspose.PDF for .NET's PdfFileSignature.Certify +
	// DocMDPAccessPermissions.
	Certify CertifyPermission

	// TimestampURL, when set, fetches an RFC 3161 trusted timestamp from that
	// Time-Stamp Authority over the signature and embeds it, anchoring the
	// signing time to a trusted clock. Requires network access at sign time.
	TimestampURL string

	// Incremental appends the signature as a new revision instead of
	// rewriting the file, preserving the original bytes verbatim. This is
	// REQUIRED to add a second signature without invalidating earlier ones,
	// and is auto-enabled when the document already contains a signature.
	// Requires a document opened from an existing PDF (Open/OpenStream).
	Incremental bool

	// LTV appends a further revision carrying the long-term validation
	// material (/DSS) once the signature is written, so the signature can
	// still be verified after the certificate expires. It runs
	// AddValidationInfo with RevocationOnline, so it needs network access at
	// sign time; without a reachable responder only the certificates are
	// embedded. Mirrors the intent of Aspose.PDF for .NET's LTV support.
	LTV bool
}

SignOptions configures a digital signature. Certificate and PrivateKey are required; the key is any crypto.Signer (RSA or ECDSA), so callers load it however they like (PEM via the standard library, an HSM, a freshly generated test key, …) — no certificate file is needed in the repository.

type SignatureAppearance added in v0.4.0

type SignatureAppearance struct {
	ShowName     bool    // "Digitally signed by <signer>"
	ShowDate     bool    // "Date: <signing time>"
	ShowReason   bool    // "Reason: <reason>" (only if a reason is set)
	ShowLocation bool    // "Location: <location>" (only if a location is set)
	Font         Font    // text font; nil = Helvetica
	FontSize     float64 // text size in points; 0 = auto-fit to the rectangle
	Color        *Color  // text color; nil = dark blue
}

SignatureAppearance controls the visible signature block's content and styling. Mirrors the intent of Aspose.PDF for .NET's SignatureCustomAppearance. The zero value (with the Show… flags false) is only used when an explicit *SignatureAppearance is supplied; passing nil to SignOptions.Appearance yields the full default block.

type SignatureVerification added in v0.4.0

type SignatureVerification struct {
	FieldName           string            // the /T of the signature field
	SignerName          string            // /Name from the signature dictionary, if present
	Reason              string            // /Reason
	Location            string            // /Location
	SigningTime         time.Time         // parsed from /M (zero if absent/unparseable)
	Valid               bool              // signature cryptographically valid AND content intact
	IntegrityOK         bool              // the /ByteRange bytes match the signature digest
	CoversWholeDocument bool              // the signature covers the entire file
	Certificate         *x509.Certificate // signer certificate (nil on parse failure)
	// Chain holds the other certificates the signer embedded — the
	// intermediates a caller needs to build a path to a trust anchor. The
	// signer certificate itself is not repeated here.
	Chain []*x509.Certificate
	// Revocation is what the issuer says about the signing certificate. It is
	// nil unless ValidationOptions asked for a check. A revoked certificate
	// does not make Valid false: Valid stays cryptographic, and what to do
	// about revocation is the caller's policy.
	Revocation *RevocationStatus
	// LTVEnabled reports that the document carries everything needed to verify
	// this signature offline. Mirrors Aspose.PDF for .NET's IsLtvEnabled.
	LTVEnabled bool
	Err        error // non-nil reason when Valid is false
}

SignatureVerification is the result of verifying one digital signature.

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

func (m *SquigglyAnnotation) QuadPoints() []QuadPoint

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

func (*SquigglyAnnotation) RegenerateAppearance added in v0.9.0

func (a *SquigglyAnnotation) RegenerateAppearance()

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

func (*SquigglyAnnotation) SetColor

func (m *SquigglyAnnotation) SetColor(c *Color)

SetColor writes /C and redraws the appearance in the new colour.

func (*SquigglyAnnotation) SetQuadPoints

func (m *SquigglyAnnotation) SetQuadPoints(qp []QuadPoint)

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

func (*SquigglyAnnotation) SetRect

func (m *SquigglyAnnotation) SetRect(r Rectangle)

SetRect moves the annotation and redraws its appearance, whose coordinates are relative to the rectangle.

type Stamp added in v0.4.0

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

Stamp is content overlaid on (or behind) a page: a TextStamp, an ImageStamp, or a PageNumberStamp. Apply it with (*Page).AddStamp or (*Document).AddStamp. Mirrors Aspose.PDF for .NET's Aspose.Pdf.Stamp class hierarchy.

Every stamp shares the placement and appearance fields of stampBase (embedded): a placement Rect (zero value = the whole page), HAlign/VAlign within that Rect, Opacity, RotateAngle, and Background (draw behind page content). Concrete types add their own content.

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

func (m *StrikeOutAnnotation) QuadPoints() []QuadPoint

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

func (*StrikeOutAnnotation) RegenerateAppearance added in v0.9.0

func (a *StrikeOutAnnotation) RegenerateAppearance()

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

func (*StrikeOutAnnotation) SetColor

func (m *StrikeOutAnnotation) SetColor(c *Color)

SetColor writes /C and redraws the appearance in the new colour.

func (*StrikeOutAnnotation) SetQuadPoints

func (m *StrikeOutAnnotation) SetQuadPoints(qp []QuadPoint)

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

func (*StrikeOutAnnotation) SetRect

func (m *StrikeOutAnnotation) SetRect(r Rectangle)

SetRect moves the annotation and redraws its appearance, whose coordinates are relative to the rectangle.

type StringDiffOutputGenerator added in v0.10.0

type StringDiffOutputGenerator interface {
	// GenerateOutput renders a single, unlabeled list of operations — the
	// shape ComparePages returns.
	GenerateOutput(ops []DiffOperation) (string, error)
	// GenerateOutputPages renders one section per page — the shape
	// (*ComparisonResult).Pages returns.
	GenerateOutputPages(pages [][]DiffOperation) (string, error)
}

StringDiffOutputGenerator produces comparison output as a string. Mirrors Aspose.PDF for .NET's IStringOutputGenerator.

type StructElement added in v0.4.0

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

StructElement is a node in the logical structure tree.

func (*StructElement) AddChild added in v0.4.0

func (e *StructElement) AddChild(t StructType) *StructElement

AddChild creates a grouping structure element of type t as a child of e and returns it. Use it for containers (Sect, Table, TR, TD, L, LI, …) that hold other elements rather than wrapping content directly.

func (*StructElement) AddObjectReference added in v0.10.0

func (e *StructElement) AddObjectReference(annot Annotation) error

AddObjectReference ties e directly to annot via an Object Reference (/OBJR, ISO 32000-1 §14.7.4.4) rather than marked content — the mechanism a /Link structure element uses to point at its LinkAnnotation, so assistive technology can associate the two (also valid for any other annotation type, e.g. bringing a Widget into reading order). annot must already be attached to a page (via (*AnnotationCollection).Add) before calling this — /Pg is read from that attachment, not asked of the caller, so it can never disagree with where the annotation actually lives. annot gains a /StructParent entry pointing back at e; an annotation already referenced by another structure element is rejected; each annotation is meant to appear in the reading order exactly once.

Composes with the existing primitives rather than replacing them: a link whose visible text is itself tagged calls this on the element TagContent returned; a link with no separately-tagged visible text (e.g. an image link tagged as /Figure elsewhere) calls it on a bare AddChild(StructLink).

func (*StructElement) SetActualText added in v0.4.0

func (e *StructElement) SetActualText(text string)

SetActualText sets the exact text (/ActualText) the element represents.

func (*StructElement) SetAlt added in v0.4.0

func (e *StructElement) SetAlt(text string)

SetAlt sets alternate text (/Alt) — required on Figure/Formula for PDF/UA.

func (*StructElement) SetLanguage added in v0.4.0

func (e *StructElement) SetLanguage(lang string)

SetLanguage overrides the natural language for this element's content.

type StructType added in v0.4.0

type StructType string

StructType is a PDF standard structure type (ISO 32000-1 §14.8.4), used as the /S value of a structure element. The value includes the leading slash.

const (
	StructDocument StructType = "/Document"
	StructPart     StructType = "/Part"
	StructArt      StructType = "/Art"
	StructSect     StructType = "/Sect"
	StructDiv      StructType = "/Div"
	StructP        StructType = "/P"
	StructH        StructType = "/H"
	StructH1       StructType = "/H1"
	StructH2       StructType = "/H2"
	StructH3       StructType = "/H3"
	StructH4       StructType = "/H4"
	StructH5       StructType = "/H5"
	StructH6       StructType = "/H6"
	StructSpan     StructType = "/Span"
	StructQuote    StructType = "/Quote"
	StructNote     StructType = "/Note"
	StructCode     StructType = "/Code"
	StructFigure   StructType = "/Figure"
	StructFormula  StructType = "/Formula"
	StructCaption  StructType = "/Caption"
	StructList     StructType = "/L"
	StructListItem StructType = "/LI"
	StructLabel    StructType = "/Lbl"
	StructListBody StructType = "/LBody"
	StructTable    StructType = "/Table"
	StructTR       StructType = "/TR"
	StructTH       StructType = "/TH"
	StructTD       StructType = "/TD"
	StructTHead    StructType = "/THead"
	StructTBody    StructType = "/TBody"
	StructTFoot    StructType = "/TFoot"
	StructLink     StructType = "/Link"
	// StructAnnot wraps content associated with an annotation other than a
	// link (e.g. a comment's visible marker).
	StructAnnot StructType = "/Annot"
	// StructForm marks a form field's visible representation as part of the
	// reading order — distinct from the AcroForm field itself.
	StructForm StructType = "/Form"
	// StructBibEntry is one entry in a bibliography.
	StructBibEntry StructType = "/BibEntry"
	// StructBlockQuote is a block-level (multi-paragraph) quotation, as
	// opposed to StructQuote's inline one.
	StructBlockQuote StructType = "/BlockQuote"
	// StructIndex is a sequence of entries in a back-of-book index.
	StructIndex StructType = "/Index"
	// StructTOC is a table of contents; its entries are StructTOCI.
	StructTOC StructType = "/TOC"
	// StructTOCI is one table-of-contents entry, typically containing a
	// StructLink (AddObjectReference) to its target.
	StructTOCI StructType = "/TOCI"
	// StructNonStruct groups content that carries no useful structural
	// meaning of its own without excluding it from the tree entirely (unlike
	// TagArtifact, which removes content from the tree).
	StructNonStruct StructType = "/NonStruct"
	// StructPrivate is application-specific content a generic reader can
	// ignore the internal structure of, but should not discard.
	StructPrivate StructType = "/Private"
	// StructReference is a citation to content elsewhere in the document.
	StructReference StructType = "/Reference"
	// StructRuby and StructWarichu are East Asian typography annotations
	// (ISO 32000-2): a ruby gloss above/beside base text, and interlinear
	// (two-line) annotation text respectively.
	StructRuby    StructType = "/Ruby"
	StructWarichu StructType = "/Warichu"
)

Standard structure types. Grouping types (Document, Part, Sect, Div, Table, TR, L, …) hold child elements; the rest typically wrap marked content.

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 TOCEntry added in v0.4.0

type TOCEntry struct {
	Title string
	Level int
	Page  *Page
	// Label overrides the displayed page number. Empty uses the target
	// Page's 1-based number; set it to show a logical label instead (e.g.
	// a /PageLabels label like "iv" or a body number that differs from the
	// physical page index). The link still targets Page.
	Label string
}

TOCEntry is one line of a table of contents: a title, an indent level (0 = top level), and the page it points at. A nil Page renders the line without a page number or link.

type TOCOptions added in v0.4.0

type TOCOptions struct {
	// Title is the heading drawn above the entries (e.g. "Table of
	// Contents"). Empty draws no heading.
	Title string
	// TitleStyle styles the heading. Zero value = Helvetica-Bold 18, black.
	TitleStyle TextStyle
	// EntryStyle styles every entry line. Zero value = Helvetica 12, black.
	// HAlign/VAlign are managed internally and ignored here.
	EntryStyle TextStyle
	// IndentStep is the horizontal indent added per level, in points.
	// Zero = 18.
	IndentStep float64
	// LineSpacing multiplies the entry font size to get the row height.
	// Zero = 1.6.
	LineSpacing float64
	// Margin is the page margin used for the pages GenerateTOC inserts,
	// in points. Zero = 54. Ignored by Page.AddTOC (which uses its rect).
	Margin float64

	NoPageNumbers bool // zero value draws page numbers
	NoLeader      bool // zero value draws a dotted leader between title and number
	NoLinks       bool // zero value adds a GoTo link over each entry
}

TOCOptions controls how a table of contents is rendered. The zero value produces a sensible TOC: black 12pt entries, an 18pt-per-level indent, 1.6 line spacing, dotted leaders, page numbers, and clickable links. The negative ("No…") booleans turn those defaults off so that the zero value stays the full-featured one.

Loosely mirrors Aspose.PDF for .NET's TocInfo (a title plus per-entry formatting and dotted leaders).

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.

Example

Build a tiny invoice-style table and render it onto a blank page.

package main

import (
	"fmt"
	"log"

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

func main() {
	doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
	page, _ := doc.Page(1)

	table := pdf.NewTable().
		SetColumnWidths([]float64{300, 100}).
		SetDefaultCellBorder(pdf.BorderInfo{Sides: pdf.BorderSideAll, Width: 0.5}).
		SetDefaultCellMargin(pdf.MarginInfo{Top: 4, Right: 6, Bottom: 4, Left: 6})

	header := table.AddRow()
	header.AddCell("Item").SetTextStyle(pdf.TextStyle{Font: pdf.FontHelveticaBold, Size: 11})
	header.AddCell("Price").SetTextStyle(pdf.TextStyle{Font: pdf.FontHelveticaBold, Size: 11}).
		SetHAlign(pdf.HAlignRight)

	table.AddRows([][]string{
		{"Espresso", "€3.50"},
		{"Cappuccino", "€4.50"},
		{"Tiramisu", "€7.50"},
	})

	rect := pdf.Rectangle{LLX: 50, LLY: 500, URX: 450, URY: 750}
	if _, err := page.AddTable(table, rect); err != nil {
		log.Fatal(err)
	}
	fmt.Println("rows:", table.RowCount())
}
Output:
rows: 4

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 TableAbsorber added in v0.7.0

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

TableAbsorber detects tables on a page and exposes their logical structure (epic pdf-go-w4ht). Mirrors Aspose.PDF for .NET's TableAbsorber:

absorber := pdf.NewTableAbsorber()
if err := absorber.Visit(page); err != nil { ... }
for _, table := range absorber.TableList() {
    for _, row := range table.RowList() {
        for _, cell := range row.CellList() { _ = cell.Text() }
    }
}

The current detector is vector-native lattice recognition (ruled tables, including borders drawn as thin filled rectangles, dashed/segmented rules, and rowspan/colspan from missing inner rulings). Borderless (stream-mode) recognition is the next phase; note Aspose's own absorber handles ruled tables only.

func NewTableAbsorber added in v0.7.0

func NewTableAbsorber() *TableAbsorber

NewTableAbsorber creates a table absorber.

func (*TableAbsorber) TableList added in v0.7.0

func (ta *TableAbsorber) TableList() []*AbsorbedTable

TableList returns the tables recognized by the last Visit, top-to-bottom.

func (*TableAbsorber) Visit added in v0.7.0

func (ta *TableAbsorber) Visit(p *Page) error

Visit runs table detection on the page, replacing the absorber's TableList.

type TaggedContent added in v0.4.0

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

TaggedContent is the facade for authoring a Tagged PDF (ISO 32000-1 §14.8): it owns the document's logical structure tree and sets the catalog marks PDF/UA requires. Obtain it with (*Document).TaggedContent. Mirrors the intent of Aspose.PDF for .NET's Document.TaggedContent / ITaggedContent.

func (*TaggedContent) Root added in v0.4.0

func (tc *TaggedContent) Root() *StructElement

Root returns the document-level (/Document) structure element — the default parent for top-level content.

func (*TaggedContent) SetLanguage added in v0.4.0

func (tc *TaggedContent) SetLanguage(lang string)

SetLanguage sets the document's default natural language (/Catalog/Lang), e.g. "en-US".

func (*TaggedContent) SetTitle added in v0.4.0

func (tc *TaggedContent) SetTitle(title string)

SetTitle sets the document title (so PDF/UA's title requirement is met).

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) Flatten added in v0.3.0

func (b *TextAnnotation) Flatten() error

Flatten bakes this annotation's normal appearance (/AP/N, honoring the /AS state) into its page's content stream at the annotation's /Rect, then removes the annotation. The annotation handle is dangling afterwards.

An annotation with no normal appearance (e.g. a sticky-note Text annotation, which viewers render as an icon) is simply removed — nothing is drawn.

Mirrors Aspose.PDF for .NET's Annotation.Flatten. For form-field widgets prefer (*Form).Flatten, which also clears the /AcroForm entry.

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) Flatten added in v0.3.0

func (b *TextBoxField) Flatten() error

Flatten bakes this single field's appearance (each of its widgets) into the owning page content and removes the field, leaving every other field and the /AcroForm dict intact. Mirrors Aspose.PDF for .NET's Field.Flatten.

After Flatten the field handle is dangling and must not be used.

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) SetStyle added in v0.3.0

func (b *TextBoxField) SetStyle(s FieldStyle) error

SetStyle applies s to the field, writing /MK, /BS, /DA, and /Q on the field and its widgets and regenerating each widget's /AP appearance so the new look is visible immediately in every viewer. Returns an error only if the field is detached or a styled font cannot be registered.

func (*TextBoxField) SetValue

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

func (*TextBoxField) Style added in v0.3.0

func (b *TextBoxField) Style() FieldStyle

Style reads back the field's current styling from /DA, /Q, /MK, and /BS. Properties never set return their zero/default value. The first widget is used for /MK and /BS.

func (*TextBoxField) Value

func (f *TextBoxField) Value() string

type TextExtractOptions added in v0.4.0

type TextExtractOptions struct {
	Mode TextExtractionMode
}

TextExtractOptions configures ExtractText. The zero value is reading order.

type TextExtractionMode added in v0.4.0

type TextExtractionMode int

TextExtractionMode selects how ExtractText orders the extracted text. Mirrors the intent of Aspose.PDF for .NET's TextExtractionOptions.TextFormattingMode.

const (
	// TextExtractReading returns text in visual reading order (fragments sorted
	// top-to-bottom, left-to-right, grouped into lines). This is the default.
	TextExtractReading TextExtractionMode = iota
	// TextExtractRaw returns text in the order the content stream emits it,
	// without visual sorting — useful when the emission order is significant or
	// when the reading-order heuristics reorder columned/overlapping content.
	TextExtractRaw
	// TextExtractFlatten lays the page out on a fixed-pitch character grid:
	// every word keeps its horizontal position, padded with spaces, so
	// columns stay columns and the output reads like the page when shown in a
	// monospace font. Mirrors Aspose.PDF for .NET's TextFormattingMode.Flatten
	// — useful for fixed-format reports, for diffing two revisions of a page,
	// and for tabular text no table detector was asked about.
	TextExtractFlatten
)

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
	Rotation      float64 // baseline angle in degrees CCW; 0 = horizontal (diagonal watermarks, axis labels, …)
	// contains filtered or unexported fields
}

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 TextMatch added in v0.3.0

type TextMatch struct {
	Text       string    // the matched text as it appears on the page
	PageNumber int       // 1-based page number the match was found on
	Rect       Rectangle // bounding box of the match in PDF user space (points)
}

TextMatch is a single occurrence located by SearchText.

type TextStamp added in v0.4.0

type TextStamp struct {

	// Value is the text to stamp. Mirrors Aspose TextStamp.Value.
	Value string
	// TextStyle controls font, size, and colour (the stamp's HAlign/VAlign/
	// RotateAngle/Background override the style's alignment/rotation/behind).
	// Mirrors Aspose TextStamp.TextState.
	TextStyle TextStyle
	// contains filtered or unexported fields
}

TextStamp overlays a line (or wrapped block) of text. Mirrors Aspose.Pdf.TextStamp. Construct with NewTextStamp.

func NewTextStamp added in v0.4.0

func NewTextStamp(text string, style TextStyle) *TextStamp

NewTextStamp creates a text stamp. Mirrors Aspose's TextStamp(string, ...).

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
	RTL           bool    // if true, the paragraph base direction is right-to-left (Hebrew/Arabic); default false (auto-detected from the text when it contains RTL characters)
	Skew          float64 // synthetic oblique: glyph slant in degrees (positive leans right, ~12 matches typical italics); applied per line about its baseline — faux italic for fonts without an italic face
	Invisible     bool    // if true, glyphs use text rendering mode 3 (ISO 32000-1 §9.3.6): nothing is painted, but the text remains selectable, searchable, and extractable. Underline/Strikethrough decorations are suppressed too. Used for hidden OCR text layers over scanned pages.

	// MissingGlyph controls what AddText/AddTextAt/MeasureText do when
	// the font has no glyph for a character in text. Zero value
	// (MissingGlyphAllow) keeps the long-standing default: the character
	// draws .notdef (glyph 0) — or, for a Type3 font, is silently
	// dropped — with no signal at all (GitHub issue #19,
	// shadowhunter1470-svg). A default-ignorable code point (a zero-width
	// joiner, a variation selector, …) is never flagged regardless of
	// this setting — drawing nothing for one of those is correct, not
	// missing.
	MissingGlyph MissingGlyphPolicy
	// ReplacementRune is substituted for a missing glyph when
	// MissingGlyph is MissingGlyphReplace. Zero value (rune 0) means
	// U+FFFD, the Unicode replacement character — the same substitution
	// this library's own text extraction already uses for a character
	// it can't map back from a glyph. If the font has no glyph for the
	// replacement rune either, that draws .notdef in turn; pick a
	// replacement the font actually covers if that matters.
	ReplacementRune rune
}

TextStyle defines reusable text formatting properties.

type TiffDevice added in v0.3.0

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

TiffDevice renders pages to TIFF. Mirrors Aspose.PDF for .NET's TiffDevice: Process writes one page, ProcessDocument writes a whole document as a single multi-page TIFF.

func NewTiffDevice added in v0.3.0

func NewTiffDevice(res Resolution) *TiffDevice

NewTiffDevice returns a TiffDevice for the given resolution.

func (*TiffDevice) Process added in v0.3.0

func (d *TiffDevice) Process(page *Page, w io.Writer) error

Process renders page and writes it to w as a single-page TIFF.

func (*TiffDevice) ProcessDocument added in v0.3.0

func (d *TiffDevice) ProcessDocument(doc *Document, w io.Writer) error

ProcessDocument renders every page of doc into one multi-page TIFF.

type TilingPattern added in v0.4.0

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

TilingPattern is a repeating fill (PatternType 1, ISO 32000-1 §8.7.3.1): a small cell of content tiled across whatever shape it fills. Draw the cell once via Canvas() (the full *Page drawing API), optionally adjust the tile spacing with SetStep, then use it as a fill by setting ShapeStyle.FillTiling on any Draw* call. Useful for hatching, textures and repeated motifs. Mirrors the colored (PaintType 1) tiling patterns of Aspose.PDF for .NET.

func (*TilingPattern) Canvas added in v0.4.0

func (t *TilingPattern) Canvas() *Page

Canvas returns the cell's drawing surface (the full *Page drawing API). Draw everything before the pattern is first used as a fill — its content is frozen at that point.

func (*TilingPattern) SetStep added in v0.4.0

func (t *TilingPattern) SetStep(xstep, ystep float64)

SetStep sets the horizontal and vertical tile spacing in points. The default is the cell size (tiles touch edge-to-edge); a larger step leaves gaps, a smaller one overlaps. Non-positive values are ignored.

type Type3Font added in v0.8.0

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

Type3Font is a user-defined glyph-stream font. Create with Document.CreateType3Font, add glyphs, then use as TextStyle.Font.

func (*Type3Font) AddGlyph added in v0.8.0

func (t *Type3Font) AddGlyph(r rune, width float64) (*Page, error)

AddGlyph registers a glyph for r with the given advance width (in 1/1000 em, like all font metrics) and returns its drawing canvas: a detached page covering the em square (x 0..1000, y -300..1000, baseline at y=0) on which the whole drawing API works. Draw before the first AddText using the font — glyph streams are frozen when the font is first used. Errors on a duplicate rune, a non-positive width, a font already frozen, or a full font (255 glyphs).

func (*Type3Font) BaseFont added in v0.8.0

func (t *Type3Font) BaseFont() string

BaseFont implements Font.

func (*Type3Font) IsEmbedded added in v0.8.0

func (t *Type3Font) IsEmbedded() bool

IsEmbedded implements Font (glyph streams are embedded by construction).

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

func (m *UnderlineAnnotation) QuadPoints() []QuadPoint

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

func (*UnderlineAnnotation) RegenerateAppearance added in v0.9.0

func (a *UnderlineAnnotation) RegenerateAppearance()

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

func (*UnderlineAnnotation) SetColor

func (m *UnderlineAnnotation) SetColor(c *Color)

SetColor writes /C and redraws the appearance in the new colour.

func (*UnderlineAnnotation) SetQuadPoints

func (m *UnderlineAnnotation) SetQuadPoints(qp []QuadPoint)

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

func (*UnderlineAnnotation) SetRect

func (m *UnderlineAnnotation) SetRect(r Rectangle)

SetRect moves the annotation and redraws its appearance, whose coordinates are relative to the rectangle.

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 ValidationOptions added in v0.10.0

type ValidationOptions struct {
	// Revocation selects how far to go in establishing revocation status.
	Revocation RevocationCheck
	// Fetcher supplies revocation material; nil uses the built-in HTTP client.
	Fetcher RevocationFetcher
	// Timeout bounds each network request; zero means 10 seconds.
	Timeout time.Duration
}

ValidationOptions configures signature verification. The zero value checks no revocation, so existing calls behave exactly as before. Mirrors the intent of Aspose.PDF for .NET's ValidationOptions / OcspSettings.

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.

Scope: this is a structural-integrity check (is the file parseable and internally consistent), NOT a standards-conformance check. It does not validate PDF/A or PDF/UA. This differs from Aspose.PDF for .NET's Document.Validate, which checks PDF/A and PDF/UA compliance and writes an XML report; the corresponding capability here is intentionally narrower.

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

Validate the structural integrity of a PDF file.

package main

import (
	"fmt"
	"log"

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

func main() {
	report, err := pdf.Validate("testdata/4pages.pdf")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("valid:", report.Valid, "issues:", len(report.Issues))
}
Output:
valid: true issues: 0

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) Flatten added in v0.3.0

func (b *WidgetAnnotation) Flatten() error

Flatten bakes this annotation's normal appearance (/AP/N, honoring the /AS state) into its page's content stream at the annotation's /Rect, then removes the annotation. The annotation handle is dangling afterwards.

An annotation with no normal appearance (e.g. a sticky-note Text annotation, which viewers render as an icon) is simply removed — nothing is drawn.

Mirrors Aspose.PDF for .NET's Annotation.Flatten. For form-field widgets prefer (*Form).Flatten, which also clears the /AcroForm entry.

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

type XForm added in v0.4.0

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

XForm is a reusable Form XObject (ISO 32000-1 §8.10) — a self-contained content stream (with its own resources) that can be placed on any number of pages and positions with a single Do invocation. Draw into it once via its Canvas (the full *Page drawing API: AddText, Draw*, AddImage, AddTable, …), then place it with Page.AddForm. Ideal for page templates, shared headers/footers and watermarks. Mirrors the intent of Aspose.PDF for .NET's XForm.

func (*XForm) Canvas added in v0.4.0

func (x *XForm) Canvas() *Page

Canvas returns the drawing surface for the form. Use the full *Page drawing API on it (AddText, DrawLine, AddImage, AddTable, …). Draw everything before the first Page.AddForm — the form's content is frozen when it is first placed.

func (*XForm) Size added in v0.4.0

func (x *XForm) Size() (width, height float64)

Size returns the form's width and height in points.

type XMPMetadata added in v0.3.0

type XMPMetadata struct {
	Title        string
	Authors      []string
	Description  string
	Keywords     []string
	CreatorTool  string
	Producer     string
	CreateDate   string
	ModifyDate   string
	MetadataDate string
	Custom       []XMPProperty
}

XMPMetadata is the document's XMP packet modelled as common schema fields plus a list of arbitrary Custom properties. Empty fields are omitted when written. Dates are ISO 8601 strings (e.g. "2026-05-29T12:00:00Z") to round-trip losslessly.

Field → XMP property mapping:

  • Title → dc:title (language alternative, x-default)
  • Authors → dc:creator (ordered rdf:Seq)
  • Description → dc:description (language alternative, x-default)
  • Keywords → dc:subject (unordered rdf:Bag)
  • CreatorTool → xmp:CreatorTool
  • CreateDate → xmp:CreateDate
  • ModifyDate → xmp:ModifyDate
  • MetadataDate → xmp:MetadataDate
  • Producer → pdf:Producer

func (XMPMetadata) IsEmpty added in v0.3.0

func (m XMPMetadata) IsEmpty() bool

IsEmpty reports whether the XMP metadata carries no information.

type XMPProperty added in v0.3.0

type XMPProperty struct {
	Namespace string // namespace URI, e.g. "http://ns.adobe.com/xap/1.0/mm/"
	Prefix    string // namespace prefix used in the serialised packet, e.g. "xmpMM"
	Name      string // local property name, e.g. "DocumentID"
	Value     string // property value
}

XMPProperty is a single simple (string-valued) XMP property in an arbitrary namespace. Used for properties outside the common Dublin Core / XMP Basic / PDF schemas modelled directly on XMPMetadata.

type XlsxRecognitionMode added in v0.8.0

type XlsxRecognitionMode int

XlsxRecognitionMode selects what lands in the workbook.

const (
	// XlsxTablesOnly (default): every detected table, stacked on a single
	// "Tables" worksheet in document order — a "Page N" caption above the
	// first table of each page, one blank row between tables. Tables
	// continuing across consecutive pages with the same column signature
	// are stitched into one (the repeated header row is dropped).
	XlsxTablesOnly XlsxRecognitionMode = iota
	// XlsxFullPage: one worksheet per source page carrying ALL page text —
	// layout lines become rows, wide intra-line gaps split cells, detected
	// tables keep their exact logical grid.
	XlsxFullPage
)

type XlsxSaveOptions added in v0.8.0

type XlsxSaveOptions struct {
	// Pages is a 1-based subset (in the given order); nil = all pages.
	Pages []int
	// Mode selects the recognition mode (default XlsxTablesOnly).
	Mode XlsxRecognitionMode
	// NoStyles suppresses fills, fonts, alignment and column widths.
	NoStyles bool
	// NoImages skips images (FullPage mode anchors page images on the
	// sheet; TablesOnly never carries images).
	NoImages bool
}

XlsxSaveOptions configures SaveXlsx / WriteXlsx.

Source Files

Directories

Path Synopsis
_examples
acroform_build command
Builds a single-page A4 PDF with a title, a paragraph of body text, and an AcroForm containing one field of each supported type.
Builds a single-page A4 PDF with a title, a paragraph of body text, and an AcroForm containing one field of each supported type.
acroform_read command
Reads every form field from a PDF and emits a JSON dump to stdout.
Reads every form field from a PDF and emits a JSON dump to stdout.
ai_alt_text command
ai_alt_text fills missing alternate text on the figures of a tagged PDF using a vision model, then saves the more-accessible document.
ai_alt_text fills missing alternate text on the figures of a tagged PDF using a vision model, then saves the more-accessible document.
ai_chat command
ai_chat opens an interactive Q&A session about a PDF using an OpenAI-compatible model: type a question, get an answer grounded in the document; the conversation keeps its history.
ai_chat opens an interactive Q&A session about a PDF using an OpenAI-compatible model: type a question, get an answer grounded in the document; the conversation keeps its history.
ai_make_searchable command
ai_make_searchable OCRs a scanned PDF with a vision-capable model and writes an invisible text layer over each scanned page, so the output is selectable and Ctrl+F-searchable while looking pixel-identical.
ai_make_searchable OCRs a scanned PDF with a vision-capable model and writes an invisible text layer over each scanned page, so the output is selectable and Ctrl+F-searchable while looking pixel-identical.
ai_summary command
ai_summary summarizes a PDF with an OpenAI-compatible model and saves the summary as both text output and a PDF next to the input.
ai_summary summarizes a PDF with an OpenAI-compatible model and saves the summary as both text output and a PDF next to the input.
barcode_verify command
barcode_verify renders BarcodeField symbols of every symbology to PNGs (through the real field/appearance/rasterizer pipeline) plus a manifest.json of what each should decode to, for tools/validate_barcodes.py to check with a third-party decoder.
barcode_verify renders BarcodeField symbols of every symbology to PNGs (through the real field/appearance/rasterizer pipeline) plus a manifest.json of what each should decode to, for tools/validate_barcodes.py to check with a third-party decoder.
embed_font command
feature_showcase command
Feature Showcase — a small "annual report"-style document that exercises every major Aspose.PDF for Go feature inside a single narrative.
Feature Showcase — a small "annual report"-style document that exercises every major Aspose.PDF for Go feature inside a single narrative.
markdown_to_pdf command
markdown_to_pdf converts a Markdown file (CommonMark + GFM tables, strikethrough, task lists, autolinks) to a paginated PDF, plus a PNG preview of page 1.
markdown_to_pdf converts a Markdown file (CommonMark + GFM tables, strikethrough, task lists, autolinks) to a paginated PDF, plus a PNG preview of page 1.
metadata command
openall command
Diagnostic: open every PDF in a folder with the library and report any failures.
Diagnostic: open every PDF in a folder with the library and report any failures.
pdf_to_markdown command
pdf_to_markdown converts a PDF to GFM Markdown.
pdf_to_markdown converts a PDF to GFM Markdown.
render command
render rasterizes every page of a PDF to a PNG under result_files/render/, and writes the whole document as one multi-page TIFF (document.tiff).
render rasterizes every page of a PDF to a PNG under result_files/render/, and writes the whole document as one multi-page TIFF (document.tiff).
set_password command
showcase_preview command
Regenerates docs/feature_showcase-preview.png — the clickable preview shown in the README — as a 2×2 montage of representative pages from docs/feature_showcase.pdf.
Regenerates docs/feature_showcase-preview.png — the clickable preview shown in the README — as a 2×2 montage of representative pages from docs/feature_showcase.pdf.
text_extraction command
textsearch command
textsearch opens a real PDF, searches it for a query string, and prints the matches (text + page + bounding rectangle) as JSON.
textsearch opens a real PDF, searches it for a query string, and prints the matches (text + page + bounding rectangle) as JSON.
toc command
Builds a small multi-section report, adds outline bookmarks, then generates a linked table of contents from those bookmarks.
Builds a small multi-section report, adds outline bookmarks, then generates a linked table of contents from those bookmarks.
visualtest command
visualtest renders a slice of PDFs from a corpus folder to multi-page TIFFs for eyeballing the renderer's output against a reference viewer (Acrobat).
visualtest renders a slice of PDFs from a corpus folder to multi-page TIFFs for eyeballing the renderer's output against a reference viewer (Acrobat).
Package ai provides AI-powered document operations — summarization, OCR of scanned pages, and a hidden-text-layer "make searchable" pipeline — built on the asposepdf core.
Package ai provides AI-powered document operations — summarization, OCR of scanned pages, and a hidden-text-layer "make searchable" pipeline — built on the asposepdf core.

Jump to

Keyboard shortcuts

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