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:
- Parser.Parse parses PDF bytes with the parser's defaults.
- Parser.ParseData parses anything, detecting the format from the bytes, and takes ReadOptions for a password or a page range.
- Parser.ParseFile does the same for a path, converting office documents through LibreOffice.
- Parser.ExtractText and Parser.ExtractTextData skip the boxes and use PDFium's whole-page text API, which is several times cheaper.
- Parser.ParseImage reads a scan or a photo through the OCR backend.
- Parser.Inspect reports which pages need OCR before you pay for any.
- Parser.Extract walks a file and everything inside it.
- Parser.RenderPage rasterizes one page.
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 ¶
- Constants
- Variables
- func IsOfficeFormat(path string) bool
- type Block
- type BlockKind
- type BlockOptions
- type Cell
- type Child
- type ChildRequest
- type Complexity
- type Container
- type Document
- type ExtractOptions
- type FileResult
- type Format
- type Granularity
- type ImageRegion
- type Line
- type Node
- type OCR
- type OfficeDocument
- type Option
- func WithContainer(format Format, c Container) Option
- func WithFontInfo() Option
- func WithGranularity(g Granularity) Option
- func WithImageOCR() Option
- func WithImages() Option
- func WithLibreOffice(path string) Option
- func WithMaxPages(n int) Option
- func WithNativeOffice() Option
- func WithOCR(o OCR) Option
- func WithPassword(password string) Option
- func WithPoolSize(minIdle, maxIdle, maxTotal int) Option
- func WithTimeout(d time.Duration) Option
- type Page
- type PageComplexity
- type Parser
- func (p *Parser) Close() error
- func (p *Parser) Extract(ctx context.Context, data []byte, opt ExtractOptions) (*Node, error)
- func (p *Parser) ExtractFile(ctx context.Context, path string, opt ExtractOptions) (*Node, error)
- func (p *Parser) ExtractFileText(ctx context.Context, path string) (string, error)
- func (p *Parser) ExtractText(ctx context.Context, data []byte) (string, error)
- func (p *Parser) ExtractTextData(ctx context.Context, data []byte, opt ReadOptions) (string, error)
- func (p *Parser) Inspect(ctx context.Context, data []byte, opt ReadOptions) (*Complexity, error)
- func (p *Parser) InspectFile(ctx context.Context, path string) (*Complexity, error)
- func (p *Parser) Parse(ctx context.Context, data []byte) (*Document, error)
- func (p *Parser) ParseData(ctx context.Context, data []byte, opt ReadOptions) (*Document, error)
- func (p *Parser) ParseFile(ctx context.Context, path string) (*Document, error)
- func (p *Parser) ParseFiles(ctx context.Context, paths []string, concurrency int) []FileResult
- func (p *Parser) ParseImage(ctx context.Context, data []byte) (*Document, error)
- func (p *Parser) RenderPage(ctx context.Context, data []byte, req RenderRequest) (image.Image, error)
- type ReadOptions
- type RenderRequest
- type Word
Examples ¶
Constants ¶
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.
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 ¶
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 ¶
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 BlockOptions ¶ added in v0.2.0
type BlockOptions struct {
// 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 Child ¶ added in v0.2.0
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
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) Markdown ¶ added in v0.2.0
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 ¶
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
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 ¶
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
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
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
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
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
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
IsOOXML reports whether the format is an Office Open XML package (the ZIP + XML formats ParseRails can also read natively, without LibreOffice).
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
FontSize reports the most common font size among the line's words, or 0 when the parser did not collect font information.
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
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
Count reports how many files the tree holds, including this one.
func (*Node) MarshalJSON ¶ added in v0.2.0
MarshalJSON renders the node with its error as a string, so an extraction tree survives a round trip through JSON.
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
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
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
Output:
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
Output:
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 ¶
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
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 ¶
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
WithPassword sets the default password used to open encrypted documents. It can be overridden per read with ReadOptions.Password.
func WithPoolSize ¶
WithPoolSize tunes the underlying PDFium worker pool.
func WithTimeout ¶ added in v0.2.0
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.
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 ¶
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) Extract ¶ added in v0.2.0
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))
}
})
}
Output:
func (*Parser) ExtractFile ¶ added in v0.2.0
ExtractFile is the file counterpart of Extract.
func (*Parser) ExtractFileText ¶
ExtractFileText is the file counterpart of ExtractText: PDFs are read directly, office documents are converted via LibreOffice first.
func (*Parser) ExtractText ¶
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
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
Output:
func (*Parser) InspectFile ¶ added in v0.2.0
InspectFile is the file counterpart of Inspect.
func (*Parser) Parse ¶
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
Output:
func (*Parser) ParseData ¶ added in v0.2.0
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
Output:
func (*Parser) ParseFile ¶
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())
}
Output:
func (*Parser) ParseFiles ¶
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
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
Output:
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.
Source Files
¶
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. |