gomupdf

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 3, 2026 License: AGPL-3.0 Imports: 21 Imported by: 0

README

gomupdf

The fast, idiomatic way to read, render, and write PDFs in Go.

A focused cgo binding over the battle-tested MuPDF C core — text extraction, table detection, rendering, and full document assembly, behind a small, Go-shaped API.

CI codecov Go Reference Go Report Card

doc, _ := gomupdf.Open("invoice.pdf")
defer doc.Close()

text, _   := doc.Text()         // every page, in reading order
page, _   := doc.LoadPage(0)
tables, _ := page.FindTables()  // structured rows & columns

pm, _ := page.Pixmap()          // render the page…
_ = pm.SavePNG("page.png")      // …and save it as an image

Why gomupdf?

  • One dependency, many formats. PDF, XPS, EPUB, MOBI, FB2, CBZ, SVG, plain text, and raster images — all open through the same Document API.
  • Extraction that keeps geometry. Plain text and word/span boxes, reading-order reconstruction, and table detection with two strategies (word-alignment and vector-ruling).
  • Real writing, not just reading. Create documents, insert text/images, merge, set metadata/XMP, page labels, page boxes, and save with fine-grained options including AES-256 encryption and incremental updates.
  • Idiomatic Go. iter.Seq2 page ranges, typed geometry, error returns, deterministic Close(), no hidden globals.
  • Thin and honest. A small layer over MuPDF — the credit for the engine belongs upstream; gomupdf gives it a clean Go surface.

Table of contents


Install

go get github.com/srijanmukherjee/gomupdf
Requirements

gomupdf links against the MuPDF C library via cgo, so a C toolchain and MuPDF (shared library + development headers) must be present at build time. CGO_ENABLED=1 is required (on by default for native builds).

Platform Install MuPDF
macOS (Homebrew) brew install mupdf
Debian / Ubuntu sudo apt-get install libmupdf-dev mupdf-tools
Fedora / RHEL sudo dnf install mupdf-devel
Arch sudo pacman -S libmupdf
From source / custom prefix / Windows / troubleshooting

From source (any platform):

git clone --recursive https://github.com/ArtifexSoftware/mupdf.git
cd mupdf && make HAVE_X11=no HAVE_GLUT=no prefix=/usr/local install

Custom install location. The default cgo flags (in mupdf.go) target /opt/homebrew on darwin and the system paths on linux, linking -lmupdf (plus -lmupdf-third on linux). If MuPDF lives elsewhere, supplement via environment variables instead of editing source:

export CGO_CFLAGS="-I/your/prefix/include"
export CGO_LDFLAGS="-L/your/prefix/lib -lmupdf -lmupdf-third"
go build ./...

Windows is not covered by the default flags; build with a MinGW/MSYS2 toolchain and set CGO_CFLAGS / CGO_LDFLAGS to your MuPDF install.

ld: library 'mupdf' not found means MuPDF is not installed or not on the library path — install it or set CGO_LDFLAGS as above.


60-second tour

package main

import (
	"fmt"
	"log"

	"github.com/srijanmukherjee/gomupdf"
)

func main() {
	doc, err := gomupdf.Open("document.pdf")
	if err != nil {
		log.Fatal(err)
	}
	defer doc.Close() // always Close; the finalizer is only a backstop

	// Encrypted? Unlock it (or use OpenWithPassword to do both in one call).
	if doc.NeedsPass() && !doc.Authenticate("secret") {
		log.Fatal("wrong password")
	}

	fmt.Println("pages:", doc.PageCount())

	for i, page := range doc.Pages() { // ranges via iter.Seq2
		text, err := page.GetText()
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("=== page %d ===\n%s\n", i, text)
	}
}

Coordinates. All geometry is in PDF points. The geometry package uses a top-left origin with y growing downward (Rect{X0,Y0,X1,Y1}).


Cookbook

Open anything
// PDF fast paths
doc, _ := gomupdf.Open("file.pdf")                      // from a file
doc, _ := gomupdf.OpenStream(pdfBytes)                  // from memory
doc, _ := gomupdf.OpenWithPassword("file.pdf", "pw")    // open + authenticate
doc, _ := gomupdf.OpenStreamWithPassword(b, "pw")

// Any MuPDF-supported format (XPS, EPUB, MOBI, FB2, CBZ, SVG, TXT, images)
doc, _ := gomupdf.OpenAny("book.epub")                  // format from extension
doc, _ := gomupdf.OpenAnyStream(pngBytes, "png")        // explicit format hint

// Turn a non-PDF (or any) document into a writable PDF
pdf, _ := doc.ConvertToPDF()
defer pdf.Close()

Non-PDF documents open read-only (text, geometry, rendering all work); use ConvertToPDF to get a writable PDF Document.

Text & geometry
text, _   := doc.Text()            // whole document, pages joined by '\f'
pages, _  := doc.TextByPage()      // []string, one per page
lines, _  := doc.AllLines()        // flat lines: soft-hyphens stripped, blanks dropped

words, _  := page.Words()          // word boxes with character-level precision
spans, _  := page.Spans()          // positioned fragments + font name/size
blocks, _ := page.StructuredText() // []Block → []Span tree with bbox & baseline
raw, _    := page.StructuredJSON() // the raw block/line/char JSON, your way

Words is the recommended input for layout work and table reconstruction — the boxes are unions of per-character quads, not span approximations.

Tables

Two strategies: word-alignment (StrategyText, the default) and vector-ruling (StrategyLines, follows drawn gridlines).

tables, _ := page.FindTables() // default word-alignment strategy
tables, _ := page.FindTables(gomupdf.TableSettings{
	Strategy:      gomupdf.StrategyLines,
	SnapTolerance: 3,
})

for _, t := range tables {
	fmt.Println(t.NumRows(), "x", t.NumCols())
	for _, row := range t.Rows {
		fmt.Println(row) // []string cells
	}
}
quads, _ := page.Search("invoice")       // oriented quads (great for highlights)
rects, _ := page.SearchRects("invoice")  // axis-aligned rects
toc, _   := doc.TOC()                     // flat, depth-first outline entries
links, _ := page.Links()                  // clickable rects + target URIs
Render & images
pm, _  := page.Pixmap(gomupdf.PixmapOptions{Zoom: 2.0}) // 144 DPI RGB raster
png, _ := pm.PNG()                                       // encode to PNG bytes
_ = pm.SavePNG("page.png")
img, _ := pm.Image()                                     // a stdlib image.Image
px := pm.Pixel(10, 10)                                   // raw component bytes

infos, _ := page.GetImages()       // each image's placement bbox + source dims
raw, _   := page.ExtractImage(0)   // original encoded bytes (JPEG/PNG/…)
paths, _ := page.GetDrawings()     // vector fill/stroke paths with color & width
Pages, rotation & boxes
n      := doc.PageCount()
page, _ := doc.LoadPage(0)

