Documentation
¶
Overview ¶
Package pdf extracts text and direction-aware glyph geometry from PDF files.
Extract returns per-page glyph quads and baselines; Page.Text reconstructs plain text by clustering direction-compatible glyphs into lines and inserting word spacing derived from glyph gaps and font metrics.
The package is pure Go with no external dependencies. It implements the PDF object layer (cross-reference tables and streams, object streams, stream filters, and password-aware standard-handler decryption) natively per ISO 32000, and on top of it a content-stream lexer, interpreter, and font decoder tuned for real-world files: it descends into Form XObjects (where e.g. Google Docs exports keep their text), honors /ToUnicode even alongside an /Encoding dictionary, tracks positions through every text operator, honors tagged-PDF replacement text, never loops on tokens straddling /Contents array segments, and reports bounded partial extraction caused by decompression bombs, stalled filter chains, or work limits.
Index ¶
- Variables
- type Annotation
- type CMapResolver
- type Destination
- type Document
- type FormField
- type Glyph
- type LayoutMode
- type LayoutOptions
- type Limits
- type Line
- type Metadata
- type OCR
- type OCRFunc
- type OCRRequest
- type Options
- type Outline
- type Page
- type PageRange
- type Point
- type Quad
- type Rect
- type StrictError
- type Warning
- type WarningCode
Constants ¶
This section is empty.
Variables ¶
var ErrPasswordRequired = crypt.ErrPasswordRequired
ErrPasswordRequired reports that an encrypted document could not be unlocked with the supplied password.
Functions ¶
This section is empty.
Types ¶
type Annotation ¶ added in v0.3.0
type Annotation struct {
Subtype string
Rect Rect
Contents string
Title string
URL string
Destination Destination
}
Annotation contains text-bearing annotation and link information.
type CMapResolver ¶ added in v0.3.0
CMapResolver supplies a named predefined CMap that is not built into the package. The returned bytes use normal PDF CMap syntax.
type Destination ¶ added in v0.3.0
Destination identifies a named destination or a destination on a page.
type Document ¶
type Document struct {
PageCount int
Pages []Page
Metadata Metadata
Outlines []Outline
FormFields []FormField
Warnings []Warning
}
Document is the extraction result for a whole file.
func Extract ¶
Extract parses the PDF in r and extracts every page's glyphs. Malformed pages yield whatever was decoded before the failure; a malformed file returns an error. The context is checked between pages and periodically while processing page operators and glyphs.
func ExtractPages ¶ added in v0.3.0
func ExtractPages( ctx context.Context, r io.ReaderAt, size int64, opts Options, yield func(Page) error, ) (*Document, error)
ExtractPages extracts pages one at a time and calls yield without retaining them in the returned Document. Document metadata, page count, form fields, outlines, and accumulated warnings are still returned.
func ExtractWithOptions ¶ added in v0.3.0
func ExtractWithOptions(ctx context.Context, r io.ReaderAt, size int64, opts Options) (*Document, error)
ExtractWithOptions extracts selected pages and document extras according to opts. In strict mode it returns the partial document together with the first warning as a *StrictError.
type Glyph ¶
type Glyph struct {
Text string // decoded text, non-empty
X, Y float64 // origin: where the baseline starts
Advance float64 // displacement along the baseline in page units
Size float64 // effective font size
// Direction is the unit direction the baseline runs in. Ascent and
// Descent are the vectors from the baseline to the far and near
// edges of the glyph box, preserving rotation, skew, and vertical
// writing: horizontal text has Ascent spanning the font size along
// the text-space y axis and a zero Descent; vertical text reaches
// half the font size to either side of its baseline.
Direction Point
Ascent Point
Descent Point
}
Glyph is one decoded glyph (or glyph cluster) with its position in unrotated page space.
The geometry is stored compactly — a document's glyph slice is its largest allocation — and Baseline and Quad derive the full shapes. A Glyph carrying only Text, X, Y, Advance, and Size (for example one supplied by an OCR hook) is treated as upright horizontal text.
type LayoutMode ¶ added in v0.3.0
type LayoutMode uint8
LayoutMode selects how Page.Text reconstructs text.
const ( // LayoutPosition groups glyphs using their geometric baselines. LayoutPosition LayoutMode = iota // LayoutContentOrder preserves the order in which glyphs occur in content // streams, inserting line breaks only when the baseline changes. LayoutContentOrder // LayoutColumns separates wide horizontal gaps into column regions and // reads each column from top to bottom. LayoutColumns )
type LayoutOptions ¶ added in v0.3.0
type LayoutOptions struct {
Mode LayoutMode
}
LayoutOptions controls plain-text reconstruction.
type Limits ¶ added in v0.3.0
type Limits struct {
MaxStreamBytes int
MaxOperatorsPerPage int
MaxGlyphsPerPage int
MaxFormDepth int
}
Limits bounds work performed on untrusted documents. Zero fields use the package defaults.
type Metadata ¶ added in v0.3.0
type Metadata struct {
Title string
Author string
Subject string
Keywords string
Creator string
Producer string
CreationDate string
ModifiedDate string
Trapped string
XMP []byte
Custom map[string]string
}
Metadata contains common document information dictionary and XMP fields. Dates retain their original PDF string representation.
type OCR ¶ added in v0.3.0
type OCR interface {
ExtractPage(context.Context, OCRRequest) ([]Glyph, error)
}
OCR extracts text for an image-only page. Implementations may invoke an external renderer or OCR engine; the core package remains dependency-free.
type OCRFunc ¶ added in v0.3.0
type OCRFunc func(context.Context, OCRRequest) ([]Glyph, error)
OCRFunc adapts a function to OCR.
func (OCRFunc) ExtractPage ¶ added in v0.3.0
ExtractPage calls f.
type OCRRequest ¶ added in v0.3.0
OCRRequest is passed to an external OCR implementation for a page whose content streams produced no text. Reader and Size identify the original PDF.
type Options ¶ added in v0.3.0
type Options struct {
Password string
Pages []PageRange
Strict bool
Limits Limits
Layout LayoutOptions
IgnoreArtifacts bool
IncludeMetadata bool
IncludeOutlines bool
IncludeAnnotations bool
IncludeFormValues bool
// PreserveLigatures keeps the Unicode presentation forms U+FB00–U+FB06
// (ff fi fl ffi ffl ſt st) in glyph text. By default they fold to their letter
// sequences (ff, fi, fl, ffi, ffl, st) — the form searchers, tokenizers
// and other extractors expect — whether the glyph reached the ligature
// codepoint through a glyph name (Type1 /Differences, the standard
// encodings, an embedded font program) or through a ToUnicode CMap.
PreserveLigatures bool
CMapResolver CMapResolver
OCR OCR
// Concurrency bounds how many pages are extracted at once. Zero picks
// a worker per available processor; one extracts sequentially.
// Extraction stays deterministic either way: pages, their glyphs, and
// their warnings come out in the same order.
//
// Pages run concurrently only when nothing observable depends on the
// order they execute in. Strict stops at the first warning, and OCR
// and CMapResolver are caller code, so those extract sequentially
// whatever this is set to.
Concurrency int
}
Options controls extraction. Its zero value preserves Extract's permissive, all-pages behavior.
type Outline ¶ added in v0.3.0
type Outline struct {
Title string
Destination Destination
Children []Outline
}
Outline is one bookmark in the document outline tree.
type Page ¶
type Page struct {
Number int
Glyphs []Glyph
MediaBox Rect
CropBox Rect
Rotation int
Annotations []Annotation
Warnings []Warning
// contains filtered or unexported fields
}
Page holds the glyphs of one page in content order.
func (Page) GlyphsIn ¶ added in v0.3.0
GlyphsIn returns glyphs whose quadrilateral intersects region.
func (Page) Text ¶
Text reconstructs a page's plain text using glyph baselines and the layout selected at extraction time. Rotated and vertical runs retain their reading direction, and spaces are inferred from geometric gaps.
func (Page) TextIn ¶ added in v0.3.0
func (p Page) TextIn(region Rect, layout LayoutOptions) string
TextIn reconstructs text from glyphs intersecting region.
func (Page) TextWithOptions ¶ added in v0.3.0
func (p Page) TextWithOptions(layout LayoutOptions) string
TextWithOptions reconstructs page text using layout rather than the layout selected during extraction.
type PageRange ¶ added in v0.3.0
PageRange selects an inclusive, one-based page range. A Last value of zero means the final page.
type Quad ¶ added in v0.3.0
type Quad [4]Point
Quad describes a glyph-region perimeter. The first edge follows the baseline direction and the opposite edge returns toward its origin.
type StrictError ¶ added in v0.3.0
type StrictError struct {
Warning Warning
}
StrictError is returned when strict extraction encounters a condition that permissive extraction would record as a Warning.
func (*StrictError) Error ¶ added in v0.3.0
func (e *StrictError) Error() string
func (*StrictError) Unwrap ¶ added in v0.3.0
func (e *StrictError) Unwrap() error
type Warning ¶ added in v0.3.0
type Warning struct {
Page int
Code WarningCode
Err error
}
Warning describes a condition that may have made an extraction incomplete. Page is one-based, or zero for a document-level warning.
type WarningCode ¶ added in v0.3.0
type WarningCode string
WarningCode identifies a recoverable extraction problem.
const ( // WarningMalformedDocument reports malformed document-level structures // such as outlines or form-field trees. WarningMalformedDocument WarningCode = "malformed_document" // WarningMalformedPage reports malformed page content or page extras. WarningMalformedPage WarningCode = "malformed_page" // WarningStream reports a stream decoding or filter failure. WarningStream WarningCode = "stream_error" // WarningStreamLimit reports decoded data truncated at a configured limit. WarningStreamLimit WarningCode = "stream_limit" // WarningWorkLimit reports an operator, glyph, or nesting budget. WarningWorkLimit WarningCode = "work_limit" // WarningUnsupported reports a recoverable unsupported PDF feature. WarningUnsupported WarningCode = "unsupported" // WarningOCR reports an external OCR implementation failure. WarningOCR WarningCode = "ocr" )
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
crypt
Package crypt implements the PDF standard security handler (ISO 32000-1 §7.6.3 and ISO 32000-2 §7.6.4): RC4 and AES stream/string decryption with the file key derived from a supplied user or owner password.
|
Package crypt implements the PDF standard security handler (ISO 32000-1 §7.6.3 and ISO 32000-2 §7.6.4): RC4 and AES stream/string decryption with the file key derived from a supplied user or owner password. |
|
encoding
Package encoding implements the simple-font character encodings of ISO 32000-1 Annex D and the Adobe Glyph List glyph-name algorithm.
|
Package encoding implements the simple-font character encodings of ISO 32000-1 Annex D and the Adobe Glyph List glyph-name algorithm. |
|
filter
Package filter implements the PDF stream decode filters of ISO 32000-1 §7.4 that text extraction needs: FlateDecode, LZWDecode, ASCIIHexDecode, ASCII85Decode and RunLengthDecode, with the PNG and TIFF predictors.
|
Package filter implements the PDF stream decode filters of ISO 32000-1 §7.4 that text extraction needs: FlateDecode, LZWDecode, ASCIIHexDecode, ASCII85Decode and RunLengthDecode, with the PNG and TIFF predictors. |
|
object
Package object is a native PDF object layer: a lexer and parser for the COS object syntax (ISO 32000-1 §7.2–7.3), cross-reference tables and streams (§7.5), and a Value model for navigating the resulting object graph.
|
Package object is a native PDF object layer: a lexer and parser for the COS object syntax (ISO 32000-1 §7.2–7.3), cross-reference tables and streams (§7.5), and a Value model for navigating the resulting object graph. |
|
safeio
Package safeio bounds reads from untrusted streams: decompression bombs and stalled filter chains must cost bounded memory and CPU.
|
Package safeio bounds reads from untrusted streams: decompression bombs and stalled filter chains must cost bounded memory and CPU. |
|
Package pdftest builds minimal synthetic PDF files for tests, in the spirit of net/http/httptest.
|
Package pdftest builds minimal synthetic PDF files for tests, in the spirit of net/http/httptest. |