parserails

package module
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: MIT Imports: 42 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

ParseRails

Fast, light, cgo-free document parsing for Go. Spatial text with bounding boxes, Markdown reconstruction, page screenshots, OCR routing and recursive extraction of files inside files — no cloud, no LLM required.

Go Reference CI

ParseRails is the Go counterpart to run-llama/liteparse. It wraps the same engine liteparse uses — Google's PDFium — through klippa-app/go-pdfium, running it in pure-Go WebAssembly (wazero) mode. That means no CGO_ENABLED=1, no native libraries to install in your Docker image, and clean cross-compilation.

Why

Most Go PDF text extractors give you a flat string and lose layout. ParseRails keeps spatial structure — every word with its bounding box, page, and font — which is what downstream RAG, table reconstruction, and LLM-vision pipelines actually need. On top of that it reconstructs the structure those pipelines read: headings, tables and lists as Markdown.

It also handles what arrives around the document. Real input is a scan, or a .docx with a spreadsheet pasted into it, or an invoice attached to an e-mail inside a ZIP — so ParseRails detects formats from their bytes, walks files inside files, and says which pages need OCR before you pay for it.

Features

Capability Engine Status
PDF text + per-word bounding boxes PDFium (WASM) ✅
Word / line granularity, opt-in font size PDFium (WASM) ✅
Page screenshot rendering (RenderPage) PDFium (WASM) ✅
Pluggable OCR + automatic fallback interface ✅
Figure OCR on text pages, merged with native words interface ✅
Standalone images (PNG/JPEG/TIFF/BMP/WebP/GIF) OCR backend ✅
Tesseract OCR adapter (cgo-free, subprocess) tesseract CLI ✅
HTTP OCR adapter (LiteParse OCR API compatible) net/http ✅
Office formats (DOCX/PPTX/XLSX/...) LibreOffice headless → PDF ✅
Native DOCX/XLSX/PPTX reading (no LibreOffice) archive/zip + encoding/xml ✅
Magic-byte format detection (Sniff/Detect) — ✅
Encrypted PDFs, page ranges (ReadOptions) PDFium ✅
Complexity routing (Inspect, is-complex) PDFium ✅
Recursive containers (ZIP/EML/MSG/OLE/attachments) — ✅
Concurrent batch parsing — ✅
Per-document timeouts (WithTimeout) — ✅
CLI: parse/batch/extract/render/is-complex, stdin — ✅
ExtractText whole-page text fast path PDFium ✅
Markdown output (headings, tables, lists, figures) — ✅
Layout blocks as data (Blocks) — ✅
Native cgo backend (-tags parserails_cgo) libpdfium ✅

Choose the right entry point

Task Go CLI
PDF/Office/image text with coordinates ParseData, ParseFile parse --format json
PDF text layer only, without OCR ExtractText, ExtractTextData —
Headings, tables and lists Document.Markdown, Document.Blocks parse --format markdown
DOCX/XLSX/PPTX structure without LibreOffice ReadOfficeDocument parse --native-office --format markdown
Archives, emails and embedded attachments Extract, ExtractFile extract
Independent files in a batch ParseFiles batch
OCR candidates and page screenshots Inspect, RenderPage is-complex, render

For a complete walkthrough with runnable Go code, start with the Usage Guide. The CLI reference lists flags and exit codes.

Install

Requires Go 1.27 or later.

As a library:

go get github.com/promptrails/parserails

As a command:

go install github.com/promptrails/parserails/cmd/parserails@latest

parserails parse      invoice.pdf               # reconstructed text
parserails parse      --format markdown doc.pdf  # headings, tables, lists
parserails parse      --json report.docx         # JSON with boxes
parserails batch      ./corpus ./out             # a directory, concurrently
parserails extract    bundle.zip                 # everything inside a file
parserails is-complex scan.pdf                   # which pages need OCR?
parserails render     --dpi 150 doc.pdf          # page 0 → doc-p0.png

curl -sL https://example.com/report.pdf | parserails parse -

No system dependencies for PDF or native DOCX/XLSX/PPTX text reading. Office page layout and word boxes need libreoffice/soffice on PATH. OCR needs the tesseract binary or a configured HTTP OCR server.

@latest installs a published version. To test the code in a local checkout:

go build -o ./bin/parserails ./cmd/parserails
./bin/parserails parse --native-office --format markdown report.docx

Place CLI flags before positional arguments. --pages selections are 1-based; render --page and result page indexes are 0-based.

Usage

package main

import (
	"context"
	"fmt"
	"os"

	"github.com/promptrails/parserails"
)

func main() {
	p, err := parserails.New() // initializes a pooled PDFium WASM runtime
	if err != nil {
		panic(err)
	}
	defer p.Close()

	pdf, err := os.ReadFile("invoice.pdf")
	if err != nil {
		panic(err)
	}

	doc, err := p.Parse(context.Background(), pdf)
	if err != nil {
		panic(err)
	}

	for _, w := range doc.Words() {
		fmt.Printf("p%d %q [%.1f %.1f %.1f %.1f]\n",
			w.Page, w.Text, w.X0, w.Y0, w.X1, w.Y1)
	}
}
Word
type Word struct {
	Text           string
	Page           int
	X0, Y0, X1, Y1 float64 // bounding box, PDF user-space coordinates
	FontSize       float64 // 0 unless New(WithFontInfo()) is used
	Confidence     float64 // OCR score, 0-1; 0 for natively extracted text
}
Granularity

Word-level boxes are precise but extract every character across the WASM boundary. For per-line boxes at ~6× the speed:

p, _ := parserails.New(parserails.WithGranularity(parserails.GranularityLine))

Markdown & blocks

Structure, reconstructed from the geometry — headings, tables, lists, figures, in reading order:

md := doc.Markdown()

for _, b := range doc.Blocks() {
	fmt.Printf("%-10s p%d %q\n", b.Kind, b.Page, b.Text)
}

For PDF-derived blocks, Go coordinate fields map a heading or table cell back to the page. Use WithFontInfo() and WithImages() to supply heading metrics and figure regions; the CLI enables these for Markdown automatically. Figure links are placeholders, not image files written to disk. See docs/markdown.md.

Does it need OCR?

c, _ := p.Inspect(ctx, data, parserails.ReadOptions{})
if c.NeedsOCR() {
	fmt.Println("pages needing OCR:", c.OCRPages()) // reasons: scanned, garbled, ...
}

A text-layer pass — nothing is rendered, no OCR runs — so a pipeline can route or price a batch for a fraction of a parse. See docs/complexity.md.

