pdf

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: MIT Imports: 17 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

pdf: text extraction after pdfminer.six

A pure Go port of the parts of pdfminer.six that turn a PDF into laid-out text: what markitdown uses for PDFs. It matches pdfminer character for character, and its layout analysis line for line, on every sample in its test corpus, and runs about 20 times faster.

pdf/          syntax: lexer, objects, xref tables and streams, object
              streams, filters, encryption, page tree, content operators.
              Repairs damaged files by scanning for objects.
pdf/font/     fonts: encodings, glyph names, ToUnicode CMaps, predefined CJK
              CMaps, standard 14 metrics, TrueType cmap fallback, widths.
pdf/extract/  the content interpreter: every character drawn, with its box.
pdf/layout/   pdfminer's layout analysis: characters to lines to boxes, and
              boxes into reading order.
pdf/table/    ruled tables: pdfplumber's line-based table finder, from the
              lines, rectangles and curves the interpreter records.

Where it comes from

Part Source
layout, interpreter, font logic ported from pdfminer.six 20260107 (MIT)
font/tables_gen.go generated by gen_tables.py from pdfminer's data: Adobe Glyph List (BSD-3-Clause), standard 14 AFM metrics (Adobe), Latin encodings
font/cmapdata/ generated by gen_cmaps.py from pdfminer's copy of Adobe's cmap-resources (BSD-3-Clause)
syntax layer written to ISO 32000-2, with pdfminer's repair strategy
table/ ported from pdfplumber 0.11.11 (MIT), lines strategy only

mupdf is a useful behavioral reference, but it is AGPL: read it to learn what a file needs, never to copy or closely port code.

Testing against pdfminer

testdata/pdfminer/ holds pdfminer.six's own sample PDFs (MIT, its nonfree/ samples left out) with goldens recorded by pdfminer itself: NAME.chars.json (every character's text, box, font and size) and NAME.txt (extract_text output). extract/golden_test.go checks both.

python -m venv venv && venv/bin/pip install -r pdf/testdata/requirements.txt
venv/bin/python -I pdf/testdata/gen_pdfminer.py --force   # re-record goldens

Larger corpora are checked locally, uncommitted because their PDFs carry mixed licenses. pdf.js's test corpus has over a thousand broken and unusual files:

go tool task corpus-pdf   # fetch, record and test, in .corpus/pdf

That fetches pdf.js's corpus and pdfplumber's test PDFs at pinned commits (fetch_pdfjs.sh, fetch_pdfplumber.sh), records what has no goldens yet, and runs the tests with DOCSIGHT_PDF_CORPUS and DOCSIGHT_TABLE_CORPUS. CI runs it weekly and on changes (.github/workflows/corpus.yml).

That also runs TestCorpusRobust: every file must open or fail cleanly, never panic, and none may be slow.

Tables are checked the same way against pdfplumber, which builds on the same pdfminer.six release: gen_pdfplumber.py records each page's paths and tables (NAME.tables.json), and table/golden_test.go checks them, over the committed samples and DOCSIGHT_TABLE_CORPUS (for instance a copy of pdfplumber's tests/pdfs, every one of whose tables matches).

Deliberate differences from pdfminer

Where pdfminer departs from the PDF specification, docsight follows the specification. Each case is pinned by a unit test and listed, with the corpus files it affects, in extract/golden_test.go:

  • " moves to the next line before showing text (9.4.3). pdfminer does not move, so text after it drifts onto the line before.
  • An odd hex string <…1> ends in 0x10, as if a 0 followed (7.3.4.3). pdfminer reads 0x01.
  • An unknown escape \ drops only the backslash (7.3.4.2). pdfminer drops the next character too.
  • TrueType cmap format 4 glyph addresses are computed from each segment's own idRangeOffset entry. pdfminer uses the array's start, so later segments map to wrong characters.
  • Numbers in exponent form (1e2) read as pdf.js and Acrobat read them.
  • A Type0 font with a null descendant stays a two-byte font, rather than pdfminer's fallback to a one-byte font that emits a spurious (cid:0).
  • Repair takes the newest trailer of a damaged file, as incremental updates intend; pdfminer takes the first.
  • F fills a path as f does (8.5.3.1); pdfminer's do_F is empty, so such paths vanish.
  • A form's cm ends with the form (Do is an implicit q/Q); pdfminer leaves it on its device, misplacing what is drawn after.
  • A stream whose /Length cuts it short is read to its endstream.
  • A page's content stream reused as a form it draws is drawn once; pdfminer's cycle check refuses it.

Beyond those, pdfminer breaks ties between equally distant text boxes by memory address, so its own output varies between runs on pages of identical boxes. docsight breaks them by creation order, deterministically; the text test tolerates a few lines in a different order.