rot, _  := page.Rotation()           // 0, 90, 180, or 270
_ = page.SetRotation(90)             // multiples of 90, normalized

mb, _ := page.MediaBox()             // full physical page, unrotated points
cb, _ := page.CropBox()              // visible region (defaults to MediaBox)
_ = page.SetCropBox(geometry.Rect{X0: 10, Y0: 10, X1: 400, Y1: 600})
Metadata & page labels
// Read / write the standard info dictionary
meta, _ := doc.Metadata()            // map: title, author, producer, dates, …
_ = doc.SetMetadata(map[string]string{
	"title":  "Quarterly Report",
	"author": "Finance",
	// an empty value clears a field; unknown keys are ignored
})

// XMP packet (Catalog /Metadata stream)
xmp, _ := doc.XMP()
_ = doc.SetXMP(xmlPacket)
_ = doc.DeleteXMP()

// Logical page numbering: front-matter as i, ii, iii then body 1, 2, 3 …
_ = doc.SetPageLabels([]gomupdf.PageLabel{
	{StartPage: 0, Style: gomupdf.LabelRomanLower, Start: 1},
	{StartPage: 2, Style: gomupdf.LabelDecimal, Prefix: "", Start: 1},
})
label, _ := page.Label()             // resolved label, e.g. "ii" or "A-3"
rules, _ := doc.PageLabels()          // read the rules back
Write & assemble
doc, _ := gomupdf.NewPDF()
defer doc.Close()

doc.NewPage(595, 842)                 // A4 in points
p, _ := doc.LoadPage(0)
p.InsertText(72, 800, 12, "Hello, gomupdf")
p.InsertImage(geometry.NewRect(0, 0, 200, 200), imageBytes)

doc.InsertPDF(otherPDFBytes, "")      // append every page of another PDF
doc.DeletePage(3)
Save options
data, _ := doc.SaveBytes(true)                     // quick: serialize (+garbage)
_ = doc.EzSave("out.pdf")                          // sensible defaults to a file

// Fine-grained control
data, _ = doc.SaveBytesWithOptions(gomupdf.SaveOptions{
	Garbage:       3,     // 0–4 dead-object collection
	Deflate:       true,  // compress streams
	Clean:         true,  // sanitize content streams
	Linear:        true,  // "fast web view"
	ASCII:         true,  // escape binary to 7-bit
})

// AES-256 encryption
data, _ = doc.SaveBytesWithOptions(gomupdf.SaveOptions{
	Encrypt: true, UserPassword: "open-me", OwnerPassword: "full", Permissions: -1,
})
data, _ = doc.SaveEncryptedBytes("user", "owner")  // shorthand

// Incremental update (file/stream-opened docs): appends changes after the
// original bytes instead of rewriting the whole file.
_ = doc.SaveIncremental("out.pdf")

API cheat-sheet

Want to… Call
Open a PDF Open · OpenStream · OpenWithPassword
Open EPUB/XPS/image/… OpenAny · OpenAnyStream
Convert to writable PDF doc.ConvertToPDF()
Count / load / iterate pages doc.PageCount · doc.LoadPage · doc.Pages
Extract text doc.Text · page.GetText · page.Lines · page.ExtractText (clip+flags)
Get positioned text page.Words · page.Spans · page.StructuredText · page.RawDict/Dict
Export markup page.HTML · page.XHTML · page.XML
Find tables page.FindTablestable.ToMarkdown / table.Header
Search page.Search · page.SearchRects · page.SearchWith (clip, cap)
Outline / links doc.TOC/SetTOC · page.Links/InsertLink/DeleteLink
Annotate page.AddHighlight/AddFreeText/AddLine/Annotations/DeleteAnnotation
Redact page.AddRedactionpage.ApplyRedactions
Forms page.Widgets · page.SetTextField · page.AddTextField
Page ops doc.CopyPage/MovePage/SelectPages/InsertPDFRange
Draw page.DrawRect/DrawLine/DrawCircle · page.InsertTextbox
Render page.Pixmap(PixmapOptions{DPI,CMYK,Clip…})pm.PNG/JPEG/Save/Image
Pixmap ops pm.Invert · pm.Gamma · pm.Bytes
Fonts page.GetFonts · doc.ExtractFont · NewFont(…).TextLength
Images / drawings page.GetImages · page.ExtractImage · page.GetDrawings
Rotation / boxes page.Rotation/SetRotation · page.MediaBox/CropBox/Set…
Metadata / XMP doc.Metadata/SetMetadata · doc.XMP/SetXMP/DeleteXMP
Page labels doc.PageLabels/SetPageLabels · page.Label
Build / edit NewPDF · doc.NewPage · doc.DeletePage · doc.InsertPDF
Write content page.InsertText · page.InsertImage · page.AddRectAnnot
Save doc.SaveBytes · doc.EzSave · doc.SaveWithOptions · doc.SaveIncremental

Full reference: pkg.go.dev/github.com/srijanmukherjee/gomupdf

Feature support

Legend: ✅ supported · 🟡 partial · ⬜ not yet

Area Capability Status
Read Open PDF (file / stream / password)
Read Open XPS / EPUB / CBZ / SVG / images, convert to PDF
Read Page count, load, iterate
Read Plain & structured text, char-level word boxes
Read dict/rawdict (per-char), HTML / XHTML / XML export
Read Text extraction options (clip rect, stext flags)
Read Geometry primitives (geometry pkg)
Read Text search (quads & rects; region clip + hit cap)
Read Tables — word-alignment & vector-ruling, → Markdown
Structure Outline (TOC) read & write
Structure Page links — read, insert, goto, delete
Structure Page labels, page boxes, rotation
Structure Metadata read/write + XMP
Structure Embedded files, optional-content layers
Render Pixmap → raster (DPI, RGB/Gray/CMYK, clip, annot toggle)
Render Pixmap ops (invert, gamma) + PNG/JPEG/PNM encode & save
Render Extract images + placement bbox
Render Vector drawings / paths
Read Fonts — enumerate, extract embedded program, glyph metrics
Render OCR, image masks
Write New PDF, page insert/delete/copy/move/select, merge & range-merge
Write Insert text, images, word-wrapped text boxes
Write Draw lines / rects / circles
Write Annotations — markup, shapes, ink, free-text, sticky notes
Write Redaction (mark + apply)
Write Form widgets — read, fill, create text fields 🟡 text/checkbox
Write Save options (deflate, clean, linear, ASCII, incremental)
Write AES-256 encryption
Write Digital signatures, full Shape API, OCG layers

gomupdf is actively working toward feature parity with PyMuPDF. The remaining remaining ⬜ items (digital signatures, full form types, OCR, optional-content layers) are on the roadmap.

Concurrency & memory