Files inside files

node, err := p.ExtractFile(ctx, "bundle.zip", parserails.ExtractOptions{
	MaxFiles: 100,
	MaxBytes: 64 << 20,
})
if err != nil {
	panic(err)
}
node.Walk(func(n *parserails.Node) {
	if n.Err != nil {
		fmt.Fprintf(os.Stderr, "%s: %v\n", n.Name, n.Err)
	}
})
fmt.Println(node.AllText())

PDF attachments, ZIP entries, e-mail and Outlook attachments, OLE objects embedded in office documents — recursively, bounded by depth, file count and unpacked bytes. One unreadable file is recorded on its own node instead of failing the walk. Check every Node.Err before treating the result as complete. Extract returns an inventory/text tree; it does not save the original attachment files. See docs/containers.md.

OCR (pluggable)

Scanned/image-only pages have no extractable text. ParseRails renders those pages and falls back to an OCR backend you provide — automatically:

import "github.com/promptrails/parserails/ocr/tesseract"

p, _ := parserails.New(
	parserails.WithOCR(tesseract.New(tesseract.Config{Lang: "eng"})),
)

The bundled ocr/tesseract adapter shells out to the tesseract binary (no cgo, no libtesseract), and ocr/httpocr talks to a remote server over the LiteParse OCR API, so the OCR server images published for LiteParse (EasyOCR, PaddleOCR, RapidOCR, Surya) work unchanged. Implement the one-method OCR interface for anything else.

WithImageOCR goes further than the fallback: it also reads the figures on pages that do have text — charts, pasted screenshots — and merges the result with the native words.

Screenshots

img, _ := p.RenderPage(ctx, pdf, parserails.RenderRequest{Page: 0, DPI: 150})
png.Encode(out, img) // standard image.Image

Text-only fast path

When you need just the text (RAG ingestion, search indexing) and not boxes, use ExtractText — it uses PDFium's whole-page text API (one call per page) and is several times cheaper than Parse:

text, _ := p.ExtractText(ctx, pdf)        // plain string, no boxes
text, _ = p.ExtractFileText(ctx, "x.docx") // PDF or office doc

The PDF fast path never runs OCR, even with WithOCR configured. Use Parse/ParseData for scanned PDFs and call doc.Text() on the result.

Backends: WASM (default) vs. native cgo

Same API, two build-time backends:

go build .                       # PDFium as WASM — cgo-free, portable (default)
go build -tags parserails_cgo .  # PDFium native — much faster/lighter, needs libpdfium

The default is cgo-free and needs no system libraries. The parserails_cgo backend links libpdfium for far higher throughput on controlled hosts (e.g. a Dockerized worker). parserails.Backend reports which is active. See docs/architecture.md.

Architecture

  • cgo-free by default — PDFium runs as WASM under wazero; opt into the native parserails_cgo backend for maximum throughput.
  • Pooled runtime — instances are reused across requests (PDF parsing is CPU-bound); one pool per process.
  • Layered — domain → parser → ocr → service, mirroring the PromptRails service conventions so it drops cleanly into a standalone parse service.

Benchmarks

ParseRails is benchmarked against ledongthuc/pdf, pdfcpu/pdfcpu, and unidoc/unipdf in benchmark/ — a separate Go module, so those (heavy, partly AGPL/commercial) dependencies never enter this module's graph.

cd benchmark && go test -bench=. -benchmem ./...

ParseRails is the only one of the four that returns per-word bounding boxes; the pure-Go readers are far faster but give flat text only. See benchmark/README.md for numbers and the (important) caveats on what each library actually measures.

Files & batches

doc, _ := p.ParseFile(ctx, "report.docx")           // PDF or office doc
results := p.ParseFiles(ctx, paths, 4)               // concurrent batch

ParseFile converts Office documents to PDF via LibreOffice, then parses. ParseFiles captures errors in each FileResult and preserves input order; pass a positive concurrency value. WithNativeOffice applies to text extraction and the container walk, not these spatial APIs.

For CLI input discovery, output collisions, retries and examples, see Batch Processing.

Limits and partial results

Extraction defaults to depth 8, 512 file attempts and 256 MiB of content, including the root. MaxBytes is not a process memory cap: PDFium materializes PDF attachments before their sizes can be checked. WithTimeout stops the caller waiting for an operation but cannot kill an in-progress PDFium call. Use a context deadline for a whole request spanning multiple operations.

CLI extract can exit successfully with errors on individual nodes. Use tree or JSON output when completeness matters; text output alone omits those errors. See Limits & Timeouts for accounting, cancellation and native Office timeout scope.

Documentation

Full documentation lives in docs/:

The documentation site deploys from main. Feature-branch pages can be read in the checkout or previewed locally as described in Troubleshooting.

Agent skill

SKILL.md is a ready-made skill file for coding agents: which command fits which task, how to route scanned documents, and how to read the output. Copy it into your agent's skills directory.

Examples

Runnable, self-contained examples (each its own module + Dockerfile) live in examples/:

  • extract-text — the basics, fully static cgo-free binary
  • parse-server — HTTP service with OCR + office support
  • native-cgo — native PDFium backend for max throughput

See docs/examples.md.

Status

The PDF core is complete — spatial text, rendering, OCR, office formats, CLI, batch — with both a cgo-free WASM backend and a native parserails_cgo backend. Around it sit the layers a real pipeline needs: format detection, Markdown and block reconstruction, OCR routing, recursive container extraction and native office reading.

See docs/roadmap.md for the detailed status and what is still being considered (ruled-table detection from vector graphics, layout complexity signals, published quality benchmark numbers).

License

MIT © PromptRails

Documentation

Overview

Package parserails reads documents: PDFs, office files, e-mail, archives, and scans, without cgo and without a cloud service.

PDF text comes from Google's PDFium, the engine behind Chrome's PDF viewer, compiled to WebAssembly and run under wazero. Nothing here links C: a ParseRails binary is static, cross-compiles cleanly, and needs no libpdfium in your image. Build with -tags parserails_cgo to link the native library instead, for throughput on a host you control.

ParseRails is the Go counterpart to run-llama/liteparse, and uses the same engine.

Getting started

Create one Parser per process — it owns a pooled runtime and is safe for concurrent use — and give it bytes or a path:

p, err := parserails.New()
if err != nil {
	return err
}
defer p.Close()

doc, err := p.ParseFile(ctx, "invoice.pdf")
if err != nil {
	return err
}
for _, w := range doc.Words() {
	fmt.Printf("p%d %q [%.1f %.1f %.1f %.1f]\n", w.Page, w.Text, w.X0, w.Y0, w.X1, w.Y1)
}