Not yet

  • Lists from geometry, and borderless tables. (Headings by font size, line-end dehyphenation, ligatures, and which ruled grids read as tables are decided when building Markdown, in convert/, leaving this package's output identical to pdfminer's and pdfplumber's.)
  • OCR for scanned pages.

Documentation

Overview

Package pdf reads the object structure of PDF files: objects, cross reference tables and streams, object streams, stream filters, encryption, and the page tree. It is the syntax layer under text extraction, after pdfminer.six's psparser, pdfparser, pdfdocument, pdftypes and pdfpage.

It is built for reading files from anywhere: it repairs what it can (a broken cross reference table, a wrong stream length, a truncated zlib stream), bounds what it allocates, and reports what it cannot read as an error rather than a panic.

Index

Constants

View Source
const MaxFile = 512 << 20

MaxFile bounds the size of a PDF Open reads into memory.

View Source
const MaxStream = 256 << 20

MaxStream bounds how large one stream may decode to, so a small compressed stream cannot exhaust memory.

Variables

View Source
var ErrImageData = errors.New("pdf: image-encoded stream")

ErrImageData is returned when a stream is encoded with an image filter, whose data this package does not decode.

View Source
var ErrPassword = errors.New("pdf: incorrect password")

ErrPassword is returned when an encrypted document opens with neither the empty password nor the one given.

Functions

func Format

func Format(o Object) string

Format renders an object compactly, for errors and debugging.

func Int

func Int(o Object) (int, bool)

Int reads an integer, truncating a real.

func Num

func Num(o Object) (float64, bool)

Num reads a number, integer or real.

func Ops

func Ops(content []byte, yield func(Op) bool)

Ops reads the operators in a content stream. Malformed content ends the sequence at the damage rather than failing.

Types

type Array

type Array []Object

Array is a PDF array.

type Dict

type Dict map[Name]Object

Dict is a PDF dictionary.

type Document

type Document struct {

	// Repaired says the cross reference data was unreadable and objects were
	// found by scanning the file instead.
	Repaired bool
	// contains filtered or unexported fields
}

Document is an opened PDF.

func Open

func Open(r io.ReaderAt, size int64, password string) (*Document, error)

Open reads a PDF. Password is tried as the user and then the owner password; most encrypted files open with the empty one.

func OpenBytes

func OpenBytes(data []byte, password string) (*Document, error)

OpenBytes reads a PDF held in memory. The document keeps data.

func (*Document) Array

func (d *Document) Array(o Object) Array

Array resolves o and returns it as an array, or nil.

func (*Document) ContentOf

func (d *Document) ContentOf(o Object) []byte

ContentOf decodes and joins a Contents value: one stream or an array of them. Streams that fail to decode contribute what decoded.

func (*Document) Dict

func (d *Document) Dict(o Object) Dict

Dict resolves o and returns it as a dictionary, or nil. A stream yields its dictionary.

func (*Document) Int

func (d *Document) Int(o Object) (int, bool)

Int resolves o and returns it as an integer.

func (*Document) Name

func (d *Document) Name(o Object) Name

Name resolves o and returns it as a name, or "".

func (*Document) Num

func (d *Document) Num(o Object) (float64, bool)

Num resolves o and returns it as a number.

func (*Document) Pages

func (d *Document) Pages() []*Page

Pages returns the document's pages in order. A page tree too damaged to walk falls back to every page object in the file, as pdfminer does.

func (*Document) Resolve

func (d *Document) Resolve(o Object) Object

Resolve follows references until it reaches a direct object. A missing or unreadable object resolves to nil, as PDF readers must treat it.

func (*Document) Stream

func (d *Document) Stream(o Object) *Stream

Stream resolves o and returns it as a stream, or nil.

func (*Document) Trailer

func (d *Document) Trailer() Dict

Trailer returns the trailer dictionary.

type Keyword

type Keyword string

Keyword is a bare word in a content stream, such as an operator.

type Name

type Name string

Name is a PDF name, without its slash and with #xx escapes decoded.

type Object

type Object any

Object is a PDF object: nil (null), bool, int, float64, String, Name, Array, Dict, *Stream, Ref, or, in content streams only, Keyword.

type Op

type Op struct {
	Name Keyword
	Args []Object
	// Inline is the dictionary of an inline image (operator "BI"), whose
	// data has been skipped.
	Inline Dict
}

Op is one operator in a content stream, with its operands.

type Page

type Page struct {
	Dict      Dict
	Resources Dict
	MediaBox  [4]float64
	CropBox   [4]float64
	Rotate    int // 0, 90, 180 or 270
	// contains filtered or unexported fields
}

Page is one page of a document, with its inherited attributes resolved.

func (*Page) Content

func (p *Page) Content() []byte

Content returns the page's content streams, decoded and joined.

func (*Page) Document

func (p *Page) Document() *Document

Document returns the document the page belongs to.

type Ref

type Ref struct{ Num, Gen int }

Ref is an indirect reference to object Num, generation Gen.

func (Ref) String

func (r Ref) String() string

type Stream

type Stream struct {
	Dict Dict
	// contains filtered or unexported fields
}

Stream is a stream object: its dictionary and its still-encoded data.

func (*Stream) Decode

func (s *Stream) Decode() ([]byte, error)

Decode returns the stream's data with its filters undone. Data that is cut short or damaged decodes as far as it can, as viewers do: a truncated Flate stream yields what it held.

func (*Stream) Raw

func (s *Stream) Raw() []byte

Raw returns the stream's data as stored, decrypted but not decoded.

type String

type String string

String is a PDF string's bytes, already decrypted.

Directories

Path Synopsis
Package extract runs a page's content streams and collects every character drawn, positioned and sized, as layout input.
Package extract runs a page's content streams and collects every character drawn, positioned and sized, as layout input.
Package font maps the bytes a PDF shows to text and glyph geometry: it decodes character codes, maps them to Unicode (ToUnicode CMaps, simple encodings with Differences, embedded font tables), and supplies widths, descent and vertical displacement.
Package font maps the bytes a PDF shows to text and glyph geometry: it decodes character codes, maps them to Unicode (ToUnicode CMaps, simple encodings with Differences, embedded font tables), and supplies widths, descent and vertical displacement.
Package layout groups positioned characters into words, lines and text boxes, and orders the boxes for reading.
Package layout groups positioned characters into words, lines and text boxes, and orders the boxes for reading.
Package table finds ruled tables on a PDF page: tables whose cells are drawn with lines or rectangles.
Package table finds ruled tables on a PDF page: tables whose cells are drawn with lines or rectangles.

Jump to

Keyboard shortcuts

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