A Document owns a single native MuPDF context and is not safe for concurrent use; all of its methods are serialized internally by a mutex. To process documents in parallel, open one Document per goroutine.

  • Always Close() a document when done — the finalizer is only a backstop.
  • The in-memory bytes backing a streamed/opened document are held for its lifetime (MuPDF reads from them lazily).
  • C resources are released deterministically in helper functions, so a Go-side mistake cannot leak the underlying objects.

Backends

gomupdf's public API is backend-neutral: every operation that touches a native engine is delegated through an internal interface. The MuPDF (cgo) backend is the default and is compiled in automatically — you don't need to do anything.

Building with -tags nomupdf excludes all cgo (no C toolchain or MuPDF needed to compile); constructors then return a "no backend" error. This build tag is the seam for alternative backends — e.g. a future cgo-free WASM or pure-Go engine slots in under the opposite tag with no change to the public API.

go build ./...                 # default: MuPDF backend
go build -tags nomupdf ./...   # compile with the engine excluded

Subpackages

  • geometry — the 2D primitives (Point, Rect, IRect, Matrix, Quad) used throughout the API, with full affine algebra.
  • experimental — a higher-level, ergonomic layer: lifecycle-managed documents, a row/word model for layout-aware extraction, region and key/value queries (ValueRightOf, ValueBelow), located regex search, and helpers for rendering, image extraction, and merging PDFs/images.

Acknowledgements

  • MuPDF by Artifex Software is the C library that does the heavy lifting — parsing, rendering, and text extraction. gomupdf is a thin Go layer over it; all credit for the underlying PDF engine belongs to the MuPDF authors.
  • PyMuPDF and pdfplumber are the prior art that shaped this library's extraction and table-detection design. Thank you to their authors and maintainers.

License

MuPDF is distributed under the GNU AGPL-3.0, and this package links against it, so the same license applies (see LICENSE). Review its obligations before distributing binaries built with this package.

Documentation

Overview

Package gomupdf is a focused binding for reading, extracting, rendering, and writing PDFs. It exposes a compact API: open a (possibly encrypted) PDF from a file or from memory, authenticate, and pull reading-order text and positioned geometry per page, along with rendering and document-assembly helpers.

The public types here (Document, Page, Font and the result types) are backend-neutral; every operation that touches a native engine is delegated to the interfaces in backend.go. The default engine is MuPDF (cgo), compiled in unless the binary is built with `-tags nomupdf`.

Concurrency: a Document binds one backend and is guarded by a mutex; do not share a Document across goroutines without it. Always Close a Document.

Index

Examples

Constants

View Source
const (
	LabelDecimal    = "D" // 1, 2, 3, …
	LabelRomanUpper = "R" // I, II, III, …
	LabelRomanLower = "r" // i, ii, iii, …
	LabelAlphaUpper = "A" // A, B, C, …, AA, …
	LabelAlphaLower = "a" // a, b, c, …, aa, …
)

Page-label numbering styles, as used in PageLabel.Style. An empty style means the page has no number (prefix only).

Variables

This section is empty.

Functions

This section is empty.

Types

type AnnotStyle added in v1.0.0

type AnnotStyle struct {
	Stroke  *[3]float64 // RGB 0..1 border/line color; nil → black
	Fill    *[3]float64 // RGB 0..1 interior fill color; nil → no fill
	Width   float64     // border width in points; ≤0 → 1
	Opacity float64     // 0..1; ≤0 → 1 (fully opaque)
}

AnnotStyle holds shared styling options for shape and text annotations. The zero value uses sensible defaults: black 1pt stroke, no fill, fully opaque.

type Annotation added in v1.0.0

type Annotation struct {
	Index    int           // 0-based position on the page (use with DeleteAnnotation)
	Type     string        // MuPDF annotation type name, e.g. "Highlight", "Square", "FreeText"
	Rect     geometry.Rect // bounding rect in PDF points
	Contents string        // text contents / note, if any
}

Annotation describes an annotation present on a page.

type Block

type Block struct {
	Type  string // "text" | "image"
	BBox  Rect
	Spans []Span
}

Block is a text or image block containing zero or more spans.

type Char added in v1.0.0

type Char struct {
	Rune   rune           // the Unicode code point
	Origin geometry.Point // glyph origin (baseline start), PDF points
	BBox   geometry.Rect  // glyph bounding box, PDF points
}

Char is a single extracted glyph with its geometry.

type Document

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

Document is an open PDF. Methods are serialized internally; a Document binds one backend. Always Close it.

func NewPDF

func NewPDF() (*Document, error)

NewPDF creates a new, empty PDF document.

func Open

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

Open opens a PDF document from a file path.

Example

Open a PDF and print the reading-order text of every page.

package main

import (
	"fmt"
	"log"

	"github.com/srijanmukherjee/gomupdf"
)

func main() {
	doc, err := gomupdf.Open("document.pdf")
	if err != nil {
		log.Fatal(err)
	}
	defer doc.Close()

	for i, page := range doc.Pages() {
		text, err := page.GetText()
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("page %d:\n%s\n", i, text)
	}
}

func OpenAny added in v1.0.0

func OpenAny(filename string) (*Document, error)

OpenAny opens a document of any MuPDF-supported format, inferring the format from the file extension. Use Open for the PDF-only fast path.

func OpenAnyStream added in v1.0.0

func OpenAnyStream(data []byte, filetype string) (*Document, error)

OpenAnyStream opens in-memory bytes of any MuPDF-supported format. filetype is a format hint — a file extension ("png", "xps", "epub"), a leading-dot extension (".pdf"), or a MIME type. An empty filetype is treated as PDF.

func OpenStream

func OpenStream(pdf []byte) (*Document, error)

OpenStream opens a PDF from in-memory bytes. It does not fail on encryption; the returned Document is left locked (NeedsPass() true) until Authenticate succeeds.

func OpenStreamWithPassword

func OpenStreamWithPassword(pdf []byte, password string) (*Document, error)

OpenStreamWithPassword is OpenWithPassword for in-memory bytes.

func OpenWithPassword

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

OpenWithPassword opens a file and authenticates in one step, returning an error if the password is wrong (QoL over Open + Authenticate).

func (*Document) AllLines

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

AllLines returns every page's Lines concatenated into a single flat line stream across the whole document.

func (*Document) Authenticate

func (d *Document) Authenticate(password string) bool

Authenticate tries a password and returns true if the document is now readable (correct password, or it was never locked).

Example

Open an encrypted PDF, authenticating with a password.

package main

import (
	"fmt"
	"log"

	"github.com/srijanmukherjee/gomupdf"
)

func main() {
	doc, err := gomupdf.Open("encrypted.pdf")
	if err != nil {
		log.Fatal(err)
	}
	defer doc.Close()

	if doc.NeedsPass() && !doc.Authenticate("secret") {
		log.Fatal("wrong password")
	}

	fmt.Println(doc.PageCount())
}

func (*Document) Close