Which entry point

Every one of these takes a context and returns on cancellation:

What comes back

A Document is pages of [Word]s, each with its text, page, bounding box in PDF points, font size and — for recognized text — a confidence. On top of that geometry sit [Line]s, reconstructed by grouping words that share a band, and [Block]s: headings, paragraphs, list items, tables and figures, classified from the layout. Document.Markdown renders those blocks, which is usually what an LLM or a RAG index wants.

Coordinates are PDF user space everywhere: origin bottom-left, units of 1/72 inch.

OCR

Nothing is recognized unless you provide a backend, through WithOCR. A backend implements OCR: an image in, words with pixel-space boxes out, which ParseRails maps back into the page. Two ship with the library — ocr/tesseract shells out to the binary, ocr/httpocr talks to a server over the LiteParse OCR API — and a page with no extractable text falls back to whichever is configured. WithImageOCR additionally reads the figures on pages that do have text.

Files inside files

A real corpus is an invoice attached to an e-mail inside an archive. Parser.Extract walks that: PDF attachments, ZIP entries, e-mail and Outlook attachments, the objects embedded in office documents, and whatever is inside those. The walk is bounded by depth, file count and unpacked bytes, and a file it cannot read becomes a Node carrying the reason rather than failing the walk. WithContainer teaches it a format it does not know.

Office documents without LibreOffice

ReadOfficeDocument reads a DOCX, XLSX or PPTX straight out of the package. There are no page coordinates — nothing has been laid out — but the document's own structure is better than any inference from geometry: heading levels as declared, table cells as authored, spreadsheet rows in their real columns. WithNativeOffice prefers it wherever text rather than geometry is being asked for.

Index

Examples

Constants

View Source
const (
	// ReasonScanned marks a page covered by one raster with no text behind it.
	ReasonScanned = "scanned"
	// ReasonNoText marks a page with almost no extractable text and no
	// full-page image — a blank page, a cover, a divider.
	ReasonNoText = "no-text"
	// ReasonSparseText marks real text that covers very little of the page,
	// typically a figure with a thin caption.
	ReasonSparseText = "sparse-text"
	// ReasonEmbeddedImages marks substantial raster figures next to the text.
	ReasonEmbeddedImages = "embedded-images"
	// ReasonGarbled marks text that decodes to nonsense, usually a broken font
	// encoding, where re-reading the pixels beats trusting the text layer.
	ReasonGarbled = "garbled"
)

Reasons a page is flagged as needing OCR.

View Source
const Backend = "wasm"

Backend identifies the active PDFium backend. This is the default, cgo-free WebAssembly build; build with -tags parserails_cgo for the native backend.

Variables

View Source
var ErrNoLibreOffice = errors.New("parserails: LibreOffice not found")

ErrNoLibreOffice reports that no LibreOffice binary could be found. Office conversion wraps it, so callers can fall back to reading a package natively instead of treating a missing dependency like a broken document.

Functions

func IsOfficeFormat

func IsOfficeFormat(path string) bool

IsOfficeFormat reports whether path has an extension ParseRails converts to PDF via LibreOffice before parsing.

Types

type Block added in v0.2.0

type Block struct {
	Kind           BlockKind `json:"kind"`
	Page           int       `json:"page"`
	X0, Y0, X1, Y1 float64   `json:"-"`

	Text  string `json:"text,omitempty"`  // heading, paragraph, list item
	Level int    `json:"level,omitempty"` // heading depth, 1-6

	Ordered bool   `json:"ordered,omitempty"` // list item
	Marker  string `json:"marker,omitempty"`  // the bullet or number as written

	Header []Cell   `json:"header,omitempty"` // table
	Rows   [][]Cell `json:"rows,omitempty"`

	ID string `json:"id,omitempty"` // figure, e.g. "img_p1_2"
}

Block is a classified region of a page, in reading order.

Blocks are what Document.Markdown output is built from. Taking them as data of as rendered text gives you the same decomposition with the coordinates the classifier used, so a heading or a table cell can be mapped back to the part of the page it came from.

type BlockKind added in v0.2.0

type BlockKind string

BlockKind classifies a region of a page.

const (
	BlockHeading   BlockKind = "heading"
	BlockParagraph BlockKind = "paragraph"
	BlockListItem  BlockKind = "list_item"
	BlockTable     BlockKind = "table"
	BlockFigure    BlockKind = "figure"
)

The block kinds ParseRails reconstructs.

type BlockOptions added in v0.2.0

type BlockOptions struct {
	// KeepHeadersFooters keeps running headers and footers. By default a line
	// that repeats at the top or bottom of most pages is dropped, since it is
	// furniture rather than content.
	KeepHeadersFooters bool
}

BlockOptions tunes block reconstruction.

type Cell added in v0.2.0

type Cell struct {
	Text           string  `json:"text"`
	X0, Y0, X1, Y1 float64 `json:"-"`
}

Cell is one table cell with the region it was read from.

type Child added in v0.2.0

type Child struct {
	Name string
	Data []byte
	Err  error
}

Child is a file found inside another file. Err records a child that was found but could not be taken — a corrupt archive entry, or one that would blow the walk's remaining budget — so it is reported rather than silently missing.

type ChildRequest added in v0.2.0

type ChildRequest struct {
	// Name is the containing file's name, for error messages.
	Name string
	// Password opens an encrypted container (a PDF with attachments).
	Password string
	// MaxFiles and MaxBytes are what remains of the walk's budget. Zero means
	// no limit. A container must not unpack more than this: the walker's own
	// accounting happens after Children returns, which is too late to stop an
	// archive from allocating.
	MaxFiles int
	MaxBytes int64
}

ChildRequest carries what a container needs besides the bytes: how to open the containing file, and how much of the walk's budget is left.

type Complexity added in v0.2.0

type Complexity struct {
	Pages []PageComplexity `json:"pages"`
}

Complexity is what Inspect reports about a document.

func (*Complexity) NeedsOCR added in v0.2.0

func (c *Complexity) NeedsOCR() bool

NeedsOCR reports whether any inspected page needs OCR.

func (*Complexity) OCRPages added in v0.2.0

func (c *Complexity) OCRPages() []int

OCRPages lists the 0-based indexes of the pages that need OCR.

type Container added in v0.2.0

type Container interface {
	// Children returns the files embedded directly in data. It does not
	// recurse: ParseRails walks the tree itself. It should stop within the
	// budget in req, reporting what it skipped as a Child with an Err.
	Children(ctx context.Context, data []byte, req ChildRequest) ([]Child, error)
}

