Documentation
¶
Overview ¶
Package gomupdf is a focused cgo binding over the MuPDF C core (https://mupdf.com/core) 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.
MuPDF + cgo discipline (the four rules):
- fz_try/fz_catch use setjmp/longjmp. A longjmp must NEVER cross the cgo→Go boundary, so every throwing fz_* call is wrapped inside a C helper that does fz_try/fz_catch and returns an error string to Go.
- fz_context is not thread-safe. Each Document owns its own context and is guarded by a mutex; do not share a Document across goroutines without it.
- All MuPDF objects are explicitly dropped (fz_drop_*); the C helpers clean up in fz_always so a Go-side mistake cannot leak.
- The in-memory PDF bytes backing fz_open_memory are NOT copied by MuPDF, so we hold a C-allocated copy alive for the Document's whole lifetime.
Index ¶
- type Block
- type Document
- func (d *Document) AllLines() ([]string, error)
- func (d *Document) Authenticate(password string) bool
- func (d *Document) Close()
- func (d *Document) DeletePage(n int) error
- func (d *Document) InsertPDF(src []byte, password string) error
- func (d *Document) IsEncrypted() bool
- func (d *Document) LoadPage(i int) (*Page, error)
- func (d *Document) Metadata() (map[string]string, error)
- func (d *Document) NeedsPass() bool
- func (d *Document) NewPage(width, height float64) error
- func (d *Document) PageCount() int
- func (d *Document) Pages() iter.Seq2[int, *Page]
- func (d *Document) Save(path string, garbage bool) error
- func (d *Document) SaveBytes(garbage bool) ([]byte, error)
- func (d *Document) SaveEncryptedBytes(userPwd, ownerPwd string) ([]byte, error)
- func (d *Document) TOC() ([]TOCEntry, error)
- func (d *Document) Text() (string, error)
- func (d *Document) TextByPage() ([]string, error)
- type Drawing
- type ExtractedImage
- type ImageInfo
- type Link
- type Page
- func (p *Page) AddRectAnnot(r geometry.Rect) error
- func (p *Page) Bound() (geometry.Rect, error)
- func (p *Page) ExtractImage(index int) (*ExtractedImage, error)
- func (p *Page) FindTables(opts ...TableSettings) ([]Table, error)
- func (p *Page) GetDrawings() ([]Drawing, error)
- func (p *Page) GetImages() ([]ImageInfo, error)
- func (p *Page) GetText() (string, error)
- func (p *Page) InsertImage(r geometry.Rect, img []byte) error
- func (p *Page) InsertText(x, y, size float64, text string) error
- func (p *Page) Lines() ([]string, error)
- func (p *Page) Links() ([]Link, error)
- func (p *Page) Pixmap(opts ...PixmapOptions) (*Pixmap, error)
- func (p *Page) Search(needle string) ([]geometry.Quad, error)
- func (p *Page) SearchRects(needle string) ([]geometry.Rect, error)
- func (p *Page) Spans() ([]Span, error)
- func (p *Page) StructuredJSON() (string, error)
- func (p *Page) StructuredText() ([]Block, error)
- func (p *Page) Words() ([]Word, error)
- type PathItem
- type Pixmap
- type PixmapOptions
- type Rect
- type Span
- type TOCEntry
- type Table
- type TableSettings
- type TableStrategy
- type Word
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Document ¶
type Document struct {
// contains filtered or unexported fields
}
Document is an open PDF. Methods are serialized internally; a Document binds one MuPDF context. Always Close it.
func Open ¶
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)
}
}
Output:
func OpenStream ¶
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 ¶
OpenStreamWithPassword is OpenWithPassword for in-memory bytes.
func OpenWithPassword ¶
OpenWithPassword opens a file and authenticates in one step, returning an error if the password is wrong (QoL over Open + Authenticate).
func (*Document) AllLines ¶
AllLines returns every page's Lines concatenated into a single flat line stream across the whole document.
func (*Document) Authenticate ¶
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())
}
Output:
func (*Document) Close ¶
func (d *Document) Close()
Close releases all native resources. Safe to call twice.
func (*Document) DeletePage ¶
DeletePage removes page n (0-based).
func (*Document) InsertPDF ¶
InsertPDF appends every page of the source PDF (given as bytes) to this document. password unlocks an encrypted source ("" if none).
func (*Document) IsEncrypted ¶
IsEncrypted reports whether the PDF was password-protected (stays true even after successful authentication, unlike NeedsPass).
func (*Document) LoadPage ¶
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 ¶
Metadata returns document metadata (title, author, format, …). Absent keys are omitted.
func (*Document) NeedsPass ¶
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) PageCount ¶
PageCount returns the number of pages. Returns 0 if the document is closed or unreadable.
func (*Document) Pages ¶
Pages iterates pages in order. Use as:
for i, page := range doc.Pages() { ... }
func (*Document) SaveBytes ¶
SaveBytes serializes the document to PDF bytes. garbage collects unused objects.
func (*Document) SaveEncryptedBytes ¶
SaveEncryptedBytes serializes the document with AES-256 encryption. userPwd is required to open; ownerPwd grants full permissions (may be "").
func (*Document) TOC ¶
TOC returns the document outline as a flat, depth-first list. Empty if the document has no bookmarks.
func (*Document) TextByPage ¶
TextByPage returns each page's text as a slice.
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 ¶
ExtractedImage is the encoded bytes of an image plus its file extension.
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 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) AddRectAnnot ¶
AddRectAnnot adds a rectangle (square) annotation on page i.
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) 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 ¶
GetDrawings returns the page's vector drawings.
func (*Page) GetImages ¶
GetImages returns the images drawn on the page, in fill order, each with its placement bbox and source dimensions.
func (*Page) InsertImage ¶
InsertImage places an encoded image (jpeg/png/…) into rect r on page i.
func (*Page) InsertText ¶
InsertText draws a line of Helvetica text at (x, y) (baseline) on page i.
func (*Page) Lines ¶
Lines returns the page's non-empty lines with the soft hyphen (U+00AD) stripped and trailing whitespace trimmed.
func (*Page) Pixmap ¶
func (p *Page) Pixmap(opts ...PixmapOptions) (*Pixmap, error)
Pixmap renders the page.
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)
}
}
Output:
func (*Page) Search ¶
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 ¶
SearchRects is Search returning bounding rectangles instead of quads.
func (*Page) Spans ¶
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 ¶
StructuredJSON returns MuPDF 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 ¶
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.
type PathItem ¶
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 ¶
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).
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
}
PixmapOptions controls rendering.
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.
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 ¶
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.
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 )
Source Files
¶
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. |