func (d *Document) Close()

Close releases all native resources. Safe to call twice.

func (*Document) ConvertToPDF added in v1.0.0

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

ConvertToPDF renders every page of the document into a freshly assembled PDF and returns it as a new, writable Document. The receiver is left untouched and must still be closed independently. For a document that is already PDF this produces a clean structural copy.

func (*Document) CopyPage added in v1.0.0

func (d *Document) CopyPage(from, to int) error

CopyPage inserts a shallow copy of page from (0-based) so the copy lands at index to (0-based). Use PageCount() as to in order to append at the end. The copy shares the source page's content stream (shallow reference), mirroring PyMuPDF's copy_page behaviour. Returns an error if either index is out of range or the document is closed.

func (*Document) DeletePage

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

DeletePage removes page n (0-based).

func (*Document) DeleteXMP added in v1.0.0

func (d *Document) DeleteXMP() error

DeleteXMP removes the document's XMP metadata stream, if any. It is a no-op when none is present. Changes take effect on the next Save.

func (*Document) ExtractFont added in v1.0.0

func (d *Document) ExtractFont(xref int) (name, ext string, data []byte, err error)

ExtractFont returns an embedded font program by font xref: the BaseFont name, a file extension hint ("ttf", "cff", "otf", "pfa"), and the raw bytes. Returns empty bytes (no error) when the font is not embedded.

func (*Document) EzSave added in v1.0.0

func (d *Document) EzSave(path string) error

EzSave writes the document to a file with DefaultSaveOptions — the convenience path equivalent to PyMuPDF's ez_save.

func (*Document) InsertPDF

func (d *Document) InsertPDF(src []byte, password string) error

InsertPDF appends every page of the source PDF (given as bytes) to this document. password unlocks an encrypted source ("" if none).

func (*Document) InsertPDFRange added in v1.0.0

func (d *Document) InsertPDFRange(src []byte, fromPage, toPage int, password string) error

InsertPDFRange appends pages [fromPage, toPage] (0-based, inclusive) of the source PDF (provided as raw bytes) to the end of this document. password unlocks an encrypted source; pass an empty string if none is needed. fromPage and toPage are clamped to the source's actual page range.

func (*Document) IsEncrypted

func (d *Document) IsEncrypted() bool

IsEncrypted reports whether the PDF was password-protected (stays true even after successful authentication, unlike NeedsPass).

func (*Document) LoadPage

func (d *Document) LoadPage(i int) (*Page, error)

LoadPage returns a handle to page i (0-based). The page is lightweight (it defers to the document on each call); no separate Close is required.

func (*Document) Metadata

func (d *Document) Metadata() (map[string]string, error)

Metadata returns document metadata (title, author, format, …). Absent keys are omitted.

func (*Document) MovePage added in v1.0.0

func (d *Document) MovePage(from, to int) error

MovePage moves page from (0-based) to index to (0-based). After the move the page that was at from will be at to (considering the shift caused by the removal). Returns an error if either index is out of range or the document is closed.

func (*Document) NeedsPass

func (d *Document) NeedsPass() bool

NeedsPass reports whether the document is encrypted and not yet unlocked. Unlike MuPDF's static flag, this flips to false once Authenticate succeeds.

func (*Document) NewPage

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

NewPage appends a blank page of the given size (points).

func (*Document) PageCount

func (d *Document) PageCount() int

PageCount returns the number of pages. Returns 0 if the document is closed or unreadable.

func (*Document) PageLabels added in v1.0.0

func (d *Document) PageLabels() ([]PageLabel, error)

PageLabels returns the document's page-label rules in page order, or nil when the document defines none.

func (*Document) Pages

func (d *Document) Pages() iter.Seq2[int, *Page]

Pages iterates pages in order. Use as:

for i, page := range doc.Pages() { ... }

func (*Document) Save

func (d *Document) Save(path string, garbage bool) error

Save writes the document to a PDF file.

func (*Document) SaveBytes

func (d *Document) SaveBytes(garbage bool) ([]byte, error)

SaveBytes serializes the document to PDF bytes. garbage collects unused objects.

func (*Document) SaveBytesWithOptions added in v1.0.0

func (d *Document) SaveBytesWithOptions(opts SaveOptions) ([]byte, error)

SaveBytesWithOptions serializes the document to PDF bytes using opts.

func (*Document) SaveEncryptedBytes

func (d *Document) SaveEncryptedBytes(userPwd, ownerPwd string) ([]byte, error)

SaveEncryptedBytes serializes the document with AES-256 encryption. userPwd is required to open; ownerPwd grants full permissions (may be "").

func (*Document) SaveIncremental added in v1.0.0

func (d *Document) SaveIncremental(path string) error

SaveIncremental appends pending changes to path using an incremental update. The document must have been opened from a file or stream. It is shorthand for SaveWithOptions with Incremental set.

Incremental save of an in-memory document requires a reasonably recent MuPDF; some older builds cannot relate the output to the original input and return "Cannot derive input stream from output stream".

func (*Document) SaveWithOptions added in v1.0.0

func (d *Document) SaveWithOptions(path string, opts SaveOptions) error

SaveWithOptions writes the document to a PDF file using opts.

func (*Document) SelectPages added in v1.0.0

func (d *Document) SelectPages(pages []int) error

SelectPages rebuilds the document to contain only the given pages, in the given order (0-based indices; may repeat to duplicate pages). This is the fallback implementation — pdf_rearrange_pages is not present in this MuPDF build. Returns an error on invalid indices or a closed document.

func (*Document) SetMetadata added in v1.0.0

func (d *Document) SetMetadata(meta map[string]string) error

SetMetadata writes standard document metadata. Keys use the same short names as Metadata returns ("title", "author", "subject", "keywords", "creator", "producer", "creationDate", "modDate"); unknown keys are ignored. An empty value clears that field. Changes take effect on the next Save.

Writing metadata into a document opened from an existing file requires a reasonably recent MuPDF; some older builds reject it ("not a dict (null)"). Documents created with NewPDF are unaffected.

func (*Document) SetPageLabels added in v1.0.0

func (d *Document) SetPageLabels(labels []PageLabel) error

SetPageLabels installs the document's page-label rules, replacing any existing ones. Rules must be ordered by StartPage and the first rule should start at page 0. Passing nil removes all page labels. Changes take effect on the next Save.

func (*Document) SetTOC added in v1.0.0

func (d *Document) SetTOC(entries []TOCEntry) error

SetTOC replaces the document outline (bookmarks) with the given flat, depth-first entries. Level is 1-based (1 = top level); each entry's Level must be <= previous level + 1. Page is 0-based; out-of-range pages clamp to the nearest valid page. Passing nil removes the outline. Effective on Save.

func (*Document) SetXMP added in v1.0.0

func (d *Document) SetXMP(xml string) error

SetXMP installs xml as the document's XMP metadata packet, replacing any existing one. Changes take effect on the next Save.