Container yields the files embedded in a document.

Implement it to teach ParseRails a container it does not know — a custom archive, an EDI envelope, a proprietary wrapper — and register it with WithContainer.

type Document

type Document struct {
	Pages []Page `json:"pages"`
}

Document is the result of parsing one input file.

func (*Document) Blocks added in v0.2.0

func (d *Document) Blocks() []Block

Blocks reconstructs the document's structure with the default options.

func (*Document) BlocksWith added in v0.2.0

func (d *Document) BlocksWith(opt BlockOptions) []Block

BlocksWith reconstructs the document's structure: headings, paragraphs, list items, tables and figures, in reading order.

Nothing in a PDF says "this is a heading". The classifier works from the geometry ParseRails already has — line boxes, font sizes, gaps and alignment — so it is fast and deterministic, and wrong on documents whose layout does not follow the usual conventions. Dense tables and unusual layouts are where it frays.

func (*Document) Lines added in v0.2.0

func (d *Document) Lines() []Line

Lines groups every page's words into lines, in page order.

func (*Document) Markdown added in v0.2.0

func (d *Document) Markdown() string

Markdown renders the document as Markdown with the default options.

Example

Markdown renders the blocks ParseRails reconstructs from the layout. Here the larger line becomes a heading and the two aligned rows a table.

package main

import (
	"fmt"

	"github.com/promptrails/parserails"
)

func main() {
	doc := &parserails.Document{Pages: []parserails.Page{{
		Index: 0, Width: 612, Height: 792,
		Words: []parserails.Word{
			{Text: "Revenue", X0: 72, Y0: 720, X1: 200, Y1: 744, FontSize: 24},
			{Text: "Region", X0: 72, Y0: 700, X1: 110, Y1: 711, FontSize: 11},
			{Text: "Total", X0: 220, Y0: 700, X1: 250, Y1: 711, FontSize: 11},
			{Text: "EMEA", X0: 72, Y0: 684, X1: 108, Y1: 695, FontSize: 11},
			{Text: "1.2M", X0: 220, Y0: 684, X1: 248, Y1: 695, FontSize: 11},
		},
	}}}

	fmt.Print(doc.Markdown())
}
Output:
# Revenue

| Region | Total |
| --- | --- |
| EMEA | 1.2M |

func (*Document) MarkdownWith added in v0.2.0

func (d *Document) MarkdownWith(opt BlockOptions) string

MarkdownWith renders the document's reconstructed structure as Markdown: headings, paragraphs, lists, tables and image placeholders, in reading order.

This is the shape LLM and RAG pipelines want — structure a plain-text dump throws away — and it is produced from geometry alone: no model, no network, no layout engine. Complex documents render imperfectly; the [Blocks] decomposition it is built from is available as data when you need to handle those cases yourself.

func (*Document) Text

func (d *Document) Text() string

Text returns the document's text with its line structure reconstructed: words are grouped into lines by geometry, lines are joined with newlines, and pages are separated by a form feed ("\f").

Reading order is top-to-bottom, then left-to-right. Multi-column pages are read line-by-line across the whole page width; use Blocks or Markdown when column structure matters.

Example

Text is built from lines reconstructed out of the word geometry: lines are joined with newlines and pages separated by a form feed.

package main

import (
	"fmt"

	"github.com/promptrails/parserails"
)

func main() {
	doc := &parserails.Document{Pages: []parserails.Page{{
		Index: 0, Width: 612, Height: 792,
		Words: []parserails.Word{
			{Text: "Invoice", X0: 72, Y0: 700, X1: 120, Y1: 712},
			{Text: "2026-03", X0: 124, Y0: 700, X1: 180, Y1: 712},
			{Text: "Total", X0: 72, Y0: 680, X1: 110, Y1: 692},
			{Text: "42.00", X0: 114, Y0: 680, X1: 150, Y1: 692},
		},
	}}}

	fmt.Println(doc.Text())
}
Output:
Invoice 2026-03
Total 42.00

func (*Document) Words

func (d *Document) Words() []Word

Words flattens every page's words into a single slice in reading order.

type ExtractOptions added in v0.2.0

type ExtractOptions struct {
	ReadOptions

	// MaxDepth is how deep to descend. Zero means 8; negative means no limit.
	MaxDepth int
	// MaxFiles caps how many files the walk will open. Zero means 512.
	MaxFiles int
	// MaxBytes caps the total size of the files opened, unpacked. Zero means
	// 256 MiB.
	MaxBytes int64
	// SkipParse collects the tree without parsing each document, which is much
	// cheaper when all you want is an inventory.
	SkipParse bool
}

ExtractOptions tunes an extraction walk.

type FileResult

type FileResult struct {
	Path     string
	Document *Document
	Err      error
}

FileResult pairs a parsed document with its source path and any error.

type Format added in v0.2.0

type Format string

Format identifies a document format. It is what ParseRails routes on: PDFs go straight to PDFium, office documents through LibreOffice, images through OCR, and container formats get unpacked.

const (
	FormatUnknown Format = ""
	FormatPDF     Format = "pdf"

	FormatDOCX Format = "docx"
	FormatXLSX Format = "xlsx"
	FormatPPTX Format = "pptx"
	FormatODT  Format = "odt"
	FormatODS  Format = "ods"
	FormatODP  Format = "odp"
	FormatRTF  Format = "rtf"

	// FormatOLE is the legacy Compound File Binary container behind .doc, .xls,
	// .ppt and .msg. Sniffing bytes alone cannot tell those apart; a filename
	// refines it to one of the four below.
	FormatOLE Format = "ole"
	FormatDOC Format = "doc"
	FormatXLS Format = "xls"
	FormatPPT Format = "ppt"
	FormatMSG Format = "msg"

	FormatPNG  Format = "png"
	FormatJPEG Format = "jpeg"
	FormatGIF  Format = "gif"
	FormatTIFF Format = "tiff"
	FormatBMP  Format = "bmp"
	FormatWEBP Format = "webp"

	FormatZIP  Format = "zip"
	FormatEML  Format = "eml"
	FormatText Format = "txt"
)

The formats ParseRails recognizes.

func Detect added in v0.2.0

func Detect(name string, data []byte) Format

Detect identifies a document's format from its content, using the name only where the bytes are ambiguous (legacy OLE documents) or inconclusive.

Example

Detect prefers what the bytes say, and consults the name only where they are ambiguous: .doc, .xls, .ppt and .msg share one signature.

package main

