Skip to content

Getting Started with PDF Oxide (Go)

PDF Oxide is the fastest Go PDF library — 0.8ms mean text extraction, 5× faster than PyMuPDF, 15× faster than pypdf, 100% pass rate on 3,830 PDFs. One module for extracting, creating, and editing PDFs. Goroutine-safe reads via sync.RWMutex. MIT / Apache-2.0 licensed.

Installation

go get github.com/yfedoseev/pdf_oxide/go
go run github.com/yfedoseev/pdf_oxide/go/cmd/install@latest

Requirements: Go 1.21+ with CGo enabled (CGO_ENABLED=1, the default).

Since v0.3.31 the native FFI archive is downloaded on demand rather than committed to the module. The install command fetches the matching platform tarball (~26 MB) into ~/.pdf_oxide/v<version>/, SHA-256 verifies it against the published .sha256, and prints the CGO_CFLAGS / CGO_LDFLAGS to export. Pass --write-flags=<dir> to emit a cgo_flags.go next to your code instead of exporting env vars. Run once per machine — @latest auto-resolves to the matching release via runtime/debug.ReadBuildInfo.

The binding links the Rust core as a static library, so the resulting Go binary is fully self-contained — no LD_LIBRARY_PATH, DYLD_LIBRARY_PATH, or PATH configuration required at runtime. Just go build and ship.

Monorepo / source-tree builds: add -tags pdf_oxide_dev to point CGo at a local target/release/libpdf_oxide.a — no installer needed.

Upgrading from v0.3.30 or earlier: the committed go/lib/ native archives are gone. A first go build after the upgrade will fail at link time (undefined reference to pdf_document_open ...) until go run github.com/yfedoseev/pdf_oxide/go/cmd/install@latest runs once and the printed CGO_* vars are exported (or written via --write-flags).

Prebuilt platform matrix: Linux x64/arm64, macOS x64/arm64 (Apple Silicon), Windows x64 (via x86_64-pc-windows-gnu).

Opening a PDF

package main

import (
    "fmt"
    "log"

    pdfoxide "github.com/yfedoseev/pdf_oxide/go"
)

func main() {
    doc, err := pdfoxide.Open("research-paper.pdf")
    if err != nil {
        log.Fatal(err)
    }
    defer doc.Close()

    count, _ := doc.PageCount()
    major, minor, _ := doc.Version()
    fmt.Printf("%d pages, PDF %d.%d\n", count, major, minor)
}

Page API

Since v0.3.34 you can work page-first. doc.Page(i) returns a lightweight *Page handle that dispatches to the parent document.

page, _ := doc.Page(0)
text, _ := page.Text()
md, _   := page.Markdown()

pages, _ := doc.Pages()
for _, p := range pages {
    t, _ := p.Text()
    fmt.Printf("--- Page %d ---\n%s\n", p.Index+1, t)
}

Each Page exposes Text(), Markdown(), Html(), PlainText(), Chars(), Words(), Lines(), Tables(), Images(), Paths(), Fonts(), Annotations(), Info(), Search(), NeedsOcr(), and TextWithOcr().

Text Extraction

Single Page

text, err := doc.ExtractText(0)
if err != nil {
    log.Fatal(err)
}
fmt.Println(text)

All Pages

allText, err := doc.ExtractAllText()
if err != nil {
    log.Fatal(err)
}
fmt.Println(allText)

Walk Pages Manually

pages, _ := doc.Pages()
for _, p := range pages {
    text, err := p.Text()
    if err != nil {
        log.Printf("page %d: %v", p.Index, err)
        continue
    }
    fmt.Printf("--- Page %d ---\n%s\n", p.Index+1, text)
}

Structured Extraction

words, _  := doc.ExtractWords(0)        // []Word
lines, _  := doc.ExtractTextLines(0)    // []TextLine
chars, _  := doc.ExtractChars(0)        // []Char
tables, _ := doc.ExtractTables(0)       // []Table — rows + cells with bboxes (v0.3.34)
paths, _  := doc.ExtractPaths(0)        // []Path

for _, w := range words {
    fmt.Printf("%q at (%.1f, %.1f)\n", w.Text, w.X, w.Y)
}

for _, t := range tables {
    fmt.Printf("%dx%d (header=%v)\n", t.RowCount, t.ColCount, t.HasHeader)
    for r := 0; r < t.RowCount; r++ {
        for c := 0; c < t.ColCount; c++ {
            fmt.Printf("%s\t", t.CellText(r, c))
        }
        fmt.Println()
    }
}

Region-based extraction:

region, _ := doc.ExtractTextInRect(0, 50, 700, 200, 50) // x, y, w, h
words, _  := doc.ExtractWordsInRect(0, 50, 700, 200, 50)

Markdown Conversion

md, err := doc.ToMarkdown(0)
if err != nil {
    log.Fatal(err)
}
fmt.Println(md)

// All pages
allMd, _ := doc.ToMarkdownAll()

HTML Conversion

html, _  := doc.ToHtml(0)
allHtml, _ := doc.ToHtmlAll()

Image Extraction

import "os"

images, err := doc.Images(0)
if err != nil {
    log.Fatal(err)
}

for i, img := range images {
    fmt.Printf("Image %d: %dx%d %s %s %dbpc (%d bytes)\n",
        i, img.Width, img.Height, img.Format, img.Colorspace, img.BitsPerComponent, len(img.Data))
    os.WriteFile(fmt.Sprintf("image_%d.%s", i, img.Format), img.Data, 0644)
}

