Text Extraction
Text extraction goes through the extractor package, one page at a time:
page, err := pdfReader.GetPage(pageNum)
if err != nil {
return err
}
ex, err := extractor.New(page)
if err != nil {
return err
}
text, err := ex.ExtractText()
if err != nil {
return err
}extractor.New uses the default mode. When the output is not what you expect,
the mode is usually the thing to change.
Choosing a mode
Pass a mode through NewWithOptions instead:
ex, err := extractor.NewWithOptions(page, &extractor.Options{
ExtractionMode: extractor.ExtractionModePlain,
})| Mode | What it does | Use it when |
|---|---|---|
ExtractionModeLayout (default) | Detects paragraphs and tables, works out reading order. Supports Tables() and Marks(). | You need marks or tables, for instance search and replace. |
ExtractionModePlain | Reads straight from the content streams, no paragraph grouping or table detection. Fastest, and produces the most complete text with no duplication. | Bulk text extraction, and data-heavy PDFs. |
ExtractionModeLayoutNoBreaks | As Layout, but without line breaks inside the same horizontal line. | The page is one column and layout mode is breaking lines you want joined. |
ExtractionModeGrid | Places words on a fixed-width character grid from their positions, keeping multi-column text and table columns aligned. Comparable to pdftotext -layout. | You want the visual column structure preserved as text. |
In ExtractionModeGrid, Marks() and Tables() return
empty results in this mode, so use ExtractionModeLayout if you need either. And
the grid layout is available from any mode through PageText.GridText(), so you
do not have to switch modes just to get it once.
Layout mode is the one to reach for if you are unsure, and plain mode is the one to try first when extraction looks wrong.
Other options
extractor.Options carries a few more switches worth knowing:
IncludeAnnotationspulls annotation text into the output. Off by default.ApplyCropBoxlimits extraction to the page’s crop box.DisableDehyphenationkeeps words broken across lines separate. By default a word ending in a hyphen is rejoined with the next line.RelaxedModetries to repair invalid parameter lengths and values rather than failing, which helps with malformed files.DisableDocumentTagsignores document tags during list extraction.
Run the example
outputPdfText opens the file, loops over the pages, and prints the text of each
one to the terminal using the default mode.
git clone https://github.com/unidoc/unipdf-examples.git
cd unipdf-examples/extract
go run pdf_extract_text.go input.pdfIf this is your first time using UniPDF, follow the getting started guide to create an API key and set up your development environment.