import (
	"fmt"

	"github.com/promptrails/parserails"
)

func main() {
	compoundFile := []byte{0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1, 0x00}

	fmt.Println(parserails.Detect("letter.doc", compoundFile))
	fmt.Println(parserails.Detect("mail.msg", compoundFile))
	fmt.Println(parserails.Detect("", compoundFile))
}
Output:
doc
msg
ole

func FormatByName added in v0.2.0

func FormatByName(name string) Format

FormatByName maps a file name or path to a format by its extension alone. It returns FormatUnknown for extensions ParseRails does not handle.

func Sniff added in v0.2.0

func Sniff(data []byte) Format

Sniff identifies a format from the leading bytes of a document.

Extensions lie: a `.pdf` that is really a DOCX, an attachment named `invoice.dat`, or a byte slice with no name at all are all routine. Magic bytes do not, so content wins wherever it is conclusive.

Example

Sniff identifies a document from its leading bytes. Extensions lie: a DOCX saved as .pdf, or a byte slice with no name at all, are routine.

package main

import (
	"fmt"

	"github.com/promptrails/parserails"
)

func main() {
	fmt.Println(parserails.Sniff([]byte("%PDF-1.7\n...")))
	fmt.Println(parserails.Sniff([]byte("\x89PNG\r\n\x1a\n")))
	fmt.Println(parserails.Sniff([]byte("BMI,weight\n22,70\n")))
}
Output:
pdf
png
txt

func (Format) Ext added in v0.2.0

func (f Format) Ext() string

Ext returns the conventional file extension for the format, including the leading dot, or "" when it has none.

func (Format) IsImage added in v0.2.0

func (f Format) IsImage() bool

IsImage reports whether the format is a raster image, which ParseRails reads through an OCR backend rather than through PDFium.

func (Format) IsOOXML added in v0.2.0

func (f Format) IsOOXML() bool

IsOOXML reports whether the format is an Office Open XML package (the ZIP + XML formats ParseRails can also read natively, without LibreOffice).

func (Format) IsOffice added in v0.2.0

func (f Format) IsOffice() bool

IsOffice reports whether the format is an office document ParseRails converts to PDF before parsing.

func (Format) String added in v0.2.0

func (f Format) String() string

type Granularity

type Granularity int

Granularity controls how text is segmented into Words.

const (
	// GranularityWord groups individual characters into words split on
	// whitespace; each Word's box is the union of its characters' boxes. This is
	// the most precise mode and the default.
	GranularityWord Granularity = iota

	// GranularityLine returns PDFium's text rectangles (typically line or run
	// fragments) directly. It crosses the Go↔WASM boundary far fewer times, so
	// it is dramatically faster and lighter — at the cost of per-word precision.
	// Use it when line-level boxes are enough (e.g. RAG chunking, search).
	GranularityLine
)

type ImageRegion added in v0.2.0

type ImageRegion struct {
	// Index is the image's position among the page's image objects, so a
	// figure can be named stably across runs (img_p1_2).
	Index          int     `json:"index"`
	X0, Y0, X1, Y1 float64 `json:"-"`
}

ImageRegion is an embedded raster image on a page, with its box in PDF user space (bottom-left origin, points).

func (ImageRegion) Area added in v0.2.0

func (r ImageRegion) Area() float64

Area is the region's area in square points.

type Line added in v0.2.0

type Line struct {
	Page           int     `json:"page"`
	X0, Y0, X1, Y1 float64 `json:"-"`
	Words          []Word  `json:"words"`
}

Line is a horizontal run of words that share a baseline band on one page.

PDFium reports text as characters or rectangles, not as lines: nothing in the extracted stream says where one line ends and the next begins. Line grouping reconstructs that from the geometry, which is what makes text output readable and what every higher-level structure (paragraphs, tables, Markdown) is built on.

func (Line) FontSize added in v0.2.0

func (l Line) FontSize() float64

FontSize reports the most common font size among the line's words, or 0 when the parser did not collect font information.

func (Line) Height added in v0.2.0

func (l Line) Height() float64

Height reports the line's vertical extent in points.

func (Line) Text added in v0.2.0

func (l Line) Text() string

Text joins the line's words with single spaces, in left-to-right order.

type Node added in v0.2.0

type Node struct {
	Name     string    `json:"name"`
	Format   Format    `json:"format"`
	Document *Document `json:"document,omitempty"`
	// Text carries content from formats with no spatial layout of their own —
	// an e-mail body, a plain-text attachment.
	Text     string  `json:"text,omitempty"`
	Children []*Node `json:"children,omitempty"`
	// Err records why this node could not be read. It never aborts the walk:
	// one unreadable attachment should not cost you the other nine.
	Err error `json:"-"`
}

Node is one file in an extraction tree: the document itself, whatever text it carries, and the files found inside it.

func (*Node) AllText added in v0.2.0

func (n *Node) AllText() string

AllText concatenates the text of this node and everything inside it, depth first, in the order the files were found.

func (*Node) Count added in v0.2.0

func (n *Node) Count() int

Count reports how many files the tree holds, including this one.

func (*Node) MarshalJSON added in v0.2.0

func (n *Node) MarshalJSON() ([]byte, error)

MarshalJSON renders the node with its error as a string, so an extraction tree survives a round trip through JSON.

func (*Node) Walk added in v0.2.0

func (n *Node) Walk(fn func(*Node))

Walk calls fn for this node and every node inside it, depth first.

type OCR

type OCR interface {
	// Recognize extracts words with pixel-space bounding boxes from a page image.
	Recognize(ctx context.Context, img image.Image) ([]Word, error)
}

OCR is a pluggable optical-character-recognition backend.

ParseRails calls an OCR backend as a fallback for pages that yield no extractable text (scanned or image-only PDFs): it renders the page to an image and hands it to Recognize.

Coordinate contract: Recognize returns words in the **pixel space of the given image** — origin at the top-left, X to the right, Y downward, in pixels. ParseRails translates those boxes back into PDF user space (bottom-left origin, points) so OCR words are interchangeable with natively extracted ones. This keeps backends simple: they only deal with the image they were handed.

type OfficeDocument added in v0.2.0

type OfficeDocument struct {
	Format Format
	Blocks []Block
}

OfficeDocument is an office document read natively — straight out of the Office Open XML package, with no LibreOffice and no PDF in between.

There is no page geometry here: blocks carry structure and text but no boxes, because nothing has been laid out. What it gives up in coordinates it gains in fidelity and cost — a DOCX says which paragraph is a heading and where a table's cells are, so none of that has to be inferred from positions, and a spreadsheet keeps its real rows instead of a rendering of them.