func (*Document) TOC

func (d *Document) TOC() ([]TOCEntry, error)

TOC returns the document outline as a flat, depth-first list. Empty if the document has no bookmarks.

func (*Document) Text

func (d *Document) Text() (string, error)

Text returns the full document text, pages separated by a form feed ("\f").

func (*Document) TextByPage

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

TextByPage returns each page's text as a slice.

func (*Document) XMP added in v1.0.0

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

XMP returns the document's XMP metadata packet (the XML in the Catalog's /Metadata stream), or the empty string when the document has none.

type DrawOptions added in v1.0.0

type DrawOptions struct {
	Stroke *[3]float64 // RGB 0..1 stroke color; nil → black
	Fill   *[3]float64 // RGB 0..1 fill color; nil → no fill
	Width  float64     // line width in points; ≤0 → 1
}

DrawOptions styles a drawn primitive.

type Drawing

type Drawing struct {
	Type     string
	Color    [3]float64 // sRGB 0..1
	Width    float64    // stroke width, ctm-scaled (0 for fills)
	LineJoin int
	Alpha    float64
	Items    []PathItem
	Rect     geometry.Rect // bounding box of all points
}

Drawing is one vector path captured from the page. Type is "f" (fill) or "s" (stroke). MuPDF reports fill and stroke of the same path as separate device calls, so each path's fill and stroke are reported as separate entries rather than a single combined entry.

type ExtractedImage

type ExtractedImage struct {
	Ext   string // jpeg | png | jpx | …
	Bytes []byte
}

ExtractedImage is the encoded bytes of an image plus its file extension.

type Font added in v1.0.0

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

Font is a loaded font usable for measuring text. Backed by the active engine; call Close when done (a finalizer is a backstop).

func NewFont added in v1.0.0

func NewFont(name string) (*Font, error)

NewFont loads one of the 14 standard PDF fonts by name (e.g. "Helvetica", "Times-Roman", "Courier", "Helvetica-Bold", "Symbol", "ZapfDingbats").

func (*Font) Advance added in v1.0.0

func (f *Font) Advance(r rune, size float64) float64

Advance returns the horizontal advance of a single rune at the given size.

func (*Font) Ascender added in v1.0.0

func (f *Font) Ascender() float64

Ascender returns the font's ascender as a fraction of the em (×size for points).

func (*Font) Close added in v1.0.0

func (f *Font) Close()

Close releases the underlying font. Safe to call twice.

func (*Font) Descender added in v1.0.0

func (f *Font) Descender() float64

Descender returns the font's descender as a fraction of the em (negative).

func (*Font) Name added in v1.0.0

func (f *Font) Name() string

Name returns the font's name.

func (*Font) TextLength added in v1.0.0

func (f *Font) TextLength(text string, size float64) float64

TextLength returns the rendered width of text at the given font size (points).

type FontInfo added in v1.0.0

type FontInfo struct {
	Xref     int    // PDF object number of the font dictionary (use with ExtractFont)
	Name     string // BaseFont name, e.g. "Helvetica" or "ABCDEE+Calibri"
	Type     string // font Subtype, e.g. "Type1", "TrueType", "Type0"
	Encoding string // /Encoding name if present, else ""
	Embedded bool   // whether a font program is embedded (FontFile/FontFile2/FontFile3)
}

FontInfo describes a font referenced by a page.

type ImageInfo

type ImageInfo struct {
	Index  int
	BBox   geometry.Rect
	Width  int // source image pixel width
	Height int // source image pixel height
	BPC    int // bits per component
	N      int // colorspace components (0 if none)
	Ext    string
}

ImageInfo describes an image placed on a page. BBox is the placement rectangle in page points.

type Link struct {
	Rect geometry.Rect
	URI  string
}

Link is a page link: a clickable rect with a target URI.

type Page

type Page struct {
	Number int // 0-based page index
	// contains filtered or unexported fields
}

Page is a handle to a single page.

func (*Page) AddCircle added in v1.0.0

func (p *Page) AddCircle(r geometry.Rect, style AnnotStyle) error

AddCircle adds a Circle (ellipse) annotation inscribed in rect r.

func (*Page) AddFreeText added in v1.0.0

func (p *Page) AddFreeText(r geometry.Rect, text string, size float64, style AnnotStyle) error

AddFreeText adds a FreeText annotation with the given text and font size.

func (*Page) AddHighlight added in v1.0.0

func (p *Page) AddHighlight(quads []geometry.Quad) error

AddHighlight adds a highlight annotation covering the given quads. Color: yellow. Changes take effect on the next Save.

func (*Page) AddInk added in v1.0.0

func (p *Page) AddInk(strokes [][]geometry.Point, style AnnotStyle) error

AddInk adds a freehand Ink annotation with one or more strokes.

func (*Page) AddLine added in v1.0.0

func (p *Page) AddLine(a, b geometry.Point, style AnnotStyle) error

AddLine adds a Line annotation from a to b on the page.

func (*Page) AddPolygon added in v1.0.0

func (p *Page) AddPolygon(pts []geometry.Point, style AnnotStyle) error

AddPolygon adds a closed Polygon annotation with the given vertices.

func (*Page) AddPolyline added in v1.0.0

func (p *Page) AddPolyline(pts []geometry.Point, style AnnotStyle) error

AddPolyline adds an open PolyLine annotation with the given vertices.

func (*Page) AddRectAnnot

func (p *Page) AddRectAnnot(r geometry.Rect) error

AddRectAnnot adds a rectangle (square) annotation on page i.

func (*Page) AddRedaction added in v1.0.0

func (p *Page) AddRedaction(rect geometry.Rect, opts RedactOptions) error

AddRedaction marks rect for redaction (a redaction annotation). Nothing is removed until ApplyRedactions is called.

func (*Page) AddSquiggly added in v1.0.0

func (p *Page) AddSquiggly(quads []geometry.Quad) error

AddSquiggly adds a squiggly annotation covering the given quads. Color: red. Changes take effect on the next Save.

func (*Page) AddStrikeout added in v1.0.0

func (p *Page) AddStrikeout(quads []geometry.Quad) error

AddStrikeout adds a strikeout annotation covering the given quads. Color: red. Changes take effect on the next Save.

func (*Page) AddTextField added in v1.0.0

func (p *Page) AddTextField(name string, rect geometry.Rect, value string) error

AddTextField creates a text form field named name over rect with an initial value, registering it in the document AcroForm. Effective on Save.

func (*Page) AddTextNote added in v1.0.0

func (p *Page) AddTextNote(at geometry.Point, text string) error

AddTextNote adds a Text (sticky note) annotation at the given point.

func (*Page) AddUnderline added in v1.0.0

func (p *Page) AddUnderline(quads []geometry.Quad) error

AddUnderline adds an underline annotation covering the given quads. Color: red. Changes take effect on the next Save.

