Skip to content
Extraction

Extraction

Everything in this section goes through the extractor package. You build an extractor for a single page and ask it for what you want:

page, err := pdfReader.GetPage(pageNum)
if err != nil {
    return err
}

ex, err := extractor.New(page)
if err != nil {
    return err
}

text, err := ex.ExtractText()

There is no document-level extractor, so anything covering a whole file is a loop over pages. Fonts are the exception worth knowing about: ExtractFonts takes the previous page’s result and merges it, which is how you build a deduplicated list across a document.

A PDF stores glyphs at coordinates, not paragraphs, tables or reading order. All of those are inferred by the extractor from position, so extraction is reconstruction, and how well it works depends on the document. When output looks wrong, the extraction mode is usually the first thing to change rather than the last.

Extraction modes

Four modes are available through NewWithOptions, and they differ in what they infer and what they make available afterwards.

ModeInfersTables() and Marks()
ExtractionModeLayout (default)Paragraphs, tables, reading orderBoth available
ExtractionModePlainNothing; reads content streams in orderNot built
ExtractionModeLayoutNoBreaksAs Layout, no breaks within a horizontal lineBoth available
ExtractionModeGridFixed-width character grid from positionsBoth empty

Layout mode is the default and supports the richest API. Plain mode is the fastest and produces the most complete text, so it is worth trying when layout mode duplicates or drops content. Grid mode is closest to pdftotext -layout, and is also reachable from any mode through PageText.GridText().

Text extraction covers the modes and the remaining options in full.

Where to look

GuideCovers
Text extractionExtracting text, and choosing an extraction mode.
Table extractionRecovering tables as rows and cells.
Image extractionImages with their size, position and rotation.
Font extractionFonts used on a page, and saving embedded font files.
Reconstruct textRedrawing extracted text to check accuracy.

For finding and changing text rather than reading it, see search and replace. For scanned documents with no text layer, see OCR.

Last updated on