pdfspec

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: MIT Imports: 30 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.

Documentation

Overview

Package pdfspec converts a PDF to Markdown. It is the whole path from the file to its text, which the pdfspec command and any program embedding the converter share (ADR 0051).

Open reads the file's own text and structure. Read then reads, with the engines Options name, what is only in pixels: pages that carry no text, the images worth reading, and glyphs the file gives no value. Markdown writes the result.

d, err := pdfspec.Open("paper.pdf", pdfspec.DefaultOptions)
if err != nil {
	return err
}
defer d.Close()
if err := d.Read(ctx); err != nil {
	return err
}
return d.Markdown(w)

Convert does the three in one call.

Index

Constants

View Source
const BackendNames = "pdfium, native, auto"

BackendNames is what -backend accepts, and the order is the order they are documented in.

Variables

View Source
var DefaultOptions = Options{
	OCR:       true,
	Threshold: ocr.DefaultThreshold,
	Backend:   "pdfium",
	Lang:      "eng",
	DPI:       ocrDPI,
	MinConf:   defaultMinConf,
}

DefaultOptions are "pdfspec md" with no flags: OCR on every page that needs it, with Tesseract from PATH and inferd at the platform's address when they are there.

Functions

func Convert

func Convert(ctx context.Context, w io.Writer, path string, opt Options) error

Convert writes the PDF at path to w as Markdown: Open, Read and Markdown in one call.

func ErrPages

func ErrPages(pages []PageErrs) string

ErrPages lists the pages as "p3 12, p7 4".

func ErrTotal

func ErrTotal(pages []PageErrs) int

ErrTotal is the number of glyphs across pages.

func InferRoles

func InferRoles(d *doc.Document)

InferRoles promotes table cells, headings, and list items in a document that declared none.

Called on the untagged branch only: where a structure tree exists, sectionize has already assigned every role from what the producer declared, and guessing over a declaration would replace evidence with a heuristic.

Tables first, and this order is load-bearing rather than a precedence claim. It runs on the page's own strokes, which the other two never consult, and it is the only pass that changes the block list rather than relabelling blocks in place — a table's row arrives as one paragraph and leaves as one block per cell. Running it second would hand Headings a table's header row as a short paragraph in a distinct style, which is what its size ranking promotes, and Lists a numeric first column, which is what its marker test reads. Running it first leaves both nothing to misread: they consider only RoleParagraph blocks, and a cell is RoleTableCell.

Headings then Lists, on evidence and not on necessity. Both passes consider only RoleParagraph blocks, so whichever runs second cannot reclassify what the first promoted, and Headings has the stronger claim on the overlap — a section number the document states outright, against a marker glyph.

Necessity was measured, because there is a route by which the order could matter for more than precedence: Lists edits span text, and Headings' bodyCluster ranks sizes by rune count, so stripping markers first perturbs the counts it reads. Run both ways over all 48 PDFs on disk, the two orders agree on every block's role and level, on every heading count, and on every measured body size — 0 files differ. So the order is a statement about which evidence outranks which, and nothing on disk depends on it.

OrderedLists last, and here the order is a precedence claim that matters. Its evidence is a run of incrementing numbers, and a numbered *heading* is exactly the block that could be misread as one — which is ADR 0011's stated objection to recognizing ordered lists at all. Running Headings first answers it structurally rather than by argument: a heading ADR 0008 promoted is no longer RoleParagraph, so it is not a candidate and cannot join a run. Tables first removes the other collision the ADR names, a numeric first column.

Shared by md and ocr so the two agree. They have to — ocr on a born-digital document writes what md writes and runs no engine, and TestOCRVerbOnDigitalDocument holds them to it. A page read by OCR is built of paragraphs with lines (ocr.Page), so every pass considers it as it does an extracted page.

func NeedsLine

func NeedsLine(needs []PageNeed) string

NeedsLine is probe's line for what the pages need: "read whole: 1-3; images: p5 2; glyphs with no value: p7 12".

func OpenRasterizer

func OpenRasterizer(name, path string) (render.Rasterizer, error)

OpenRasterizer builds the rasterizer a -backend value names.

One constructor for every caller, which is the point of it: render and ocr both needed a Rasterizer and both had `renderpdfium.Open` written out, so adding a second backend to one of them would have left the other on the first with nothing to say so.

pdfium stays the default. The two backends do not produce identical pixels — they disagree on CMYK by design, on glyph grid-fitting because this one does not hint, and on a substituted typeface because pdfium uses Foxit's faces and this uses Liberation — so making native the default would silently change every rendered page for existing callers. Opt-in is the honest shape until the native backend draws everything.

func Route

func Route(d *doc.Document, want []int, threshold float64, force bool) []int

Route returns the selected pages that need recognition, in page order.

Types

type Document

type Document struct {
	// Doc is what was read: the pages, their blocks and images, and what OCR recovered.
	Doc *doc.Document
	// Failed are the pages the extractor could not read, which are blank in the output.
	Failed []extract.PageError
	// Options are those Open was given. A change before Read or Markdown applies to it, such as
	// Pages chosen once the page count is known.
	Options Options
	// contains filtered or unexported fields
}

Document is one PDF being converted. Close releases the file.

func Open

func Open(path string, opt Options) (*Document, error)