func (*Page) Annotations added in v1.0.0

func (p *Page) Annotations() ([]Annotation, error)

Annotations returns the annotations on the page in document order.

func (*Page) ApplyRedactions added in v1.0.0

func (p *Page) ApplyRedactions() (int, error)

ApplyRedactions permanently removes the content under every redaction annotation on the page (text, and images per options), then deletes the redaction marks. Returns the number of redactions applied. Effective on Save.

func (*Page) Bound

func (p *Page) Bound() (geometry.Rect, error)

Bound returns the page's bounding box in points.

func (*Page) CropBox added in v1.0.0

func (p *Page) CropBox() (geometry.Rect, error)

CropBox returns the page's /CropBox — the visible region in unrotated PDF points. When the page declares no CropBox, the MediaBox is returned.

func (*Page) DeleteAnnotation added in v1.0.0

func (p *Page) DeleteAnnotation(index int) error

DeleteAnnotation removes the annotation at the given 0-based index.

func (p *Page) DeleteLink(index int) error

DeleteLink removes the link at the given 0-based index (in Links() order). Changes take effect on the next Save.

func (*Page) Dict added in v1.0.0

func (p *Page) Dict() ([]RawBlock, error)

Dict returns the page's text blocks grouped into font/size spans.

func (*Page) DrawCircle added in v1.0.0

func (p *Page) DrawCircle(center geometry.Point, radius float64, opts DrawOptions) error

DrawCircle approximates a circle with 4 cubic Bézier curves (kappa = 0.5523).

func (*Page) DrawLine added in v1.0.0

func (p *Page) DrawLine(a, b geometry.Point, opts DrawOptions) error

DrawLine draws a line from a to b with the given options.

func (*Page) DrawRect added in v1.0.0

func (p *Page) DrawRect(r geometry.Rect, opts DrawOptions) error

DrawRect draws a rectangle with the given options.

func (*Page) ExtractImage

func (p *Page) ExtractImage(index int) (*ExtractedImage, error)

ExtractImage returns the encoded bytes of the index-th image on the page. Original encoding is preserved when available (e.g. JPEG); uncompressed images are re-encoded as PNG. Returns nil if there is no image at that index.

func (*Page) ExtractText added in v1.0.0

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

ExtractText returns the page's text honoring opts (reading order, lines separated by '\n').

func (*Page) FindTables

func (p *Page) FindTables(opts ...TableSettings) ([]Table, error)

FindTables detects tables on the page. Default strategy is "text" (rulings from word alignment); set Strategy: StrategyLines to derive rulings from the page's vector drawings instead.

func (*Page) GetDrawings

func (p *Page) GetDrawings() ([]Drawing, error)

GetDrawings returns the page's vector drawings.

func (*Page) GetFonts added in v1.0.0

func (p *Page) GetFonts() ([]FontInfo, error)

GetFonts returns the fonts referenced by the page's /Resources /Font dict. The slice is deduplicated by xref (fonts with xref==0 are never deduped).

func (*Page) GetImages

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

GetImages returns the images drawn on the page, in fill order, each with its placement bbox and source dimensions.

func (*Page) GetText

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

GetText returns the page's reading-order plain text.

func (*Page) HTML added in v1.0.0

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

HTML returns the page's structured text as HTML (styled, absolute-positioned). The output mirrors PyMuPDF's page.get_text("html").

func (p *Page) InsertGotoLink(rect geometry.Rect, destPage int) error

InsertGotoLink adds an internal link over rect that jumps to destPage (0-based). Changes take effect on the next Save.

func (*Page) InsertImage

func (p *Page) InsertImage(r geometry.Rect, img []byte) error

InsertImage places an encoded image (jpeg/png/…) into rect r on page i.

func (p *Page) InsertLink(rect geometry.Rect, uri string) error

InsertLink adds a clickable link over rect that opens an external URI. Changes take effect on the next Save.

func (*Page) InsertText

func (p *Page) InsertText(x, y, size float64, text string) error

InsertText draws a line of Helvetica text at (x, y) (baseline) on page i.

func (*Page) InsertTextbox added in v1.0.0

func (p *Page) InsertTextbox(rect geometry.Rect, text string, size float64) (int, error)

InsertTextbox lays out text inside rect with word wrapping (Helvetica, the given size), top-aligned, left-justified, and draws it into the page. Returns the number of lines that fit; text that overflows the rect is clipped.

func (*Page) Label added in v1.0.0

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

Label returns the page's resolved logical label (e.g. "ii" or "A-3"). When the document defines no page labels, it returns the empty string.

func (*Page) Lines

func (p *Page) Lines() ([]string, error)

Lines returns the page's non-empty lines with the soft hyphen (U+00AD) stripped and trailing whitespace trimmed.

func (p *Page) Links() ([]Link, error)

Links returns the page's links.

func (*Page) MediaBox added in v1.0.0

func (p *Page) MediaBox() (geometry.Rect, error)

MediaBox returns the page's /MediaBox — the full physical page rectangle in unrotated PDF points.

func (*Page) Pixmap

func (p *Page) Pixmap(opts ...PixmapOptions) (*Pixmap, error)

Pixmap renders the page with the given options. Resolution precedence: DPI>0 → zoom=DPI/72; else Zoom (≤0 means 1). Colorspace precedence: CMYK → device CMYK; else Gray → device gray; else RGB.

Example

Render the first page to a PNG file at 144 DPI.

package main

import (
	"log"

	"github.com/srijanmukherjee/gomupdf"
)

func main() {
	doc, err := gomupdf.Open("document.pdf")
	if err != nil {
		log.Fatal(err)
	}
	defer doc.Close()

	page, err := doc.LoadPage(0)
	if err != nil {
		log.Fatal(err)
	}
	pm, err := page.Pixmap(gomupdf.PixmapOptions{Zoom: 2.0})
	if err != nil {
		log.Fatal(err)
	}
	if err := pm.SavePNG("page-0.png"); err != nil {
		log.Fatal(err)
	}
}

func (*Page) RawDict added in v1.0.0

func (p *Page) RawDict() ([]RawBlock, error)

RawDict returns the page's text blocks down to per-character geometry.

func (*Page) Rotation added in v1.0.0

func (p *Page) Rotation() (int, error)

Rotation returns the page's display rotation in degrees: one of 0, 90, 180, or 270. The value is normalized into [0, 360).

func (*Page) Search

func (p *Page) Search(needle string) ([]geometry.Quad, error)

Search finds all occurrences of needle on the page and returns their hit quads. Matching is MuPDF's case-insensitive, whitespace-tolerant search. Returns nil if there are no hits.

func (*Page) SearchRects

func (p *Page) SearchRects(needle string) ([]geometry.Rect, error)

SearchRects is Search returning bounding rectangles instead of quads.

func (*Page) SearchWith added in v1.0.0