func ReadOfficeDocument added in v0.2.0

func ReadOfficeDocument(data []byte, format Format) (*OfficeDocument, error)

ReadOfficeDocument reads an OOXML package (DOCX, XLSX, PPTX) directly.

Use it when LibreOffice is not available or not wanted — a scratch container, a lambda, a build with no system dependencies — or when the document's own structure is worth more than its rendered layout. Use Parser.ParseFile when you need coordinates.

Example

ReadOfficeDocument reads an Office Open XML package directly: no LibreOffice, no PDF in between, and the document's own structure instead of one inferred from a layout.

package main

import (
	"archive/zip"
	"bytes"
	"fmt"
	"log"

	"github.com/promptrails/parserails"
)

func main() {
	office, err := parserails.ReadOfficeDocument(docxBytes(), parserails.FormatDOCX)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Print(office.Markdown())
}

// docxBytes builds a minimal DOCX package, so the example above can run.
func docxBytes() []byte {
	var buf bytes.Buffer
	zw := zip.NewWriter(&buf)
	w, err := zw.Create("word/document.xml")
	if err != nil {
		log.Fatal(err)
	}
	if _, err := w.Write([]byte(`<w:document xmlns:w="x"><w:body>` +
		`<w:p><w:pPr><w:pStyle w:val="Title"/></w:pPr><w:r><w:t>Quarterly Report</w:t></w:r></w:p>` +
		`<w:p><w:r><w:t>Revenue grew across every region.</w:t></w:r></w:p>` +
		`</w:body></w:document>`)); err != nil {
		log.Fatal(err)
	}
	if err := zw.Close(); err != nil {
		log.Fatal(err)
	}
	return buf.Bytes()
}
Output:
# Quarterly Report

Revenue grew across every region.

func (*OfficeDocument) Markdown added in v0.2.0

func (o *OfficeDocument) Markdown() string

Markdown renders the document as Markdown.

func (*OfficeDocument) Text added in v0.2.0

func (o *OfficeDocument) Text() string

Text renders the document as plain text.

type Option

type Option func(*config)

Option configures a Parser.

func WithContainer added in v0.2.0

func WithContainer(format Format, c Container) Option

WithContainer registers a Container for a format, replacing the built-in one. It is how you teach ParseRails to unpack something it does not know — or stop it unpacking something it does.

Example

A container yields one level of embedded files; ParseRails walks the tree and applies the limits. Register one for a format it does not know — or replace a built-in.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/promptrails/parserails"
)

func main() {
	p, err := parserails.New(parserails.WithContainer(parserails.FormatZIP, noContainer{}))
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = p.Close() }()

	// Archives are now left unopened.
	node, err := p.Extract(context.Background(), zipBytes, parserails.ExtractOptions{})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(len(node.Children), "children")
}

// noContainer unpacks nothing, which switches extraction off for a format.
type noContainer struct{}

func (noContainer) Children(context.Context, []byte, parserails.ChildRequest) ([]parserails.Child, error) {
	return nil, nil
}

// Stand-ins for documents the examples above would read from disk.
var zipBytes []byte

func WithFontInfo

func WithFontInfo() Option

WithFontInfo collects per-character font size. It is off by default because it roughly doubles extraction cost. Only meaningful with GranularityWord.

func WithGranularity

func WithGranularity(g Granularity) Option

WithGranularity selects how text is segmented into Words (default GranularityWord).

func WithImageOCR added in v0.2.0

func WithImageOCR() Option

WithImageOCR also recognizes the text inside raster figures on pages that do have a text layer, merging it with the native words. Without it, OCR only runs on pages with no extractable text at all.

It costs one page render plus one OCR call per substantial figure, so it is off by default; it needs an OCR backend (WithOCR) to do anything.

Example

WithOCR sets the fallback for pages with no extractable text; WithImageOCR additionally reads the figures on pages that do have some.

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/promptrails/parserails"
	"github.com/promptrails/parserails/ocr/tesseract"
)

func main() {
	p, err := parserails.New(
		parserails.WithOCR(tesseract.New(tesseract.Config{Lang: "eng"})),
		parserails.WithImageOCR(),
		parserails.WithTimeout(30*time.Second),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = p.Close() }()

	doc, err := p.Parse(context.Background(), pdfBytes)
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, w := range doc.Words() {
		if w.IsOCR() && w.Confidence < 0.6 {
			fmt.Printf("low confidence: %q (%.2f)\n", w.Text, w.Confidence)
		}
	}
}

// Stand-ins for documents the examples above would read from disk.
var pdfBytes []byte

func WithImages added in v0.2.0

func WithImages() Option

WithImages records the raster figures on each page (Page.Images), so Markdown output can place them and callers can crop them. It costs one call per page object, so it is off by default; WithImageOCR implies it.

func WithLibreOffice

func WithLibreOffice(path string) Option

WithLibreOffice sets an explicit LibreOffice binary path used to convert office documents (DOCX/PPTX/XLSX/...) to PDF. By default ParseRails looks for the PARSERAILS_SOFFICE env var, then "soffice"/"libreoffice" on PATH.

func WithMaxPages added in v0.2.0

func WithMaxPages(n int) Option

WithMaxPages caps how many pages any single read parses. Zero (the default) means no cap; it can be overridden per read with ReadOptions.MaxPages.

func WithNativeOffice added in v0.2.0

func WithNativeOffice() Option

WithNativeOffice reads Office Open XML packages (DOCX, XLSX, PPTX) directly instead of converting them with LibreOffice, wherever text rather than page geometry is wanted: ExtractTextData, ExtractFileText and the Extract walk.

It removes the LibreOffice dependency for those paths and keeps the document's own structure — real table cells, declared heading levels — at the cost of page coordinates, which a package does not have. Text extraction falls back to it by itself when LibreOffice is missing.

func WithOCR

func WithOCR(o OCR) Option

WithOCR sets the OCR backend used as a fallback for pages with no extractable text. By default no OCR is performed.

func WithPassword added in v0.2.0

func WithPassword(password string) Option

WithPassword sets the default password used to open encrypted documents. It can be overridden per read with ReadOptions.Password.

func WithPoolSize

func WithPoolSize(minIdle, maxIdle, maxTotal int) Option

WithPoolSize tunes the underlying PDFium worker pool.

func WithTimeout added in v0.2.0

func WithTimeout(d time.Duration) Option

WithTimeout caps how long any single document may take. Zero, the default, means no cap.