Opening from Bytes and Readers

// From bytes
data, _ := os.ReadFile("document.pdf")
doc, err := pdfoxide.OpenFromBytes(data)

// From any io.Reader
doc, err := pdfoxide.OpenReader(someReader)

// With password
doc, err := pdfoxide.OpenWithPassword("secure.pdf", "user-password")

PDF Creation

// From Markdown
pdf, _ := pdfoxide.FromMarkdown("# Hello\n\nBody text.")
defer pdf.Close()
pdf.Save("out.pdf")

// From HTML
htmlPdf, _ := pdfoxide.FromHtml("<h1>Invoice</h1><p>Amount: $42</p>")
defer htmlPdf.Close()
htmlPdf.Save("invoice.pdf")

// From text
txt, _ := pdfoxide.FromText("Plain text document.")
defer txt.Close()

// From image
img, _ := pdfoxide.FromImage("photo.jpg")
defer img.Close()

// Merge several PDFs
merged, _ := pdfoxide.Merge([]string{"a.pdf", "b.pdf"})
os.WriteFile("merged.pdf", merged, 0644)

Rendering

// Format: 0 = PNG, 1 = JPEG
img, err := doc.RenderPage(0, 0)
if err != nil {
    log.Fatal(err)
}
defer img.Close()
img.SaveToFile("page.png")

// Zoom (2x)
zoomed, _ := doc.RenderPageZoom(0, 2.0, 0)
defer zoomed.Close()

// Thumbnail (200px width)
thumb, _ := doc.RenderThumbnail(0, 200, 0)
defer thumb.Close()
// Search all pages (case-insensitive)
hits, _ := doc.SearchAll("configuration", false)
for _, r := range hits {
    fmt.Printf("page %d: %q at (%.0f, %.0f)\n", r.Page, r.Text, r.X, r.Y)
}

// Search one page
pageHits, _ := doc.SearchPage(0, "configuration", false)

Editing

Use DocumentEditor for metadata, page operations, annotations, and forms:

editor, err := pdfoxide.OpenEditor("in.pdf")
if err != nil {
    log.Fatal(err)
}
defer editor.Close()

// Metadata — one field at a time
_ = editor.SetTitle("Quarterly Report")
_ = editor.SetAuthor("Finance Team")

// Or apply several fields at once
_ = editor.ApplyMetadata(pdfoxide.Metadata{
    Title:   "Q1 2026 Report",
    Author:  "Finance Team",
    Subject: "Results",
})

// Page operations
_ = editor.SetPageRotation(0, 90)
_ = editor.MovePage(2, 0)
_ = editor.DeletePage(5)

// Forms
_ = editor.SetFormFieldValue("employee.name", "Jane Doe")
_ = editor.FlattenForms()

// Save
_ = editor.Save("out.pdf")
_ = editor.SaveEncrypted("secret.pdf", "user", "owner")

Barcodes

qr, _ := pdfoxide.GenerateQRCode("https://example.com", 0, 256)
defer qr.Close()
_ = os.WriteFile("qr.png", qr.PNGData(), 0644)

bc, _ := pdfoxide.GenerateBarcode("123456789", 0, 128)
defer bc.Close()

OCR

Build with the ocr feature to enable OCR on scanned pages:

go build -tags ocr ./...
ocr, _ := pdfoxide.NewOcrEngine()
defer ocr.Close()

if ocr.NeedsOcr(doc, 0) {
    text, _ := ocr.ExtractTextWithOcr(doc, 0)
    fmt.Println(text)
}

See the OCR guide for complete recipes.

Concurrency

PdfDocument reads are goroutine-safe — multiple goroutines can share a single document for parallel page extraction:

import "sync"

var wg sync.WaitGroup
count, _ := doc.PageCount()
out := make(chan string, count)

for i := 0; i < count; i++ {
    wg.Add(1)
    go func(page int) {
        defer wg.Done()
        text, err := doc.ExtractText(page)
        if err == nil {
            out <- text
        }
    }(i)
}

go func() { wg.Wait(); close(out) }()

for text := range out {
    _ = text
}

DocumentEditor serializes writes internally, but don’t pipeline independent edits from multiple goroutines — collect changes on one goroutine. See the concurrency guide for patterns.

Error Handling

import "errors"

text, err := doc.ExtractText(0)
if err != nil {
    switch {
    case errors.Is(err, pdfoxide.ErrDocumentClosed):
        log.Print("document is closed")
    case errors.Is(err, pdfoxide.ErrInvalidPageIndex):
        log.Print("invalid page index")
    case errors.Is(err, pdfoxide.ErrExtractionFailed):
        log.Print("extraction failed")
    default:
        log.Printf("unexpected: %v", err)
    }
}

Available sentinel errors:

ErrInvalidPath        ErrDocumentNotFound   ErrInvalidFormat
ErrExtractionFailed   ErrParseError         ErrInvalidPageIndex
ErrSearchFailed       ErrInternal           ErrDocumentClosed
ErrEditorClosed       ErrCreatorClosed      ErrIndexOutOfBounds
ErrEmptyContent

Extract the numeric Code and Message with errors.As:

var e *pdfoxide.Error
if errors.As(err, &e) {
    fmt.Printf("code=%d message=%s\n", e.Code, e.Message)
}

Next Steps