func (p *Page) SearchWith(needle string, opts SearchOptions) ([]geometry.Quad, error)

SearchWith finds all occurrences of needle on the page like Search, then applies opts: if opts.Clip is non-nil only hits whose bounding rect intersects the clip region are kept, and if opts.MaxHits > 0 at most that many hits are returned. Hits are in page order.

func (*Page) SetCheckbox added in v1.0.0

func (p *Page) SetCheckbox(index int, checked bool) error

SetCheckbox sets the checked state of the checkbox widget at index.

func (*Page) SetCropBox added in v1.0.0

func (p *Page) SetCropBox(r geometry.Rect) error

SetCropBox sets the page's /CropBox. The rectangle is given in unrotated PDF points and is clamped to the MediaBox by MuPDF. Changes take effect on the next Save.

func (*Page) SetMediaBox added in v1.0.0

func (p *Page) SetMediaBox(r geometry.Rect) error

SetMediaBox sets the page's /MediaBox. The rectangle is given in unrotated PDF points. Changes take effect on the next Save.

func (*Page) SetRotation added in v1.0.0

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

SetRotation sets the page's display rotation. deg must be a multiple of 90; it is normalized into [0, 360). Changes take effect on the next Save.

func (*Page) SetTextField added in v1.0.0

func (p *Page) SetTextField(index int, value string) error

SetTextField sets the text value of the widget at index. Errors if it is not a text field.

func (*Page) Spans

func (p *Page) Spans() ([]Span, error)

Spans returns all text spans on the page in document order — the flat positioned-text stream that table reconstruction typically starts from.

func (*Page) StructuredJSON

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

StructuredJSON returns structured text as JSON (blocks → lines → chars, each with bbox). This is the raw geometry feed for layout reconstruction; see Words/Blocks for typed access.

func (*Page) StructuredText

func (p *Page) StructuredText() ([]Block, error)

StructuredText returns the page's blocks and spans with bounding boxes. Spans are positioned text fragments; clustering them by x yields columns and by y yields rows, which is how callers needing exact column geometry reconstruct tables rather than relying on reading-order text.

func (*Page) Widgets added in v1.0.0

func (p *Page) Widgets() ([]Widget, error)

Widgets returns the form fields on the page in document order.

func (*Page) Words

func (p *Page) Words() ([]Word, error)

Words returns the page's words with character-level bounding boxes. These boxes are more precise than the span-split approximations and are the recommended input for FindTables.

func (*Page) XHTML added in v1.0.0

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

XHTML returns the page's structured text as semantic XHTML. The output mirrors PyMuPDF's page.get_text("xhtml").

func (*Page) XML added in v1.0.0

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

XML returns the page's structured text as XML with per-character detail. The output mirrors PyMuPDF's page.get_text("xml").

type PageLabel added in v1.0.0

type PageLabel struct {
	StartPage int    // 0-based page index where this rule begins
	Style     string // one of the Label* constants, or "" for no number
	Prefix    string // literal text placed before the number
	Start     int    // first numeric value for the run (default 1 when < 1)
}

PageLabel is one numbering rule. It takes effect at StartPage (0-based) and applies until the next rule's StartPage. The displayed label for a page is Prefix followed by the page's number rendered in Style, counting from Start.

type PathItem

type PathItem struct {
	Op  string
	Pts []geometry.Point
}

PathItem is one segment of a drawing path:

Op "l"  → line:  Pts[0]→Pts[1]
Op "c"  → bezier: Pts[0] ctrl1, Pts[1] ctrl2, Pts[2] end (relative to prior point)
Op "m"  → moveto: Pts[0]
Op "h"  → closepath (no points)

type Pixmap

type Pixmap struct {
	Width   int
	Height  int
	N       int
	Stride  int
	Alpha   bool
	Samples []byte
}

Pixmap is a rendered raster of a page. Samples is row-major, Stride bytes per row, N components per pixel (1 gray, 2 gray+α, 3 rgb, 4 rgba).

func (*Pixmap) Bytes added in v1.0.0

func (pm *Pixmap) Bytes(format string) ([]byte, error)

Bytes encodes the pixmap in the named format: "png", "jpeg"/"jpg", or "pnm".

func (*Pixmap) Gamma added in v1.0.0

func (pm *Pixmap) Gamma(gamma float64)

Gamma applies gamma correction to color components in place: v' = 255·(v/255)^(1/gamma). gamma ≤ 0 is a no-op. Alpha is preserved.

func (*Pixmap) Image

func (pm *Pixmap) Image() (image.Image, error)

Image converts the pixmap to a standard library image.

func (*Pixmap) Invert added in v1.0.0

func (pm *Pixmap) Invert()

Invert inverts the color components (each → 255−v) in place; alpha is preserved.

func (*Pixmap) JPEG added in v1.0.0

func (pm *Pixmap) JPEG(quality int) ([]byte, error)

JPEG encodes the pixmap as JPEG (quality 1–100). Only gray/RGB pixmaps are supported; returns an error for CMYK.

func (*Pixmap) PNG

func (pm *Pixmap) PNG() ([]byte, error)

PNG encodes the pixmap as PNG bytes.

func (*Pixmap) PNM added in v1.0.0

func (pm *Pixmap) PNM() ([]byte, error)

PNM encodes the pixmap as binary PNM (P5 for gray, P6 for RGB). Alpha and CMYK are not representable; returns an error for CMYK.

func (*Pixmap) Pixel

func (pm *Pixmap) Pixel(x, y int) []byte

Pixel returns the N component bytes at (x, y).

func (*Pixmap) Save added in v1.0.0

func (pm *Pixmap) Save(path string) error

Save writes the pixmap to path, choosing the format from the file extension (.png, .jpg/.jpeg, .pnm). Unknown extensions return an error.

func (*Pixmap) SavePNG

func (pm *Pixmap) SavePNG(path string) error

SavePNG writes the pixmap to a PNG file.

type PixmapOptions

type PixmapOptions struct {
	Zoom     float64        // scale factor (1.0 = 72 DPI); <=0 means 1.0
	Gray     bool           // render in grayscale instead of RGB
	Alpha    bool           // include an alpha channel
	DPI      float64        // if > 0, overrides Zoom (Zoom = DPI/72)
	CMYK     bool           // render in CMYK (4 components); takes precedence over Gray
	Clip     *geometry.Rect // if non-nil, render only this region (PDF points)
	NoAnnots bool           // if true, render page contents only (skip annotations)
}

PixmapOptions controls rendering.

type RawBlock added in v1.0.0

type RawBlock struct {
	BBox  geometry.Rect
	Lines []TextLine // populated by RawDict (per-char detail)
	Spans []TextSpan // populated by Dict (font/size runs)
}

RawBlock is a text block with its lines (rawdict: per-char) or spans (dict).

type Rect

type Rect struct {
	X, Y, W, H float64
}