Open reads the PDF at path: its own text and structure, with no engine run. A page the extractor cannot read is blank, named in Failed and in the log, and the rest are read.

func (*Document) Close

func (d *Document) Close() error

Close releases the file.

func (*Document) Markdown

func (d *Document) Markdown(w io.Writer) error

Markdown writes the document: the structure tree's outline when the file has one and Flat is off, and otherwise the page-ordered text with the roles layout infers.

func (*Document) Needs

func (d *Document) Needs() []PageNeed

Needs is what Read would ask an engine to read, page by page, by the rules it reads by.

func (*Document) Outline

func (d *Document) Outline() (*doc.Outline, error)

Outline is the clause hierarchy the file's structure tree declares, or nil when it has none.

func (*Document) Read

func (d *Document) Read(ctx context.Context) error

Read reads what the file holds only in pixels, when Options.OCR is on: the pages Route picks, the images worth reading and the glyphs with no value, in that order, the file's own text first (ADR 0043). It then logs text the output leaves unread. Without Tesseract it reads nothing and says which pages needed it; with Strict off, an engine's failure is logged and the pages keep their extracted text, since the conversion is the file's and OCR only adds to it.

func (*Document) WritePage

func (d *Document) WritePage(w io.Writer, n int) error

WritePage writes page n alone, as "pdfspec md -split" writes each page: page-scoped, so with no outline, since a clause running across three pages cannot head three files.

type Engines

type Engines struct {
	Tesseract string `json:"tesseract"`
	Inferd    string `json:"inferd"`
}

Engines names the readers md would use, or why there is none.

func FindEngines

func FindEngines(ctx context.Context, exe, addr string) Engines

FindEngines looks for the engines as Read does, by Options' Tesseract and Inferd: exe is the tesseract executable, "" for the one on PATH, or "off"; addr is inferd's generation endpoint, "" for the platform's, or "off".

func (Engines) String

func (e Engines) String() string

String is probe's line: each engine by its name, or what it is with what stops it, "tesseract 5.5.3 eng; inferd off".

type Options

type Options struct {
	// KeepArtifacts keeps running headers, folios and watermarks, in the reading and the output.
	KeepArtifacts bool
	// Flat writes page-ordered prose with no headings, even when the file is tagged.
	Flat bool
	// Frontmatter writes YAML frontmatter.
	Frontmatter bool

	// OCR reads what is only in pixels, with Tesseract and the second reader below.
	OCR bool
	// Pages are the pages OCR may read whole, ascending; nil is every page. Images and glyphs
	// with no value are read on every page.
	Pages []int
	// Threshold is the fraction of a page's area covered by text below which the page is read
	// whole (ocr.Route).
	Threshold float64
	// Force reads every page in Pages whole, whatever its text covers.
	Force bool
	// Strict makes a page OCR fails on an error from Read. Otherwise the page keeps its extracted
	// text, and the failure is a warning in the log.
	Strict bool
	// Backend is the rasterizer OCR reads from: one of BackendNames.
	Backend string
	// Tesseract is the tesseract executable, "" for the one on PATH, or "off" to run none.
	Tesseract string
	// TessData is the directory of Tesseract's language models, "" for TESSDATA_PREFIX or the
	// install's.
	TessData string
	// Lang is the Tesseract language model.
	Lang string
	// DPI is the resolution a page is rasterized at before OCR.
	DPI float64
	// MinConf is, without a second reader, the Tesseract confidence (0 to 100) below which a word
	// is written [err].
	MinConf float64
	// Inferd is inferd's generation endpoint for the second reader, "" for the platform's, or
	// "off" to ask none.
	Inferd string
	// InferdTimeout bounds each request to the model: zero is five minutes, enough for a CPU with
	// no accelerator, and negative waits as long as the model takes.
	InferdTimeout time.Duration

	// Log receives what a reader of the output should know and the output cannot say: pages
	// that could not be read, what OCR read and what it could not, and text left unread. nil
	// discards it.
	Log io.Writer
}

Options say how a document is read and written. DefaultOptions is what "pdfspec md" does with no flags. The package reads no environment variable: what the command takes from PDFSPEC_TESSERACT and PDFSPEC_INFERD, a caller states here.

type PageErrs

type PageErrs struct {
	Page   int `json:"page"`
	Glyphs int `json:"glyphs"`
}

PageErrs is one page's count of the glyphs the file gives no Unicode value to.

func Unmapped

func Unmapped(d *doc.Document) []PageErrs

Unmapped counts, page by page, the glyphs the file gives no Unicode value to, each of which the Markdown writes as part of an [err] (ADR 0042). A page with none is left out, and so is a page read by OCR, whose [err] are words read below the confidence threshold and reported with it.

type PageNeed

type PageNeed struct {
	Page     int  `json:"page"`
	Whole    bool `json:"read_whole,omitempty"`
	Images   int  `json:"images,omitempty"`
	Unmapped int  `json:"unmapped,omitempty"`
}

PageNeed is what an engine would read on one page: the page whole, which the router sends to OCR, its images worth reading, and its glyphs with no value.

func PageNeeds

func PageNeeds(s objects.Store, d *doc.Document) []PageNeed

PageNeeds is what Read would ask an engine to read in d, whose file s is, page by page.

Jump to

Keyboard shortcuts

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