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 ¶
- Constants
- type AnnotStyle
- type Annotation
- type Block
- type Char
- type Document
- func NewPDF() (*Document, error)
- func Open(filename string) (*Document, error)
- func OpenAny(filename string) (*Document, error)
- func OpenAnyStream(data []byte, filetype string) (*Document, error)
- func OpenStream(pdf []byte) (*Document, error)
- func OpenStreamWithPassword(pdf []byte, password string) (*Document, error)
- func OpenWithPassword(filename, password string) (*Document, error)
- func (d *Document) AllLines() ([]string, error)
- func (d *Document) Authenticate(password string) bool
- func (d *Document) Close()
- func (d *Document) ConvertToPDF() (*Document, error)
- func (d *Document) CopyPage(from, to int) error
- func (d *Document) DeletePage(n int) error
- func (d *Document) DeleteXMP() error
- func (d *Document) ExtractFont(xref int) (name, ext string, data []byte, err error)
- func (d *Document) EzSave(path string) error
- func (d *Document) InsertPDF(src []byte, password string) error
- func (d *Document) InsertPDFRange(src []byte, fromPage, toPage int, 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) MovePage(from, to int) error
- func (d *Document) NeedsPass() bool
- func (d *Document) NewPage(width, height float64) error
- func (d *Document) PageCount() int
- func (d *Document) PageLabels() ([]PageLabel, error)
- 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) SaveBytesWithOptions(opts SaveOptions) ([]byte, error)
- func (d *Document) SaveEncryptedBytes(userPwd, ownerPwd string) ([]byte, error)
- func (d *Document) SaveIncremental(path string) error
- func (d *Document) SaveWithOptions(path string, opts SaveOptions) error
- func (d *Document) SelectPages(pages []int) error
- func (d *Document) SetMetadata(meta map[string]string) error
- func (d *Document) SetPageLabels(labels []PageLabel) error
- func (d *Document) SetTOC(entries []TOCEntry) error
- func (d *Document) SetXMP(xml string) error
- func (d *Document) TOC() ([]TOCEntry, error)
- func (d *Document) Text() (string, error)
- func (d *Document) TextByPage() ([]string, error)
- func (d *Document) XMP() (string, error)
- type DrawOptions
- type Drawing
- type ExtractedImage
- type Font
- type FontInfo
- type ImageInfo
- type Link
- type Page
- func (p *Page) AddCircle(r geometry.Rect, style AnnotStyle) error
- func (p *Page) AddFreeText(r geometry.Rect, text string, size float64, style AnnotStyle) error
- func (p *Page) AddHighlight(quads []geometry.Quad) error
- func (p *Page) AddInk(strokes [][]geometry.Point, style AnnotStyle) error
- func (p *Page) AddLine(a, b geometry.Point, style AnnotStyle) error
- func (p *Page) AddPolygon(pts []geometry.Point, style AnnotStyle) error
- func (p *Page) AddPolyline(pts []geometry.Point, style AnnotStyle) error
- func (p *Page) AddRectAnnot(r geometry.Rect) error
- func (p *Page) AddRedaction(rect geometry.Rect, opts RedactOptions) error
- func (p *Page) AddSquiggly(quads []geometry.Quad) error
- func (p *Page) AddStrikeout(quads []geometry.Quad) error
- func (p *Page) AddTextField(name string, rect geometry.Rect, value string) error
- func (p *Page) AddTextNote(at geometry.Point, text string) error
- func (p *Page) AddUnderline(quads []geometry.Quad) error
- func (p *Page) Annotations() ([]Annotation, error)
- func (p *Page) ApplyRedactions() (int, error)
- func (p *Page) Bound() (geometry.Rect, error)
- func (p *Page) CropBox() (geometry.Rect, error)
- func (p *Page) DeleteAnnotation(index int) error
- func (p *Page) DeleteLink(index int) error
- func (p *Page) Dict() ([]RawBlock, error)
- func (p *Page) DrawCircle(center geometry.Point, radius float64, opts DrawOptions) error
- func (p *Page) DrawLine(a, b geometry.Point, opts DrawOptions) error
- func (p *Page) DrawRect(r geometry.Rect, opts DrawOptions) error
- func (p *Page) ExtractImage(index int) (*ExtractedImage, error)
- func (p *Page) ExtractText(opts TextOptions) (string, error)
- func (p *Page) FindTables(opts ...TableSettings) ([]Table, error)
- func (p *Page) GetDrawings() ([]Drawing, error)
- func (p *Page) GetFonts() ([]FontInfo, error)
- func (p *Page) GetImages() ([]ImageInfo, error)
- func (p *Page) GetText() (string, error)
- func (p *Page) HTML() (string, error)
- func (p *Page) InsertGotoLink(rect geometry.Rect, destPage int) error
- func (p *Page) InsertImage(r geometry.Rect, img []byte) error
- func (p *Page) InsertLink(rect geometry.Rect, uri string) error
- func (p *Page) InsertText(x, y, size float64, text string) error
- func (p *Page) InsertTextbox(rect geometry.Rect, text string, size float64) (int, error)
- func (p *Page) Label() (string, error)
- func (p *Page) Lines() ([]string, error)
- func (p *Page) Links() ([]Link, error)
- func (p *Page) MediaBox() (geometry.Rect, error)
- func (p *Page) Pixmap(opts ...PixmapOptions) (*Pixmap, error)
- func (p *Page) RawDict() ([]RawBlock, error)
- func (p *Page) Rotation() (int, error)
- func (p *Page) Search(needle string) ([]geometry.Quad, error)
- func (p *Page) SearchRects(needle string) ([]geometry.Rect, error)
- func (p *Page) SearchWith(needle string, opts SearchOptions) ([]geometry.Quad, error)
- func (p *Page) SetCheckbox(index int, checked bool) error
- func (p *Page) SetCropBox(r geometry.Rect) error
- func (p *Page) SetMediaBox(r geometry.Rect) error
- func (p *Page) SetRotation(deg int) error
- func (p *Page) SetTextField(index int, value string) error
- func (p *Page) Spans() ([]Span, error)
- func (p *Page) StructuredJSON() (string, error)
- func (p *Page) StructuredText() ([]Block, error)
- func (p *Page) Widgets() ([]Widget, error)
- func (p *Page) Words() ([]Word, error)
- func (p *Page) XHTML() (string, error)
- func (p *Page) XML() (string, error)
- type PageLabel
- type PathItem
- type Pixmap
- func (pm *Pixmap) Bytes(format string) ([]byte, error)
- func (pm *Pixmap) Gamma(gamma float64)
- func (pm *Pixmap) Image() (image.Image, error)
- func (pm *Pixmap) Invert()
- func (pm *Pixmap) JPEG(quality int) ([]byte, error)
- func (pm *Pixmap) PNG() ([]byte, error)
- func (pm *Pixmap) PNM() ([]byte, error)
- func (pm *Pixmap) Pixel(x, y int) []byte
- func (pm *Pixmap) Save(path string) error
- func (pm *Pixmap) SavePNG(path string) error
- type PixmapOptions
- type RawBlock
- type Rect
- type RedactOptions
- type SaveOptions
- type SearchOptions
- type Span
- type TOCEntry
- type Table
- type TableSettings
- type TableStrategy
- type TextLine
- type TextOptions
- type TextSpan
- type Widget
- type Word
Examples ¶
Constants ¶
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 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 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 OpenAny ¶ added in v1.0.0
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
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 ¶
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) ConvertToPDF ¶ added in v1.0.0
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
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 ¶
DeletePage removes page n (0-based).
func (*Document) DeleteXMP ¶ added in v1.0.0
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
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
EzSave writes the document to a file with DefaultSaveOptions — the convenience path equivalent to PyMuPDF's ez_save.
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) InsertPDFRange ¶ added in v1.0.0
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 ¶
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) MovePage ¶ added in v1.0.0
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 ¶
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) PageLabels ¶ added in v1.0.0
PageLabels returns the document's page-label rules in page order, or nil when the document defines none.
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) 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 ¶
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
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
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
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
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
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
SetXMP installs xml as the document's XMP metadata packet, replacing any existing one. Changes take effect on the next Save.
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 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 ¶
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
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
Advance returns the horizontal advance of a single rune at the given size.
func (*Font) Ascender ¶ added in v1.0.0
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.
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 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
AddFreeText adds a FreeText annotation with the given text and font size.
func (*Page) AddHighlight ¶ added in v1.0.0
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 ¶
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
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
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
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
AddTextNote adds a Text (sticky note) annotation at the given point.
func (*Page) AddUnderline ¶ added in v1.0.0
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
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) CropBox ¶ added in v1.0.0
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
DeleteAnnotation removes the annotation at the given 0-based index.
func (*Page) DeleteLink ¶ added in v1.0.0
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
Dict returns the page's text blocks grouped into font/size spans.
func (*Page) DrawCircle ¶ added in v1.0.0
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 ¶
GetDrawings returns the page's vector drawings.
func (*Page) GetFonts ¶ added in v1.0.0
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 ¶
GetImages returns the images drawn on the page, in fill order, each with its placement bbox and source dimensions.
func (*Page) HTML ¶ added in v1.0.0
HTML returns the page's structured text as HTML (styled, absolute-positioned). The output mirrors PyMuPDF's page.get_text("html").
func (*Page) InsertGotoLink ¶ added in v1.0.0
InsertGotoLink adds an internal link over rect that jumps to destPage (0-based). Changes take effect on the next Save.
func (*Page) InsertImage ¶
InsertImage places an encoded image (jpeg/png/…) into rect r on page i.
func (*Page) InsertLink ¶ added in v1.0.0
InsertLink adds a clickable link over rect that opens an external URI. Changes take effect on the next Save.
func (*Page) InsertText ¶
InsertText draws a line of Helvetica text at (x, y) (baseline) on page i.
func (*Page) InsertTextbox ¶ added in v1.0.0
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
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 ¶
Lines returns the page's non-empty lines with the soft hyphen (U+00AD) stripped and trailing whitespace trimmed.
func (*Page) MediaBox ¶ added in v1.0.0
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)
}
}
Output:
func (*Page) RawDict ¶ added in v1.0.0
RawDict returns the page's text blocks down to per-character geometry.
func (*Page) Rotation ¶ added in v1.0.0
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 ¶
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) SearchWith ¶ added in v1.0.0
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
SetCheckbox sets the checked state of the checkbox widget at index.
func (*Page) SetCropBox ¶ added in v1.0.0
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
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
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
SetTextField sets the text value of the widget at index. Errors if it is not a text field.
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 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.
func (*Page) Widgets ¶ added in v1.0.0
Widgets returns the form fields on the page in document order.
func (*Page) Words ¶
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.
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 ¶
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).
func (*Pixmap) Bytes ¶ added in v1.0.0
Bytes encodes the pixmap in the named format: "png", "jpeg"/"jpg", or "pnm".
func (*Pixmap) Gamma ¶ added in v1.0.0
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) 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
JPEG encodes the pixmap as JPEG (quality 1–100). Only gray/RGB pixmaps are supported; returns an error for CMYK.
func (*Pixmap) PNM ¶ added in v1.0.0
PNM encodes the pixmap as binary PNM (P5 for gray, P6 for RGB). Alpha and CMYK are not representable; returns an error for CMYK.
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.
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 ¶
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
Header returns the table's header row (the first row), or nil if the table is empty.
func (*Table) ToMarkdown ¶ added in v1.0.0
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 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
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.
Source Files
¶
- annotations.go
- annotations_mupdf.go
- annotations_shapes.go
- annotations_shapes_mupdf.go
- backend.go
- draw.go
- drawings.go
- font_metrics.go
- fonts.go
- fonts_mupdf.go
- images.go
- links_write.go
- links_write_mupdf.go
- metadata_write.go
- metadata_write_mupdf.go
- mupdf.go
- mupdf_backend.go
- mupdf_read_mupdf.go
- mupdf_write_mupdf.go
- open_any.go
- open_any_mupdf.go
- outline.go
- page_labels.go
- page_labels_mupdf.go
- page_ops.go
- page_ops_mupdf.go
- pagebox.go
- pagebox_mupdf.go
- pixmap.go
- pixmap_ops.go
- pixmap_render.go
- pixmap_render_mupdf.go
- rawdict.go
- rawdict_mupdf.go
- rect.go
- redaction.go
- redaction_mupdf.go
- save_options.go
- save_options_mupdf.go
- search.go
- search_options.go
- tables.go
- tables_markdown.go
- text.go
- text_export.go
- text_export_mupdf.go
- text_options.go
- text_options_mupdf.go
- toc_write.go
- toc_write_mupdf.go
- widgets.go
- widgets_mupdf.go
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. |