PDFium cannot be interrupted, so a document that exceeds the timeout is abandoned rather than killed: the call returns, and the worker finishes in the background and releases itself. That is what keeps one pathological file in a batch of ten thousand from stalling the pipeline.

type Page

type Page struct {
	Index  int     `json:"index"`
	Width  float64 `json:"width"`
	Height float64 `json:"height"`
	Words  []Word  `json:"words"`
	// Images are the raster figures drawn on the page. They are only collected
	// when the parser was created with WithImages or WithImageOCR, since
	// enumerating page objects costs a call per object.
	Images []ImageRegion `json:"images,omitempty"`
}

Page holds the words extracted from a single page plus its dimensions.

func (Page) Lines added in v0.2.0

func (p Page) Lines() []Line

Lines groups the page's words into lines in reading order (top to bottom, then left to right).

func (Page) Text added in v0.2.0

func (p Page) Text() string

Text returns the page's text with its line breaks reconstructed.

type PageComplexity added in v0.2.0

type PageComplexity struct {
	Page                 int      `json:"page"` // 0-based page index
	TextLength           int      `json:"text_length"`
	TextCoverage         float64  `json:"text_coverage"`
	ImageCount           int      `json:"image_count"`
	ImageCoverage        float64  `json:"image_coverage"`
	LargestImageCoverage float64  `json:"largest_image_coverage"`
	FullPageImage        bool     `json:"full_page_image"`
	Garbled              bool     `json:"garbled"`
	NeedsOCR             bool     `json:"needs_ocr"`
	Reasons              []string `json:"reasons,omitempty"`
}

PageComplexity is the per-page verdict of Inspect.

type Parser

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

Parser extracts spatial text from documents using a pooled PDFium runtime.

It is safe for concurrent use: each Parse call borrows an instance from the pool and returns it when done. Create one Parser per process and reuse it.

func New

func New(opts ...Option) (*Parser, error)

New initializes a Parser backed by a pure-Go PDFium WebAssembly runtime. No cgo and no system libraries are required. Call Close when finished.

func (*Parser) Close

func (p *Parser) Close() error

Close releases the PDFium runtime and all pooled workers.

func (*Parser) Extract added in v0.2.0

func (p *Parser) Extract(ctx context.Context, data []byte, opt ExtractOptions) (*Node, error)

Extract reads a document and everything inside it: PDF attachments, ZIP entries, e-mail attachments, OLE objects embedded in office documents — and whatever is inside those, recursively.

One unreadable file does not fail the walk; it is recorded on its own node as Err and the rest of the tree is still returned. The walk is bounded by depth, file count and total bytes, and a file that contains itself is visited once.

Example

Extract walks a file and everything inside it. One unreadable attachment is recorded on its own node instead of failing the walk.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/promptrails/parserails"
)

func main() {
	p, err := parserails.New()
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = p.Close() }()

	node, err := p.ExtractFile(context.Background(), "bundle.zip", parserails.ExtractOptions{
		MaxDepth: 4,
		MaxBytes: 64 << 20,
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	node.Walk(func(n *parserails.Node) {
		switch {
		case n.Err != nil:
			fmt.Printf("%s [%s] not read: %v\n", n.Name, n.Format, n.Err)
		case n.Document != nil:
			fmt.Printf("%s [%s] %d page(s)\n", n.Name, n.Format, len(n.Document.Pages))
		}
	})
}

func (*Parser) ExtractFile added in v0.2.0

func (p *Parser) ExtractFile(ctx context.Context, path string, opt ExtractOptions) (*Node, error)

ExtractFile is the file counterpart of Extract.

func (*Parser) ExtractFileText

func (p *Parser) ExtractFileText(ctx context.Context, path string) (string, error)

ExtractFileText is the file counterpart of ExtractText: PDFs are read directly, office documents are converted via LibreOffice first.

func (*Parser) ExtractText

func (p *Parser) ExtractText(ctx context.Context, data []byte) (string, error)

ExtractText returns the plain text of every page, joined by form feeds, with no bounding boxes. It uses PDFium's whole-page text API — one call per page instead of per character — so it is far faster and lighter than Parse. This is the right entry point for text-only needs like RAG ingestion or search indexing, where layout is not required.

Scanned/image-only pages produce no text here; ExtractText does not run OCR (use Parser.Parse with WithOCR for that).

func (*Parser) ExtractTextData added in v0.2.0

func (p *Parser) ExtractTextData(ctx context.Context, data []byte, opt ReadOptions) (string, error)

ExtractTextData is the in-memory counterpart of ExtractText: it detects the format, converts office documents, and honours ReadOptions (password, page selection).

func (*Parser) Inspect added in v0.2.0

func (p *Parser) Inspect(ctx context.Context, data []byte, opt ReadOptions) (*Complexity, error)

Inspect reports, page by page, whether a document needs OCR — before you commit to parsing it.

It is a text-layer pass: page text, the area that text covers, and the raster images drawn on the page. No page is rendered and no OCR runs, so it costs a fraction of a parse. Use it to route documents to a cheap or an expensive pipeline, to reject what you cannot handle, or to price a batch by counting the pages that will actually need OCR.

Example

Inspect is a text-layer pass: no page is rendered and no OCR runs, so a pipeline can route or price a batch for a fraction of a parse.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/promptrails/parserails"
)

func main() {
	p, err := parserails.New()
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = p.Close() }()

	complexity, err := p.Inspect(context.Background(), pdfBytes, parserails.ReadOptions{})
	if err != nil {
		fmt.Println(err)
		return
	}
	if complexity.NeedsOCR() {
		fmt.Println("pages needing OCR:", complexity.OCRPages())
		for _, page := range complexity.Pages {
			if page.NeedsOCR {
				fmt.Printf("  page %d: %v\n", page.Page, page.Reasons)
			}
		}
	}
}

// Stand-ins for documents the examples above would read from disk.
var pdfBytes []byte

func (*Parser) InspectFile added in v0.2.0

func (p *Parser) InspectFile(ctx context.Context, path string) (*Complexity, error)

InspectFile is the file counterpart of Inspect.

func (*Parser) Parse

func (p *Parser) Parse(ctx context.Context, data []byte) (*Document, error)

Parse extracts every page's words with bounding boxes from the given PDF data, using the parser's defaults. Use Parser.ParseData for input that may be in another format, or to select pages and pass a password per call.

Example

Create one Parser per process and reuse it: it owns a pooled PDFium runtime and is safe for concurrent use.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/promptrails/parserails"
)