Rect is a bounding box in PDF points (origin top-left, y grows downward), expressed as a position and size. It is the box type carried by extracted words, spans, and blocks.

func (Rect) CenterY

func (r Rect) CenterY() float64

CenterY returns the vertical midpoint, useful when clustering boxes into rows.

func (Rect) X1

func (r Rect) X1() float64

X1 returns the right edge (X + W).

func (Rect) Y1

func (r Rect) Y1() float64

Y1 returns the bottom edge (Y + H).

type RedactOptions added in v1.0.0

type RedactOptions struct {
	// Fill is the RGB fill (0..1 each) drawn over the redacted area.
	// nil defaults to black {0,0,0}.
	Fill *[3]float64

	// RemoveImages removes images that overlap the redaction region when true.
	RemoveImages bool
}

RedactOptions controls how covered content is removed.

type SaveOptions added in v1.0.0

type SaveOptions struct {
	// Garbage is the dead-object collection level, 0–4:
	//  0 none, 1 collect unreferenced, 2 + compact xref, 3 + merge duplicates,
	//  4 + dedupe identical streams. Out-of-range values are clamped.
	Garbage int

	Deflate       bool // compress uncompressed streams (FlateDecode)
	DeflateImages bool // also recompress image streams
	DeflateFonts  bool // also recompress embedded font streams

	Clean  bool // sanitize and rewrite content streams
	Linear bool // linearize ("fast web view")
	ASCII  bool // emit only ASCII (escape binary)
	Pretty bool // pretty-print PDF objects

	Encrypt       bool   // serialize with AES-256 encryption
	UserPassword  string // required to open (when Encrypt)
	OwnerPassword string // grants full permissions (when Encrypt)
	Permissions   int    // permission bitmask; -1 grants all

	// Incremental appends changes to the original bytes instead of rewriting
	// the whole file. Valid only for documents opened from a file or stream;
	// incompatible with Garbage, Linear, and Encrypt.
	Incremental bool
}

SaveOptions configures how a Document is serialized. The zero value writes an uncompressed, un-garbage-collected PDF; DefaultSaveOptions returns sensible production defaults. Encryption fields are honored only when Encrypt is true.

func DefaultSaveOptions added in v1.0.0

func DefaultSaveOptions() SaveOptions

DefaultSaveOptions returns options suitable for most documents: garbage level 3 (merge duplicates) with stream deflation enabled.

type SearchOptions added in v1.0.0

type SearchOptions struct {
	// Clip, if non-nil, restricts results to quads whose bounding rectangle
	// intersects this region.
	Clip *geometry.Rect

	// MaxHits, if > 0, caps the number of returned hits.
	MaxHits int
}

SearchOptions refines a page search.

type Span

type Span struct {
	Text     string
	BBox     Rect
	OriginX  float64
	OriginY  float64
	FontName string
	FontSize float64
}

Span is a positioned run of text: its text, bounding box, baseline origin, and font.

type TOCEntry

type TOCEntry struct {
	Level int
	Title string
	Page  int
}

TOCEntry is one table-of-contents item: a heading level, its title, and the destination page. Page is 0-based, or -1 for external/unresolved destinations.

type Table

type Table struct {
	BBox Rect
	Rows [][]string
	ColX []float64 // column boundary x-positions (len = cols+1)
	RowY []float64 // row boundary y-positions (len = rows+1)
}

Table is a detected table: a row-major grid of cell strings plus geometry.

func (*Table) Header added in v1.0.0

func (t *Table) Header() []string

Header returns the table's header row (the first row), or nil if the table is empty.

func (*Table) NumCols

func (t *Table) NumCols() int

func (*Table) NumRows

func (t *Table) NumRows() int

NumRows / NumCols.

func (*Table) ToMarkdown added in v1.0.0

func (t *Table) ToMarkdown() string

ToMarkdown renders the table as a GitHub-Flavored-Markdown table. The first row is treated as the header. Cell pipes and newlines are escaped so the output stays a valid single GFM table. Returns "" for an empty table.

type TableSettings

type TableSettings struct {
	Strategy           TableStrategy // text | lines (default text)
	SnapTolerance      float64       // cluster edge coords within this distance
	MinWordsVertical   int           // words sharing an x to form a column ruling
	MinWordsHorizontal int           // words sharing a y to form a row ruling
	IntersectionTol    float64       // edge crossing tolerance
	AlignTolerance     float64       // max deviation for a drawing segment to count as axis-aligned (lines)
}

TableSettings configures table detection; see DefaultTableSettings for the documented defaults.

func DefaultTableSettings

func DefaultTableSettings() TableSettings

DefaultTableSettings returns sensible defaults for table detection.

type TableStrategy

type TableStrategy string

TableStrategy selects how column/row rulings are found.

const (
	StrategyText  TableStrategy = "text"  // rulings from word alignment
	StrategyLines TableStrategy = "lines" // rulings from vector drawings
)

type TextLine added in v1.0.0

type TextLine struct {
	BBox  geometry.Rect
	Chars []Char
}

TextLine is a line of characters within a block.

type TextOptions added in v1.0.0

type TextOptions struct {
	Clip               *geometry.Rect // if non-nil, only text intersecting this rect (PDF points) is returned
	Dehyphenate        bool           // join words split by a soft hyphen at line end
	PreserveWhitespace bool           // keep original whitespace instead of normalizing
	PreserveLigatures  bool           // keep ligatures (fi, fl, …) instead of expanding
	PreserveImages     bool           // keep image placeholders in the output
	InhibitSpaces      bool           // do not synthesize spaces between glyphs
}

TextOptions controls how text is extracted from a page.

type TextSpan added in v1.0.0

type TextSpan struct {
	Font string
	Size float64
	BBox geometry.Rect
	Text string
}

TextSpan groups consecutive chars sharing font and size (PyMuPDF span).

type Widget added in v1.0.0

type Widget struct {
	Index int    // 0-based position among the page's widgets
	Type  string // "text","checkbox","radiobutton","listbox","combobox","signature","button","unknown"
	Name  string // fully-qualified field name
	Value string // current field value
	Rect  geometry.Rect
}

Widget is a form field shown on a page.

type Word

type Word struct {
	Text  string
	BBox  Rect
	Block int
	Line  int
}

Word is a whitespace-delimited word with its character-derived bounding box. BBox is the union of the word's character boxes, giving precise geometry for table reconstruction and column/row clustering.

Directories

Path Synopsis
Package experimental is a question-first layer over gomupdf.
Package experimental is a question-first layer over gomupdf.
Package geometry provides a self-contained 2D geometry toolkit for PDF coordinates: Point, Rect, IRect, Matrix, and Quad.
Package geometry provides a self-contained 2D geometry toolkit for PDF coordinates: Point, Rect, IRect, Matrix, and Quad.

Jump to

Keyboard shortcuts

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