func main() {
	p, err := parserails.New()
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = p.Close() }()

	doc, err := p.Parse(context.Background(), pdfBytes)
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, w := range doc.Words() {
		fmt.Printf("p%d %q [%.1f %.1f %.1f %.1f]\n", w.Page, w.Text, w.X0, w.Y0, w.X1, w.Y1)
	}
}

// Stand-ins for documents the examples above would read from disk.
var pdfBytes []byte

func (*Parser) ParseData added in v0.2.0

func (p *Parser) ParseData(ctx context.Context, data []byte, opt ReadOptions) (*Document, error)

ParseData parses a document held in memory, detecting its format from the bytes (and, where those are ambiguous, from ReadOptions.Name).

PDFs are parsed directly; office documents are converted with LibreOffice first. Use it when a document arrives over the wire, out of an archive or an e-mail attachment, where there is no path to hand to ParseFile.

Example

ReadOptions carries a password and a page range, so one parser can serve documents that need different ones.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/promptrails/parserails"
)

func main() {
	p, err := parserails.New()
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = p.Close() }()

	doc, err := p.ParseData(context.Background(), sealedPDF, parserails.ReadOptions{
		Name:     "statement.pdf",
		Password: "hunter2",
		Pages:    "1-5,10",
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(len(doc.Pages), "pages read")
}

// Stand-ins for documents the examples above would read from disk.
var sealedPDF []byte

func (*Parser) ParseFile

func (p *Parser) ParseFile(ctx context.Context, path string) (*Document, error)

ParseFile reads and parses a document from disk. PDFs are parsed directly; office documents (DOCX/PPTX/XLSX/...) are first converted to PDF via LibreOffice. The format comes from the file's content, not its extension.

Example

ParseFile detects the format from the file's content, not its extension, and converts office documents through LibreOffice.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/promptrails/parserails"
)

func main() {
	p, err := parserails.New()
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = p.Close() }()

	doc, err := p.ParseFile(context.Background(), "quarterly.docx")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(doc.Text())
}

func (*Parser) ParseFiles

func (p *Parser) ParseFiles(ctx context.Context, paths []string, concurrency int) []FileResult

ParseFiles parses many files concurrently, running up to concurrency parses at once (concurrency <= 0 means len(paths)). Results are returned in the same order as paths; a per-file error is captured in FileResult.Err rather than aborting the batch.

func (*Parser) ParseImage added in v0.2.0

func (p *Parser) ParseImage(ctx context.Context, data []byte) (*Document, error)

ParseImage reads a standalone raster image — a scan, a photo of a receipt, a screenshot — through the configured OCR backend.

There is no PDF and no text layer here, so an OCR backend is required. The result is a one-page Document whose page is the image itself: coordinates are in **pixels**, with the origin flipped to the bottom-left so image words obey the same convention as PDF words.

Example

A scan has no text layer, so reading one needs an OCR backend. The result is a one-page document whose page is the image.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/promptrails/parserails"
	"github.com/promptrails/parserails/ocr/tesseract"
)

func main() {
	p, err := parserails.New(
		parserails.WithOCR(tesseract.New(tesseract.Config{Lang: "eng"})),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = p.Close() }()

	doc, err := p.ParseImage(context.Background(), jpegBytes)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(doc.Text())
}

// Stand-ins for documents the examples above would read from disk.
var jpegBytes []byte

func (*Parser) RenderPage

func (p *Parser) RenderPage(ctx context.Context, data []byte, req RenderRequest) (image.Image, error)

RenderPage rasterizes a single page of the given PDF to an image. It uses the same PDFium runtime as text extraction, so there is no extra dependency and no cgo. Useful for thumbnails, LLM-vision input, or feeding an OCR backend.

type ReadOptions added in v0.2.0

type ReadOptions struct {
	// Name is a file name hint. It is only consulted where the bytes are
	// ambiguous — legacy OLE documents, or content no magic number identifies.
	Name string

	// Password opens an encrypted document. Empty means the parser's default
	// (see WithPassword).
	Password string

	// Pages selects which pages to read, 1-based and inclusive, in the form
	// "1-5,10,15-20". Empty means every page. Pages beyond the end of the
	// document are skipped.
	Pages string

	// MaxPages caps how many pages are read after Pages is applied. Zero means
	// the parser's default (see WithMaxPages); a negative value means no cap.
	MaxPages int
}

ReadOptions tunes a single read: how the input is identified and which parts of it are read. The zero value is valid and means "detect the format from the bytes, read everything".

type RenderRequest

type RenderRequest struct {
	Page     int    // 0-based page index.
	DPI      int    // Render resolution; defaults to 150 when zero.
	Password string // Password for encrypted documents; defaults to WithPassword.
}

RenderRequest describes how to rasterize a single page.

type Word

type Word struct {
	Text string  `json:"text"`
	Page int     `json:"page"`
	X0   float64 `json:"x0"`
	Y0   float64 `json:"y0"`
	X1   float64 `json:"x1"`
	Y1   float64 `json:"y1"`
	// FontSize is the font size in points. It is 0 unless the parser was created
	// with [WithFontInfo] (and [GranularityWord]).
	FontSize float64 `json:"font_size,omitempty"`
	// Confidence is how sure the recognizer is of this word, from 0 to 1. It is
	// 0 for text extracted natively from the PDF, which is not a guess and
	// carries no score; OCR backends that report one set it.
	Confidence float64 `json:"confidence,omitempty"`
}

Word is a single extracted token with its spatial bounding box.

Coordinates are in PDF user space (origin at the bottom-left of the page), matching what the PDFium text engine reports. X0,Y0 is the lower-left corner and X1,Y1 the upper-right corner of the box.

func (Word) IsOCR added in v0.2.0

func (w Word) IsOCR() bool

IsOCR reports whether the word came from an OCR backend rather than from the document's own text layer.

Directories

Path Synopsis
cmd
parserails command
Command parserails is a CLI for the ParseRails document parser.
Command parserails is a CLI for the ParseRails document parser.
ocr
httpocr
Package httpocr is an OCR backend for ParseRails that delegates to a remote HTTP OCR server (EasyOCR, PaddleOCR, RapidOCR, Surya, or your own).
Package httpocr is an OCR backend for ParseRails that delegates to a remote HTTP OCR server (EasyOCR, PaddleOCR, RapidOCR, Surya, or your own).
tesseract
Package tesseract is a cgo-free OCR backend for ParseRails that shells out to the `tesseract` command-line binary.
Package tesseract is a cgo-free OCR backend for ParseRails that shells out to the `tesseract` command-line binary.

Jump to

Keyboard shortcuts

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