gofastpdf

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 36 Imported by: ? modules, 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

GoFast PDF 🛸

Go Version

A Go library that extracts the text and structure of PDF files, fast, for retrieval, knowledge graphs and language models. It is written from scratch on the standard library: its one dependency is go-fast-core, the document model that the go-fast libraries share.

  • It returns paragraphs in reading order, each with its place on the page, as JSON, Markdown or text.
  • It extracts everything a page holds, and says where the file declares text not shown or drawn with no ink; it leaves nothing out and judges nothing.
  • It reads files that are encrypted or damaged, and is bounded in time and memory on files made to exhaust them.
  • It starts no program, fetches nothing, runs nothing that a file contains, and does no OCR.

Status. v0.2.1 (2026-11-22), on go-fast-core v0.1.1. The API is not that of v0.1: MIGRATION.md says what became what; CHANGELOG.md says what changed.

Speed

Pages per second Time against go-fast-pdf Most memory
go-fast-pdf 10,011 1 30 MB
go-fast-pdf, all processors 19,773 0.51 times 59 MB
gofastpdf (the command) 7,907 1.27 times 24 MB
pdftotext (poppler) 1,989 5.03 times 20 MB
PyMuPDF 2,234 4.48 times 62 MB
pypdfium2 (PDFium) 2,202 4.55 times 30 MB
pypdf 345 29.1 times 72 MB
pdfplumber 56 178 times 53 MB

8 documents, 530 pages, 9.7 MB: the long documents of the public corpus's tuning set and one small one. Each program reads each document 5 times and its best time counts. Measured on AMD Ryzen 9 9900X 12-Core Processor (24 threads, linux/amd64) with go1.27.3-X:nodwarf5, 2026-11-22. The method, the versions and the time for each document are in bench/comparison.md.

Reading the 1,650 files of the public test corpus, damaged ones included, takes 1.3 seconds on one thread. go run ./bench/compare makes the table again on your machine.

With many workers, a good part of the time is Go's garbage collector, which a program can tune; the library leaves its settings alone. On the documents of the table, with 24 workers, the default takes 16 to 17 ms, GOGC=200 13 ms, and GOMEMLIMIT=1GiB GOGC=off 12.6 ms: more memory for less time.

Installation

go get github.com/AOShei/go-fast-pdf

Go 1.25 or later.

Usage

Command line
go install github.com/AOShei/go-fast-pdf/cmd/gofastpdf@latest

# The document as JSON (the shared document model)
gofastpdf document.pdf

# As Markdown or plain text, into a file
gofastpdf --format markdown -o document.md document.pdf

# Several files, or every PDF under a directory: one JSON document per line
gofastpdf reports/ appendix.pdf > all.jsonl

# Some pages, eight at a time, without blocks for the images
gofastpdf --pages 10-20 --workers 8 --images none document.pdf

# With the data of the images
gofastpdf --images data document.pdf

# An encrypted file
gofastpdf --password secret document.pdf

# Text the file declares not shown, or drawn with no ink, left out of what is written
gofastpdf --exclude-display --format text document.pdf

# Only text with the reasons named is left out
gofastpdf --exclude-display=hidden --format text document.pdf

# Text with the running headers and footers, the scripts and the stored part,
# and a line before each page saying which it is
gofastpdf --furniture --stored --part-markers --format text document.pdf

# Text with the scripts only, each on its page, and nothing else that is stored
gofastpdf --stored=macro --format text document.pdf

The flags for Markdown and text are those of every go-fast command: --furniture, --stored[=kinds], --part-markers, --exclude-display[=reasons], and --children (on by default: a line naming each attached file; --children=false leaves them out). JSON always has everything, with what the file declares about each block. Warnings of a file that was read are named on standard error (--quiet leaves that out); a file that cannot be read is reported there and makes the exit status 1.

Library
package main

import (
    "context"
    "fmt"
    "log"
    "os"

    gofastcore "github.com/AOShei/go-fast-core"
    gofastpdf "github.com/AOShei/go-fast-pdf"
)

func main() {
    // nil options: text and structure of every page, one worker per processor.
    doc, err := gofastpdf.ExtractFile(context.Background(), "document.pdf", nil)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(doc.Markdown()) // or doc.Text(), or encoding/json

    // Blocks in reading order, with where they are on their page.
    for part, block := range doc.AllBlocks() {
        fmt.Printf("page %d %v: %.40q\n", part.Number, block.Loc.BBox, block.Text)
    }

    // Text that the file declares not shown, or drawn with no ink, is
    // extracted with the reason.
    for part, block := range doc.AllBlocks() {
        if block.Display != 0 {
            fmt.Printf("page %d, %s: %q\n", part.Number, block.Display, block.Text)
        }
    }
    // Leave out what the file switches off, and keep the text layer of
    // scans, which is drawn with no ink:
    doc.WriteText(os.Stdout, &gofastcore.RenderOptions{ExcludeDisplay: gofastcore.DisplayHidden})

    // What went wrong, per page and for the file.
    for part, w := range doc.AllWarnings() {
        if part != nil {
            fmt.Printf("page %d: %s: %s\n", part.Number, w.Code, w.Message)
        } else {
            fmt.Printf("%s: %s\n", w.Code, w.Message)
        }
    }
}

gofastpdf.Extract(ctx, readerAt, size, opts) does the same for anything that can be read at an offset.

Page by page

A file can also be opened and read a page at a time, without holding the document. A file of any number of pages is read in bounded memory this way.

f, err := gofastpdf.Open("document.pdf", &gofastcore.Options{Workers: 8})
if err != nil {
    log.Fatal(err)
}
defer f.Close()

fmt.Println(f.NumPages(), "pages;", f.Metadata().Title)

// The parts in page order, several pages read at a time, none kept.
for part, err := range f.Parts(ctx) {
    if err != nil {
        log.Fatal(err) // the context ended, or a limit was reached
    }
    index(part.Number, part.Text())
}

// One page by its number, from any goroutine.
page, _ := f.Page(12)
part, _ := page.Part()

// More than a part has: lines, their font and size, and the box of every word.
lines, _ := page.Lines()
for _, line := range lines {
    fmt.Println(line.Font, line.Size, line.Text)
    for _, word := range line.Words {
        fmt.Println("  ", word.Text, word.BBox)
    }
}

Options are gofastcore.Options: Workers, Images (a block for each image, which is the default; its data too; or none), Password, Keys (private keys, for a file encrypted for a certificate), Parts (a range of pages), Limits, Spans and Child (an extractor for attached files). Settings that only PDF has are fields of gofastpdf.Extractor. The package documentation says what each does for PDF.

What it reads

  • Text - fonts with and without ToUnicode maps, composite fonts, the standard encodings, the Adobe Glyph List; ligatures and Arabic presentation forms are written as their letters
  • Paragraphs and reading order - lines are joined into paragraphs; columns, tables drawn by rows, and pages drawn out of order are put in reading order; in a tagged PDF the order of the structure tree decides where the white space of the page leaves it open; text written from right to left (Hebrew, Arabic) reads in the order it is written, with numbers and Latin words in it from left to right
  • Running headers and footers - titles, dates and page numbers that the pages repeat in their margins are tagged, and the renderers leave them out; a paragraph split by a page break is joined again
  • Headings - from the structure tree of a tagged PDF or the outline where they name them, otherwise by size and weight, with levels
  • Tables of tagged PDFs - table blocks with the grid the structure tree gives: header rows, merged cells, and tables over several pages continued
  • Tables in files without tags - found by the rules they are drawn with, or by how their text lines up in columns: cells of several lines, cells over several columns and header rows set in bold; columns of prose, boxes around paragraphs, lists, tables of contents and code are not taken for tables. Looking for ruled tables costs about 5 percent; Extractor.NoRuledTables turns it off
  • Descriptions of figures - an image of a tagged PDF has the alternative text its figure gives
  • List items - bulleted and numbered, with their markers and how deep they are nested; in a tagged PDF, the items of the lists of its structure tree, with their labels as markers, also where the bullet is drawn and not written
  • Bold, italic and links - with Options.Spans: spans by the fonts of the words, and links to web addresses or to pages of the document (#page=N)
  • Anchors - the identifiers of the elements of a tagged PDF, and with Options.Spans the names of its destinations, on the blocks they name (Loc.Anchor)
  • What the file declares - text that the file switches off or draws with no ink keeps its reason (hidden, no_ink) and is never dropped: see below
  • Encryption - RC4, AES-128 and AES-256, with user and owner passwords, and files encrypted for a certificate, with the private key (Options.Keys)
  • Damaged files - broken cross-reference data is rebuilt; a page that cannot be read is reported in its place and the rest is returned
  • Images - a block for every image, where it stands among the text, with its position and size; on request JPEG and JPEG 2000 data as it is in the file, and as PNG: samples of any depth in gray, RGB, CMYK, Lab or indexed colours, CCITT fax images and stencil masks, with soft masks and masks as alpha
  • Forms and annotations - what a filled form field, a stamp or a note on the page displays is read as text of the page; what is written in a comment is a note block with its author and date; the value of a field that displays nothing is a block with the field's name; the options of a list or combo box are a choices note
  • Outline, page labels, document information, attached files - the metadata packet (XMP) gives the lists of authors and keywords as the file declares them, and what the document information leaves out; attached files are handed to a child extractor that you supply
  • What a file stores and shows nowhere - scripts, the metadata packet, entries of the file's own making in the document information, form fields on no page, the filled-in data of an XFA form, text after the last %%EOF: read as text, never run, with Attrs["stored"] saying what each is. A page's scripts are on the page; the rest is in a last part of kind stored. The renderers leave both out unless asked (RenderOptions.Stored, or StoredKinds for some kinds only; the command's -stored[=kinds])
  • Lines and words - Page.Lines gives every line with its font and size and the box of each word

Output

{
  "schema_version": "0.2",
  "source": {"format": "pdf", "name": "manual.pdf", "mime": "application/pdf", "size": 48213},
  "metadata": {"title": "Technical Manual", "authors": ["A. Writer"], "extra": {"producer": "..."}},
  "outline": [{"title": "Introduction", "level": 1, "part": 1, "y": 72}],
  "parts": [
    {
      "kind": "page",
      "number": 1,
      "width": 612,
      "height": 792,
      "blocks": [
        {
          "kind": "paragraph",
          "text": "Figure 1 shows the component breakdown...",
          "origin": "inferred",
          "loc": {"bbox": {"x0": 72, "y0": 96.4, "x1": 540, "y1": 136.4}}
        },
        {
          "kind": "image",
          "image": {"id": "obj-12", "mime": "image/jpeg", "width": 1024, "height": 768},
          "loc": {"bbox": {"x0": 100.5, "y0": 200, "x1": 400.5, "y1": 350}},
          "attrs": {"color_space": "DeviceRGB"}
        }
      ]
    }
  ]
}

Coordinates are in points on the page as it is displayed (crop box, rotation and user unit applied), with the origin at the top left.

What the file declares

This library extracts everything a file contains and reports what the file itself declares about it. It does not judge whether a reader can see text, nor whether text is harmful; the absence of a reason says nothing about either. Judging that is outside this library.

A block carries a reason in Block.Display only where the file states, by one switch or one value, that its text is not shown or is drawn with no ink. Following the file's own inheritance (forms, transparency groups, membership dictionaries) is reading the declaration.

Reason What PDF declares
hidden Optional content (a layer) that is off in the default configuration: /OFF, /BaseState /OFF, or a membership dictionary whose policy its layers make off
hidden An annotation with the Hidden or NoView flag: its text, and the value of such a form field
no_ink Text in render mode 3 (neither filled nor stroked), or 7 (clip only) when nothing is painted through the clip
no_ink Text whose opacity is 0 for what its mode paints: /ca 0 for the fill, /CA 0 for the stroke, by its graphics state or its transparency group

The searchable text of a scanned page is text in render mode 3 over the picture of the page, so it is no_ink: leaving out no_ink leaves out a scan's text.

Not judged: colour against what is under the text, its size, where it is on the page or whether it is on the page at all, what is painted over it, clipping paths, soft masks, blend modes, how much of the page an image covers. Characters are kept as the file gives them: zero-width characters, Unicode tag characters and bidirectional controls stay in the text.

Nothing is left out: you decide, for instance with RenderOptions.ExcludeDisplay. Text with a reason is laid out apart from the rest, so that the other paragraphs are what they would be without it. The stored part, the document information, the outline and the names of attached files are not shown on a page and have no reason: where they are says what they are.

Untrusted files

The library is made to be given files from anywhere. Every size that a file decides is bounded: the input (1 GiB by default), what its streams decode to (1 GiB together, 64 MiB each), the text and the blocks of the document (256 MiB), pages, objects, nesting, the text and the shapes of one page. Decoded bytes and text are counted for a document and the files attached to it together. A limit that cuts a document is reported as a warning or an error, never passed over. Reading stops when the context ends, also inside a long page. One opened file can be read from many goroutines, and the result is the same for any number of workers. SECURITY.md has the threat model, every default, and how to report a problem.

How it is tested

  • A public corpus of 1,650 PDFs (the test suites of pdf.js and PDFium, and documents of GovDocs1), scored against pdftotext word by word. A third of it is held out: scored, and never looked at when a heuristic is changed. A change may not lower the score of any file.
  • A soak run over 3,186 files and 50,569 pages, each file in a process of its own under a time limit and a memory ceiling, with the default options and with Spans: no crash, no file over its limits, every result within the contract of the shared model.
  • Fuzzing of every target listed in .github/fuzz-targets.txt, 30 seconds each on every change and an hour each every night. The decompressor is compared with compress/zlib on every input.
  • Budgets: the allocations per page of the benchmark documents, and the instructions a benchmark executes against the last release.
  • Every change runs on linux/amd64, linux/arm64, darwin/arm64 and windows/amd64 under the race detector, and as a 32-bit build. The tests run over 90 percent of the statements.

Limitations

  • Structure - a table without tags is found only where its columns stand apart with white space or rules; one whose columns are set close together with neither is paragraphs, a row a line with its cells apart by tabs. Headings are found by the outline and by type; a heading set like the text around it is not found. In a file without tags, list items are found by their markers; a list set without markers is paragraphs
  • Scripts written from right to left - a line's direction is that of the letters at its ends or of most of its words, so a line of a paragraph read from right to left that is mostly Latin can be read the other way. Columns are read from left to right whatever the script. Glyphs that a font leaves without a character are read by their outlines only for the fonts built in (Noto Sans, Naskh and Kufi Arabic, Regular and Bold, of one version each, which Firefox embeds), and the page has the warning pdf.glyph_text_by_outline; in other fonts they are not read
  • Fonts without any mapping - the encodings and glyph names of embedded Type 1, CFF and TrueType programs are read, and the legacy Chinese, Japanese and Korean encodings are built in. What no table says cannot be read: Type 3 fonts, TrueType subsets without cmap and post tables, CID-keyed CFF fonts of no collection. Their glyphs are read by their codes where those are ASCII, or reported as unmapped
  • Images - JBIG2 images are listed without their data, as are images that cannot be made PNG: samples of other than 1, 2, 4, 8 or 16 bits, a Pattern colour space, inks whose function cannot be read or would take too long, damaged data; the warning image.unsupported_encoding says why. CMYK is made RGB without a colour profile, and CalRGB is read as RGB, so their colours are near but not as a profile would make them. JPEG and JPEG 2000 are handed on without their masks
  • Tagged PDF - of the structure tree, headings, tables, lists and the descriptions of figures are read, and its order where the white space of a page leaves the order open; where white space separates blocks it decides, so a text box that a word processor puts in the tree where it is anchored is still read where it stands. The tree's nesting of lists is not used: their levels are found by indent
  • No OCR - a scan without a text layer gives its images and the warning part.image_only

How it works

PDF file → objects and cross-references → content interpreter → layout → document
           (internal/file, syntax)         (internal/extract)   (internal/layout)
  1. Nothing is decoded that is not needed: image and font streams are not touched during text extraction.
  2. Streams are decompressed by a decoder made for a slice in memory (internal/inflate), about twice as fast as the standard library's, which has to serve a reader.
  3. Fonts are parsed once per document and shared by all pages.
  4. Pages are independent: each worker fills one part, and the parts are put together in page order.
  5. Drawing operators are skipped without converting their operands, which keeps pages full of vector graphics cheap.
  6. The layout keeps the order in which a page draws its text wherever the geometry does not speak against it, and uses it to choose between readings the geometry leaves open (a table drawn by rows against two columns).

Roadmap

  • The shared document model (go-fast-core)
  • Paragraphs and reading order
  • What the file declares about how text is shown (hidden, no_ink)
  • AES-256 encryption
  • Image data (JPEG, JPEG 2000, samples of any depth and colour space, CCITT fax, masks)
  • Page iterator, lines and words, the command-line tool
  • Headings, lists, running headers and footers; bold, italic and links
  • Tagged PDF: headings, tables, lists, the descriptions of figures and the order of the tree
  • Tables in files without tags, by how their text lines up
  • Tables in files without tags, by their drawn lines
  • Text from right to left in reading order

License

MIT License - see LICENSE. Notices for the tables generated from published data are in NOTICE. Changes are listed in CHANGELOG.md.

Copyright (c) 2025 Andrew O'Shei

Documentation

Overview

Package gofastpdf extracts the text and structure of PDF files into the document model shared by the go-fast libraries (github.com/AOShei/go-fast-core). It uses the standard library and go-fast-core only, starts no program, fetches nothing, runs nothing that a file contains, and does no OCR.

doc, err := gofastpdf.ExtractFile(ctx, "report.pdf", nil)
fmt.Print(doc.Markdown())

Two ways to read a file

Extract and ExtractFile return the whole document at once: its parts, and with them the document information, the outline, the attached files and the warnings. That is the entry point every go-fast library has, and Extractor is its form as a gofastcore.Extractor.

Open, OpenBytes and OpenReaderAt return a File, which reads nothing of the pages until it is asked:

f, err := gofastpdf.Open("report.pdf", nil)
defer f.Close()
for part, err := range f.Parts(ctx) {
	...
}

File.Parts hands out the parts in page order, reading several pages at a time, and keeps none of them: a file of any number of pages is gone through in the memory that the file, a few pages and a bounded amount of what was parsed take, plus about two hundred bytes for each page of the file. File.Page gives one page by its number, from any goroutine. Page.Lines gives more than the part has: the lines of the page with the font and size of each and the box of every word. File.Document is Extract on an open file.

The parts are the same whichever way they are read, with one difference for image data, which Page.Part describes. What Extract puts in the document as a whole, a File gives by its methods Metadata, Outline and Warnings; the last is final only when every part has been produced, since a page can add to it.

Reading stops when the context ends, between pages and inside a page whose content is long. Nothing is printed: what goes wrong is an error or a warning in the result.

Settings that only PDF has are the fields of Extractor, whose methods are the functions of this package: the size one stream may decode to, how much of what was parsed is kept, and whether tables are looked for by their rules.

The command gofastpdf, in cmd/gofastpdf, writes files as JSON, Markdown or text.

The document

A document has one part per page, of kind page, numbered as the pages are in the file also when only a range is extracted. A part's Width and Height are the page as it is displayed, in points: the crop box, turned by the page's rotation and scaled by its user unit. Every box of a block is in that space, with its origin at the top left. A page label that differs from the page's number is the part's Name.

Text blocks are paragraphs, in reading order. A PDF without tags does not say where a paragraph ends or in which order a page is read, so both are worked out from where the text is, and every text block has OriginInferred.

A table of a tagged PDF, which the structure tree says is one (Table, with rows TR and cells TD and TH), is a block of kind table with OriginNative. Its grid is the tree's: a cell takes the first column its row leaves free, RowSpan and ColSpan make merges, and the leading rows in THead, or all of TH, are HeaderRows. The visible text of each cell is laid out by itself; text in a cell that the file declares not shown or drawn with no ink stays out of the table, a block of its own with its reason, as such text is anywhere. A table over several pages is a block on each, with the rows that are on that page, and the block on a later page is Continued. A table whose text the page does not bear out, a row reaching into the next or cells that do not follow each other across the page, is taken for a tree made badly: its text is laid out as if the tree had no table there.

Elsewhere a table is found by how its text lines up, and its block has OriginInferred. Its rows are lines on one baseline; its columns are the white space that runs down between their cells, at the same place in every row; a cell that reaches over that space spans columns, as a merge. A region is a table only when it has two columns or more and three rows or more, most rows have text in several columns, the cells are short and lined up in their columns, and it is none of these: columns of prose, a list with bullets or numbers, a table of contents, code with its comments, names set in columns to be read down each, labels on a picture, or one label set again beside itself (the time scale of a schedule). A line set under a row closer than the rows are to each other continues that row's cells. The header rows are the first rows when they are all in bold and the rows under them are not, but for a fifth of their cells: bold used for emphasis here and there makes no header. Tables of the same columns set side by side, lists of different lengths each with a name and a value, are a table each, read down. Only text without a display reason, in no cell of a tagged table, is looked at.

Before that, a table drawn with rules is found by them, and its block has OriginInferred too. The thin lines and bars a page paints along its axes are joined where they meet into a grid; its columns lie between its upright rules and its rows between its level ones, and a rule missing inside it joins two cells into one over several columns or rows. Text goes to the cell that holds the middle of each piece of it; a line that the grid's edge cuts through stays out of the table. Text that the page draws in one go across an upright rule, the entries of two cells set apart by a gap, is cut where the rule passes between its strings, which the interpreter knows exactly; a space inside a string is not cut. Where a table is ruled between its columns and not between its rows, each line of text in a band of the grid is a row, unless its lines run on as sentences do. Where entries of several lines stand beside codes of one, each line of the first column begins a row instead: lines of four words or fewer, each with a line of the next column beside it, where no entry goes on from one row to the next. A grid is a table when it has two columns and two rows or more, at least two rows with text in two cells, text in a quarter of its cells or more, and cells that are not paragraphs of prose (30 words at the median), and it is not the frame of a page or lines on a picture. The header rows are found as for tables found by alignment. A page that draws a great many lines, a map or a hatching, is not followed past 131,072 path operators. Extractor.NoRuledTables leaves ruled tables out, and saves what following the paths costs. A table whose columns stand apart neither with white space nor with rules is not found: its text is in paragraph blocks, a row a line with its cells apart by tabs.

A paragraph that starts with the marker of a list item is a block of kind list_item: a bullet, a dash, or a number or letter that counts ("3.", "(a)", "iv)", "4.2.1"). The marker is in Block.Marker, out of the text, and Ordered says whether it counts; the renderers put it back in front. Every line that starts with a marker starts an item. Level is how deep the item is nested, by how far right its marker stands against the items before it on the page. Not markers: a decimal number, a year, an initial ("J. Smith"), an em dash (prose starts lines with it), an asterisk (more often a note), and a line with a tab after the marker, which is a row of a table. A numbered line set as a heading is a heading and keeps its number as Marker.

In a tagged PDF, a paragraph whose text is all in one item of a list of the structure tree (LI, in L) is a list_item with OriginNative. The layout starts a paragraph at each item and never joins the lines of two items, so that an item whose bullet is drawn and not written is an item of its own; a second paragraph of the same item stays a paragraph. The marker is the item's label (Lbl) where the text starts with it; else a marker as above, where a capital before a full stop ("C.", "IV.") and an asterisk count too, or a mark by itself at the start: a symbol, a character that could not be read (U+FFFD), the "o" that word processors set as a bullet. An item with no written marker has none, and the renderers set a dash in front of it. Ordered is what the list's ListNumbering attribute says, or else whether the marker counts. Level is found by indent, as above: programs nest the lists of the tree in more than one way. Paragraphs outside the items of the tree can still be items by their markers.

Headings are blocks of kind heading. In a tagged PDF, a block whose text is all part of one heading of the structure tree (H1 to H6, or H at the depth of the sections around it, through the role map) is that heading with OriginNative, and a page with such a heading has no other heading by type. A block that an entry of the outline names, on the page the entry points at, is a heading at the entry's level with OriginNative: the file says it is one. A level deeper than six, which an outline or nested H elements can give, is 6, with the real level in Attrs["level"] and the warning structure.heading_level_clamped on the part. Otherwise a short block is a heading when it is set at least 15 percent larger than the text of the document, or bold on one line where the text is not bold; its level is from its size, 1 for a title set about twice as large as the text, down to 4 for bold at the size of the text. A page with more such blocks than it can have headings, a map or a diagram, gets none by type. The size of the text of the document is the size most of it is set in, counted over the pages put in order so far and those that wait after them; a page read by itself uses its own.

Running headers and footers are blocks of kind header and footer: text that the pages repeat at their top or bottom, a title, a date, a page number, found by comparing each page with up to four pages on each side of it. The renderers of the shared model leave them out unless RenderOptions.Furniture asks for them. A paragraph that a page break splits is marked Continued on the page where it goes on, and the renderers run its two pieces into one. Both are decided as the pages are put in order, by Extract, File.Parts and File.Document; a page read by itself with File.Page is compared with nothing and has neither.

What the annotations of a page display is part of the page: the value shown in a form field, a note written on the page, a stamp. Their appearances are read after the content of the page, as a viewer paints them, and their text is in the paragraphs like any other. Two more things an annotation holds are text, and are blocks of their own:

  • What is written in an annotation, which a viewer shows in a window beside the page or in a list: a block of kind note, of type comment, with its author and date where the file has them, after the other blocks of its page.
  • The value of a form field whose appearance shows nothing, which a viewer would draw by itself: a paragraph at the place of the field, after the text that starts above it, with the full name of the field under the key "field" (gofastcore.AttrField). A choice gives the text of the option as it is displayed, a check box or radio button that is on the name of its state. A push button has no value, a signature is not text, and the value of a password field is not read.
  • The options of a choice field, a list box or a combo box: a note of type choices (gofastcore.NoteChoices), one option per line as it is displayed, in the order of the file, with the field's name, after the block of the field's value where there is one. It is there once for a field however many widgets show it, and has no display reason for being a list: a reader who opens it sees the options.

Both have OriginNative: the file says what they are. An annotation whose flags say it is not shown (Hidden, NoView), or that is in optional content that is off, has its text, displayed or written, with the reason hidden.

Anchors

Loc.Anchor is a name the file gives a block. A named destination, which links of the document and links to it from outside use (#nameddest=), names a place on a page; the block that begins there, a little below the place and not to its left, has the name, with Options.Spans. A destination that names a page, a place inside a block, a place no block begins near, or a running header or footer names no block. Finding every named destination means reading an object for each, as long as some pages take in a file with many, which is why it comes with the links. In a tagged PDF, an element of the structure tree with an identifier (/ID) gives it to the first block of its content, whatever the options; where both name a block, the destination wins. A name longer than 512 bytes is left out.

What a file stores and shows nowhere

A PDF can carry text that nobody who opens it sees: scripts, a packet of metadata in XML, entries of the file's own making in the document information, fields of a form that no page shows. A program that reads the extracted document reads it all the same, so it is extracted and marked with what it is in Attrs["stored"] (gofastcore.AttrStored), with no display reason: where it is says what it is. Nothing of it is run or followed.

  • A script that an action of a page or of an annotation on it would run is a code block on that page, after its other blocks: stored "macro", with Attrs["language"] "javascript".
  • What belongs to the file and to no page is in one part of kind stored, after the pages and numbered after them: the scripts that the document names or that its own actions and its form would run ("macro", with the name the document gives a script); entries of the document information other than the standard ones ("document_variable", as "name: value"); what the metadata packet says that Metadata does not ("custom_xml", as "property: values"); and the values of fields of the form that are on no page ("form_field", with the field's name).
  • The data of an XFA form, which only Adobe's viewer shows: each value filled in, as "form_field" with the path of its element as the field's name (form1.address.city). A value that the form also has in an ordinary field, as a static XFA form does, is read there and not said again. The template of the form, its captions and its static text, is not read.
  • What follows the last %%EOF of the file, padding aside, when it is text: UTF-8, or Latin-1 without control characters ("after_end"). An update added to a file ends in a %%EOF of its own, so only what follows the last one counts. The warning input.trailing_data says how many bytes follow the end, also when they are not text.

The stored part, and a page's scripts, have no display reason: they are where they are, which says what they are. A page's scripts are the only blocks of a page with Attrs["stored"]; so that every stored datum is found, look at the attribute of every block, not only at the stored part. The renderers of the shared model leave out the stored part and a page's scripts unless RenderOptions.Stored asks for them, or RenderOptions.StoredKinds for some kinds ("macro" for the scripts alone); a script then stands in its place on its page.

A value is given once, and values that say nothing in words (a yes or no, a number, a date, an identifier) are left out; anything with words in it is kept, whatever property it is under. The stored part is there only when the whole document is read: Options.Parts and Limits.MaxParts leave it out, and File.Parts gives it last. Its text is bounded (16 MiB) and counted against the limit on text.

The document information becomes Metadata: the title; the author as one entry, not split; subject and keywords; the creating program as Application and the producing one as Extra["producer"]; the dates; the language of the catalog; and whether the file was encrypted. The metadata packet (XMP) adds to it. Its lists of authors (dc:creator) and of keywords (dc:subject) are the authors and the keywords, an entry for each item as the file declares it, unless the information was changed after the packet (ModDate later than xmp:MetadataDate); its pdf:Keywords is one entry where it has no list. What the information leaves out is taken from the packet: the title, the subject (dc:description), the programs, the dates and the language. Properties are known by their namespace, whatever their prefix. The bookmarks become Outline, each with the page it points at and how far down that page. Files attached to the document or to a page become Children.

Options

The options are those of gofastcore.Options. Here they mean:

  • Workers: pages read at a time, by Extract and by File.Parts. The result is the same for any number.

  • Images: with ImagesMeta, which is what options mean that name no mode, an image block stands where each image is, with its size in pixels; its ID is "obj-" and the number of the image's object, or, for an image inside a content stream, "inline-", the number of its page, a hyphen and its count on that page. With ImagesData the first block of each image also has its data: JPEG and JPEG 2000 as they are in the file, without their masks; samples, of 1 to 16 bits, and CCITT fax data as PNG. The samples are made colours by their Decode array and colour space: gray, RGB, CMYK (made RGB by 1-C times 1-K, without a profile), Lab, an ICC profile by its number of components, a table of colours (Indexed), or inks (Separation, DeviceN), made colours of one of these by the file's function of their tints: sampled, exponential, stitching or PostScript calculator. A soft mask, a mask image or a range of colours masked makes the PNG's alpha. A stencil mask, which paints in the colour current where it is drawn, is black where it paints and white elsewhere. Damaged fax data gives the rows before the damage, the rest white. An image inside a content stream is read as an image object is: its abbreviated keys, filters and colour spaces written out, a colour space it names looked up in the resources, and its data running to EI, or as far as its /L says. JBIG2 images have no data, nor have images that cannot be made PNG: samples of other than 1, 2, 4, 8 or 16 bits, a colour space that is not read (Pattern, an ICC profile of other than 1, 3 or 4 components and no alternate, inks whose function cannot be read or would take too long), damaged data. Their page gets image.unsupported_encoding, which says why. With ImagesNone there are no image blocks. In a tagged PDF an image drawn as part of a figure that the structure tree describes (/Alt) has that description as its text. A block for every image costs under one percent of the time on most documents, and up to as much again on a page that is nearly all images.

  • Password: tried as the user password and as the owner password. The empty user password is always tried.

  • Keys: private keys, for a file encrypted for a certificate (the public-key security handler, /Adobe.PubSec). Every key is tried on every recipient the file names. Keys are RSA: the file's envelope holds its key encrypted with RSA, with PKCS #1 v1.5 or OAEP, and the envelope's own content in AES or triple DES. An envelope in RC2, which old versions of Acrobat wrote, is ErrUnsupported. A file that no key opens is gofastcore.ErrKeyRequired; a password does not open it.

  • Parts: a range of pages, for Extract, File.Parts and File.Document. A range that holds no page of the file is gofastcore.ErrNoPartsSelected. File.Page gives any page.

  • Limits: MaxInputBytes (default 1 GiB) is checked before the input is read. MaxDecodedBytes (default 1 GiB) bounds what the streams of a document decode to, taken together and counted in page order: the document ends before the page that would exceed it. MaxTextBytes (default 256 MiB) bounds the text of a document: the titles of its outline, the names that page labels give its parts, and the text of its blocks. Every block counts as its text and 128 bytes more, about what a block takes written down, so that a document of very many blocks without text, such as a page that draws one image a hundred thousand times, is bounded as well. The page that reaches the limit is cut before the block that does not fit, and nothing after it is read. MaxParts keeps the first pages of the range. MaxDepth bounds how deep attached files are followed. A limit that cuts the document adds limit.exceeded; File.Parts ends with ErrLimitExceeded there.

    Decoded bytes and text are counted for a document and the files attached to it together, through the budgets of gofastcore that a context carries: an attached file is read within what its document has left, and this package reads within what it is given when it is itself the Child of another extractor.

    Both are counted where the pages are put in order, a page at a time, and not while a page is being read: pages are read side by side, and counting them as they finish would make the place of the cut depend on which finished first. What is held and not yet counted is the pages being read and those waiting to be handed on, at most three for each worker, each of at most 16 MiB of text.

  • Child: the extractor for attached files. Without one they are listed with their names and sizes, and nothing of them is decoded.

  • Spans: gives the text blocks spans of bold and italic, by the fonts of their words, and of links. A link is a link annotation of the page: the words it covers, each word as a whole, go to the address of its URI action, or, for a destination in the document, to "#page=N" (the open parameter of a PDF for page N). Links to other files, links that are hidden and addresses over 4 KiB have no span. Link targets count against Limits.MaxTextBytes. A word is placed by its share of the characters of its run, and a word that the joining of lines changed may have no span. Spans take a tenth more time on pages of text, up to a third on short documents. With Spans, the names of the destinations of the document are also anchors: see "Anchors".

Text

The text of a block follows the conventions of the shared model. The lines of a paragraph are joined with one space. A hyphen at the end of a line stays and the next line follows without a space, so that "well-" and "known" are "well-known" and "inter-" and "national" are "inter-national". A soft hyphen at the end of a line, between the letters of a word, is dropped and the word joined again; anywhere else it stays. Ligatures are written as their letters, and so are the Arabic presentation forms, the forms of letters at the start, in the middle and at the end of a word. A character the file gives no meaning for is U+FFFD, and so is a control character.

Two characters in a block's text are put there by this package. A tab stands where two pieces of a line are more than twice the font size apart: a label and its value, the cells of a row. A line break stands between two such rows, which are kept in one block. Text set with its letters apart is read as its words when the rest of its line shows that it is one; a line that consists of nothing but single letters evenly apart is read as a word, which is wrong for a row of separate letters.

The order of reading is found by cutting the page along the white space between its blocks. Where a page can be cut in more than one way, the cut is taken that agrees best with the order in which the page draws its text: a page drawn column by column is read by columns, a table drawn row by row is read by rows. In a tagged PDF the order of the structure tree takes the place of the order drawn, each block by the first of its content in the tree, and a block the tree does not place right after the block drawn before it. The white space still decides where it separates blocks: a text box at the top of a page, which a word processor puts in the tree where the box is anchored, is read first, and a page drawn from top to bottom in one column is read so.

The characters of the text are what the file says each glyph is: a font's ToUnicode CMap, its encoding and the names of its glyphs, or codes that are Unicode already. For the fonts of Chinese, Japanese and Korean, the CMaps the specification predefines for the legacy encodings (Shift-JIS, EUC, GBK, Big Five, UHC and the others) are built in, from Adobe's published resources: they give a code's CID, and with it its width, and the CID's character in its collection (Adobe-GB1, -CNS1, -Japan1, -Korea1, -KR) gives the text where the file does not. A CIDFont of type 2 whose CIDs are of no collection takes the characters of its glyphs from the cmap of its TrueType program, or their names in its 'post' table, read the first time a code has no text otherwise; a glyph neither gives a character has the text of the glyph with its outline in a known font. The known fonts are Noto Sans, Noto Naskh and Noto Kufi Arabic, Regular and Bold, of the versions the table was made from: Firefox embeds subsets of them whose ToUnicode CMap gives U+0000 (read as no text) to the pieces a letter is drawn in, its body without its dots and the dots, and the pieces are put together into the letter. A simple font without a ToUnicode CMap that names no encoding has its program's: the encoding of a Type 1 or CFF program, as glyph names, unless most of its letters are not their codes' (names scrambled by the program that made them); for a symbolic TrueType program, the glyph its symbol or Macintosh cmap gives each code and that glyph's character, or WinAnsiEncoding when it reaches its glyphs by Unicode only. A name in /Differences that says nothing by itself is looked up in a TrueType program's 'post' table. A glyph of which nothing is known is U+FFFD.

A line with letters of a script written from right to left (Hebrew, Arabic and the others) is read in the order it is written, whatever order the page draws it in: from left to right as it is seen, word by word, or glyph by glyph from right to left. The line is put together from where its glyphs stand, and the Unicode bidirectional algorithm gives the order of reading: numbers and Latin words read from left to right within it, spaces and punctuation take the direction of what surrounds them, and a glyph that stands for more than one letter (a ligature of lam and alef) keeps its letters in their order. The line reads from right to left when the letters at both its ends are of such a script, or else when most of its words are. Brackets read from right to left are mirrored where the file gives the glyph drawn and not the character it stands for, which is told by which reading pairs them. The paragraphs of such lines are found as for others, with the start of a line at its right. A mark (a vowel sign, a hamza, the dots of a letter drawn in pieces) that the page draws by itself on the glyph before it, however far up or down, is read with that glyph, and a letter and the hamza on it are the letter with hamza.

What the file declares

Text is extracted whether or not a reader sees it. Where the file itself declares, by one switch or one value, that text is not shown or is drawn with no ink, the text's block (Block.Display) has the reason; following the file's own inheritance, through forms, groups and membership dictionaries, is reading the declaration. Nothing else gives a reason. The caller decides what to do with the text, for instance with RenderOptions.ExcludeDisplay.

hidden   content in optional content (a layer) that is off in the
         document's default configuration (/OFF, /BaseState /OFF,
         or a membership dictionary whose policy its layers make
         off); the text of an annotation whose flags are Hidden or
         NoView, and the value of such a form field
no_ink   text in render mode 3, neither filled nor stroked, or 7,
         clip only, when nothing is painted through it; text whose
         opacity is 0 for what its mode paints (/ca for the fill,
         /CA for the stroke), by its graphics state or that of the
         transparency group it is drawn in

The searchable text of a scanned page is text in render mode 3 over the picture of the page: it is no_ink, and leaving out no_ink leaves out a scan's text.

Not judged: colour against what is under the text, its size, where it is on the page or outside it, what is painted over it, clipping paths, soft masks and blend modes, how much of the page an image covers. Text with a reason is laid out apart from the rest, so that the other blocks are what they would be without it. The absence of a reason says nothing about whether text can be seen. Characters are kept as the file gives them, zero-width characters, tag characters and bidirectional controls included. Judging text by what it may do to a reader or a program is outside this package.

Warnings

The codes of the shared model are used where they apply. Those that need a word about PDF:

input.repaired            the cross-reference data was unusable, or
                          wrong about some object, and the objects
                          were found by scanning the file
input.ambiguous           the file had to be read by scanning and
                          defines an object more than once. The last
                          definition is read, as it is the newest in
                          a file that was saved in steps
input.active_content      JavaScript (in the name tree, on opening
                          or closing, on a page, a link or a form
                          field) or an action that starts a program
input.external_reference  a stream or an image whose data is in
                          another file, a page of another document
                          shown in this one, an action that goes to
                          another file, sends a form or loads data,
                          a launch that names a file. A link to an
                          address is an ordinary link and is not one
input.trailing_data       bytes other than padding follow the last
                          %%EOF of the file; the message says how
                          many. Their text, where they are text, is
                          in the stored part (Attrs["stored"] is
                          after_end), which then has the warning;
                          otherwise the document has it

Scripts and actions are looked for on the pages that are extracted and in the catalog and the form fields; no script is read.

limit.exceeded, an error, reports what a limit cut of the output: of the Limits, and of the fixed bounds of this package that SECURITY.md lists, such as the annotations read on a page or the length of a name. It is given once for each limit, on the part or the document that was cut, with a count ("names longer than 1024 bytes were cut there (2 names, 600 bytes left out)"). A bound on what is used only inside the package, such as the saved graphics states, gives none, and no other code is given for a cut: without limit.exceeded nothing was cut. Of the other warnings of the document as a whole, eight of a code are kept, in the order of their messages, and one more counts the others.

Codes that only this package uses, each for a fact about the file:

pdf.glyph_text_assumed          characters of a font that does not
                                say what its glyphs are were read as
                                the characters their codes stand for
pdf.glyph_text_by_outline       glyphs the file gives no text were
                                read by their outlines, which are
                                those of the Noto Arabic fonts the
                                library knows
pdf.font_missing                text is set in a font that the
                                page's resources do not define
pdf.content_stream_damaged      a content stream is damaged; what
                                came before the damage was read
pdf.content_stream_unreadable   a content stream could not be decoded
pdf.content_bytes_skipped       bytes of a content stream are not
                                valid syntax and were skipped
pdf.object_unreadable           an object could not be read
pdf.page_tree_damaged           a node of the page tree is not what
                                it should be
pdf.xref_section_unreadable     a section of the cross-reference
pdf.xref_entry_unreadable       data, or an entry of it, is unusable
pdf.string_undecryptable        a string of an encrypted file could
                                not be decrypted

Errors

An error means that there is no document. It wraps one of the errors of the shared model: ErrMalformed for input that is not a readable PDF, including one without pages; ErrPasswordRequired and ErrWrongPassword; ErrKeyRequired for a file encrypted for a certificate that no key of Options.Keys opens; ErrUnsupported for an encryption this package does not have; ErrLimitExceeded for input larger than MaxInputBytes; ErrNoPartsSelected. A file that can be read in part is not an error: a page that cannot be read is a part with part.failed, in its place.

Index

Examples

Constants

View Source
const (
	// DefaultMaxInputBytes is the largest input read.
	DefaultMaxInputBytes = 1 << 30
	// DefaultMaxDecodedBytes is the most that the streams of one
	// document may decode to, taken together.
	DefaultMaxDecodedBytes = 1 << 30
)

The defaults for the limits of gofastcore.Limits that are left zero.

View Source
const (
	// WarnGlyphTextAssumed: characters on the page are set in a font
	// that does not say which characters its glyphs are; they were read
	// as the characters their codes stand for.
	WarnGlyphTextAssumed = "pdf.glyph_text_assumed"
	// WarnGlyphTextByOutline: characters on the page are set in glyphs
	// that the file gives no text; they were read by their outlines,
	// which are those of glyphs of the Noto Arabic fonts the library
	// knows (Sans, Naskh and Kufi, Regular and Bold, one version each).
	WarnGlyphTextByOutline = "pdf.glyph_text_by_outline"
	// WarnFontMissing: text on the page is set in a font that the page's
	// resources do not define.
	WarnFontMissing = "pdf.font_missing"
	// WarnContentStreamDamaged: a content stream of the page is damaged;
	// what could be decoded before the damage was read.
	WarnContentStreamDamaged = "pdf.content_stream_damaged"
	// WarnContentStreamUnreadable: a content stream of the page could
	// not be decoded at all.
	WarnContentStreamUnreadable = "pdf.content_stream_unreadable"
	// WarnContentBytesSkipped: bytes of a content stream of the page are
	// not valid syntax and were skipped.
	WarnContentBytesSkipped = "pdf.content_bytes_skipped"
	// WarnObjectUnreadable: an object of the file could not be read and
	// was taken as null. It is a warning of the document.
	WarnObjectUnreadable = "pdf.object_unreadable"
	// WarnPageTreeDamaged: a node of the page tree is not what it should
	// be; the pages under it may be missing.
	WarnPageTreeDamaged = "pdf.page_tree_damaged"
	// WarnXRefSectionUnreadable: a section of the cross-reference data
	// could not be read.
	WarnXRefSectionUnreadable = "pdf.xref_section_unreadable"
	// WarnXRefEntryUnreadable: an entry of the cross-reference data is
	// unusable.
	WarnXRefEntryUnreadable = "pdf.xref_entry_unreadable"
	// WarnStringUndecryptable: a string of an encrypted file could not be
	// decrypted.
	WarnStringUndecryptable = "pdf.string_undecryptable"
)

Warning codes that only this library uses. Each states a fact about the file or about what was done with it.

View Source
const Format = "pdf"

Format is the name of the format in Source.Format.

Variables

View Source
var ErrClosed = errors.New("gofastpdf: the file is closed")

ErrClosed is returned by the methods of a File that has been closed.

Functions

func Extract

func Extract(ctx context.Context, r io.ReaderAt, size int64, opts *gofastcore.Options) (*gofastcore.Document, error)

Extract reads a PDF file of size bytes from r and returns it as a document: one part per page, the text of each page as paragraphs in reading order.

opts may be nil. See the package documentation for what each option does here. Extract is Open, Document and Close in one.

Example

The whole document at once, from anything that can be read at an offset.

package main

import (
	"bytes"
	"context"
	"fmt"
	"log"
	"os"

	gofastpdf "github.com/AOShei/go-fast-pdf"
)

func main() {
	data, err := os.ReadFile("testdata/fixtures/english.pdf")
	if err != nil {
		log.Fatal(err)
	}
	doc, err := gofastpdf.Extract(context.Background(), bytes.NewReader(data), int64(len(data)), nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(doc.Metadata.Title)
	fmt.Println(len(doc.Parts), "pages")
	fmt.Println(doc.Parts[0].Blocks[0].Text)
}
Output:
Sample document
3 pages
Extracting text from documents

func ExtractFile

func ExtractFile(ctx context.Context, path string, opts *gofastcore.Options) (*gofastcore.Document, error)

ExtractFile is Extract for the file at path. The name of the file is the document's Source.Name unless opts gives another.

Example

The whole document of a file on disk, with options.

package main

import (
	"context"
	"fmt"
	"log"
	"strings"

	gofastcore "github.com/AOShei/go-fast-core"
	gofastpdf "github.com/AOShei/go-fast-pdf"
)

func main() {
	opts := &gofastcore.Options{Parts: gofastcore.PartRange{First: 2, Last: 2}}
	doc, err := gofastpdf.ExtractFile(context.Background(), "testdata/fixtures/english.pdf", opts)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(doc.Source.Name)
	for _, part := range doc.Parts {
		fmt.Printf("page %d: %d blocks, %d words\n", part.Number, len(part.Blocks), len(strings.Fields(part.Text())))
	}
}
Output:
english.pdf
page 2: 6 blocks, 356 words

Types

type Extractor

type Extractor struct {
	// MaxStreamBytes is the most that one stream of the file may decode
	// to: a page's content, an image, an attached file. The default is
	// 64 MiB, or Limits.MaxDecodedBytes where that is lower. A stream
	// that is larger is cut there and its part gets limit.exceeded.
	MaxStreamBytes int64
	// ObjectStreamCacheBytes is how much decoded object-stream data is
	// kept, so that an object stream is not decoded again for every
	// object in it. The default is 64 MiB.
	ObjectStreamCacheBytes int64
	// ObjectCacheBytes is how much of the parsed objects of a file is
	// kept, so that an object used by many pages is parsed once. The
	// default is 4 MiB. When more is kept, all of it is let go: this is
	// what keeps a file of many pages from taking more memory with every
	// page that is read.
	ObjectCacheBytes int64
	// NoRuledTables leaves out the tables found by the rules they are
	// drawn with, and the following of a page's paths that finding them
	// takes: about 5 percent of the instructions over a mixed set of
	// documents, less on pages of text. Tables of tagged files, and those
	// found by how their text lines up, are found as before.
	NoRuledTables bool
}

Extractor extracts PDF files into the shared document model. The zero value is ready to use and safe for concurrent use; the functions of this package that are not its methods use the zero value.

Settings that only PDF has are fields of this type. Zero means the default for each.

Example

Settings that only PDF has are fields of an Extractor.

package main

import (
	"context"
	"fmt"
	"log"

	gofastpdf "github.com/AOShei/go-fast-pdf"
)

func main() {
	e := &gofastpdf.Extractor{MaxStreamBytes: 8 << 20}
	doc, err := e.ExtractFile(context.Background(), "testdata/fixtures/english.pdf", nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(e.Formats(), len(doc.Parts))
}
Output:
[pdf] 3

func (*Extractor) Extract

func (e *Extractor) Extract(ctx context.Context, r io.ReaderAt, size int64, opts *gofastcore.Options) (*gofastcore.Document, error)

Extract implements gofastcore.Extractor. See the function Extract.

func (*Extractor) ExtractFile

func (e *Extractor) ExtractFile(ctx context.Context, path string, opts *gofastcore.Options) (*gofastcore.Document, error)

ExtractFile is Extract for the file at path. See the function ExtractFile.

func (*Extractor) Formats

func (*Extractor) Formats() []string

Formats returns the format this extractor handles: "pdf".

func (*Extractor) Open

func (e *Extractor) Open(path string, opts *gofastcore.Options) (*File, error)

Open opens the PDF file at path. See the function Open.

func (*Extractor) OpenBytes

func (e *Extractor) OpenBytes(data []byte, opts *gofastcore.Options) (*File, error)

OpenBytes opens a PDF file that is in memory. See the function OpenBytes.

func (*Extractor) OpenReaderAt

func (e *Extractor) OpenReaderAt(r io.ReaderAt, size int64, opts *gofastcore.Options) (*File, error)

OpenReaderAt opens a PDF file of size bytes read from r. See the function OpenReaderAt.

type File

type File struct {
	// contains filtered or unexported fields
}

File is an open PDF file. Nothing of its pages is read until a page is asked for, and no page is kept once it has been handed out, so a file of any number of pages can be gone through in the memory that the file itself and a few pages take.

A File is safe for use by several goroutines at once. Close it when done with it.

The whole file is held in memory while it is open: a PDF is read from its end and by offsets all over it.

func Open

func Open(path string, opts *gofastcore.Options) (*File, error)

Open opens the PDF file at path. opts may be nil; see the package documentation for what each option does. An error wraps one of the errors of gofastcore: ErrMalformed, ErrPasswordRequired, ErrWrongPassword, ErrUnsupported, ErrLimitExceeded, ErrNoPartsSelected.

Example

Page by page, without holding the document: each part is handed out as soon as its turn comes, and several pages are read at a time.

package main

import (
	"context"
	"fmt"
	"log"

	gofastpdf "github.com/AOShei/go-fast-pdf"
)

func main() {
	f, err := gofastpdf.Open("testdata/fixtures/english.pdf", nil)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	fmt.Println(f.NumPages(), "pages by", f.Metadata().Authors[0])
	for part, err := range f.Parts(context.Background()) {
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("page %d: %d blocks\n", part.Number, len(part.Blocks))
	}
}
Output:
3 pages by go-fast-pdf tests
page 1: 6 blocks
page 2: 6 blocks
page 3: 2 blocks

func OpenBytes

func OpenBytes(data []byte, opts *gofastcore.Options) (*File, error)

OpenBytes opens a PDF file that is in memory. The data is used as it is, not copied: it must not change while the File is open.

Example

A file that is already in memory.

package main

import (
	"fmt"
	"log"
	"os"

	gofastpdf "github.com/AOShei/go-fast-pdf"
)

func main() {
	data, err := os.ReadFile("testdata/fixtures/english.pdf")
	if err != nil {
		log.Fatal(err)
	}
	f, err := gofastpdf.OpenBytes(data, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()
	fmt.Println(f.NumPages())
}
Output:
3

func OpenReaderAt

func OpenReaderAt(r io.ReaderAt, size int64, opts *gofastcore.Options) (*File, error)

OpenReaderAt opens a PDF file of size bytes read from r. All of it is read at once; r is not used after OpenReaderAt returns.

Example

A file read from anything that can be read at an offset.

package main

import (
	"fmt"
	"log"
	"os"

	gofastpdf "github.com/AOShei/go-fast-pdf"
)

func main() {
	in, err := os.Open("testdata/fixtures/english.pdf")
	if err != nil {
		log.Fatal(err)
	}
	defer in.Close()
	info, err := in.Stat()
	if err != nil {
		log.Fatal(err)
	}
	f, err := gofastpdf.OpenReaderAt(in, info.Size(), nil)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()
	fmt.Println(f.Metadata().Title)
}
Output:
Sample document

func (*File) Close

func (f *File) Close() error

Close releases the file. The parts, pages and lines that were handed out stay valid. Closing twice is not an error.

func (*File) Document

func (f *File) Document(ctx context.Context) (*gofastcore.Document, error)

Document reads the selected pages and returns the whole document, as Extract does: the parts, and with them the document information, the outline, the attached files and the warnings of the file.

Example

The whole document from an open file, as Extract gives it.

package main

import (
	"context"
	"fmt"
	"log"

	gofastpdf "github.com/AOShei/go-fast-pdf"
)

func main() {
	f, err := gofastpdf.Open("testdata/fixtures/english.pdf", nil)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	doc, err := f.Document(context.Background())
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(len(doc.Parts), "parts")
}
Output:
3 parts

func (*File) Metadata

func (f *File) Metadata() gofastcore.Metadata

Metadata returns what the file says about itself: title, author, dates, the program that made it. No page is read for it.

func (*File) NumPages

func (f *File) NumPages() int

NumPages returns the number of pages in the file, whatever range of them the options select.

func (*File) Outline

func (f *File) Outline() []gofastcore.OutlineItem

Outline returns the bookmarks of the file, each with the page it points at. No page is read for it.

func (*File) Page

func (f *File) Page(n int) (*Page, error)

Page returns page n of the file, the first being 1. Any page of the file can be asked for, whatever range the options select. Nothing is read until a method of the page is called.

Example

One page by its number, from any goroutine.

package main

import (
	"fmt"
	"log"

	gofastpdf "github.com/AOShei/go-fast-pdf"
)

func main() {
	f, err := gofastpdf.Open("testdata/fixtures/english.pdf", nil)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	page, err := f.Page(3)
	if err != nil {
		log.Fatal(err)
	}
	part, err := page.Part()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("page %d is %.0f by %.0f points and has %d blocks\n", part.Number, part.Width, part.Height, len(part.Blocks))
}
Output:
page 3 is 595 by 842 points and has 2 blocks

func (*File) Parts

func (f *File) Parts(ctx context.Context) iter.Seq2[gofastcore.Part, error]

Parts returns the parts of the selected pages, one at a time and in page order. Several pages are read at a time (Options.Workers), a few ahead of the one being handed out, and none is kept after it has been handed out.

A part is never an error: a page that cannot be read is a part with part.failed. The error is not nil once, at the end, when the parts could not all be produced: the context ended, or a limit of Options.Limits was reached (ErrLimitExceeded). The part that comes with an error is empty.

The parts are those of Document. Stopping the loop early stops the reading.

Example (Display)

What the file declares about how text is shown is on its blocks: hidden for content the file switches off, no_ink for text drawn with no paint. Such text is extracted like any other.

package main

import (
	"context"
	"fmt"
	"log"

	gofastpdf "github.com/AOShei/go-fast-pdf"
)

func main() {
	f, err := gofastpdf.Open("testdata/fixtures/english.pdf", nil)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	declared := 0
	for part, err := range f.Parts(context.Background()) {
		if err != nil {
			log.Fatal(err)
		}
		for _, block := range part.Blocks {
			if block.Display != 0 {
				declared++
			}
		}
	}
	fmt.Println(declared, "blocks with a display reason")
}
Output:
0 blocks with a display reason

func (*File) Warnings

func (f *File) Warnings() []gofastcore.Warning

Warnings returns what concerns the file as a whole, as the warnings of a Document do: that it was read through repair, that it holds scripts, that it points outside itself. What is known without reading a page is there from the start; a page that is read can add input.active_content or input.external_reference, so the value is final only when every part has been produced.

type Line

type Line struct {
	// Text is the text of the line by itself. The text of a block joins
	// its lines by the conventions of the shared model, which this does
	// not: a hyphen at the end of the line is there, and nothing of the
	// next line.
	Text string
	// BBox is the box of the line on its page, in the space of the
	// part: points, origin at the top left.
	BBox gofastcore.Rect
	// Block is the index in Part.Blocks of the paragraph the line is in,
	// for the part that Page.Part returns for the same page.
	Block int
	// Display is what the file declares about how the line is shown:
	// that of its block.
	Display gofastcore.Display
	// Font is the name of the font that most of the line is set in,
	// without the tag of a subset, and Size the height it is displayed
	// at, in points.
	Font string
	Size float64
	// Words are the stretches of the line between its spaces and tabs,
	// in the order of the line.
	Words []Word
}

Line is one line of text on a page, with more detail than a block has: where the line is, the font it is set in, and where each of its words is.

type Page

type Page struct {
	// contains filtered or unexported fields
}

Page is one page of an open file.

func (*Page) Lines

func (p *Page) Lines() ([]Line, error)

Lines reads the page and returns its lines of text, block by block in the order of the blocks of its part, the lines of a block from its first to its last. Images have no lines.

A page that cannot be read has no lines; its part says why. The error is ErrClosed after Close.

Example

The lines of a page, with their fonts and the boxes of their words.

package main

import (
	"fmt"
	"log"

	gofastpdf "github.com/AOShei/go-fast-pdf"
)

func main() {
	f, err := gofastpdf.Open("testdata/fixtures/english.pdf", nil)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	page, err := f.Page(1)
	if err != nil {
		log.Fatal(err)
	}
	lines, err := page.Lines()
	if err != nil {
		log.Fatal(err)
	}
	title := lines[0]
	fmt.Printf("%q in %s at %.0f points\n", title.Text, title.Font, title.Size)
	for _, word := range title.Words {
		fmt.Printf("%-10s from %3.0f to %3.0f\n", word.Text, word.BBox.X0, word.BBox.X1)
	}
}
Output:
"Extracting text from documents" in Times-Roman at 15 points
Extracting from  72 to 134
text       from 138 to 161
from       from 164 to 193
documents  from 197 to 262

func (*Page) Number

func (p *Page) Number() int

Number returns the number of the page in its file, from 1.

func (*Page) Part

func (p *Page) Part() (gofastcore.Part, error)

Part reads the page and returns its part, as Document and Parts give it. A page that cannot be read is a part with part.failed, not an error; the error is ErrClosed after Close.

A page read by itself knows nothing of the pages before it. With Options.Images at ImagesData, each image therefore has its data on the first block that shows it on this page, also when an earlier page shows it too, where Document and Parts give the data once for the document. The limits on decoded bytes and on text apply to the page by itself. And it is compared with no other page: it has no running headers or footers, no paragraph of it continues the page before, and its headings are found by the type of this page alone.

type Word

type Word struct {
	// Text is the word as it stands in the text of its line.
	Text string
	// BBox is the box of the word on its page. It runs from where the
	// word begins on the line to where it ends, as wide as its glyphs
	// are said to be by their font, and as high as the line.
	BBox gofastcore.Rect
}

Word is one word of a line: what stands between two spaces.

Directories

Path Synopsis
bench
compare command
Command compare measures this library beside other programs that extract text from PDF files, on the same files, and writes the table that the README shows.
Command compare measures this library beside other programs that extract text from PDF files, on the same files, and writes the table that the README shows.
cmd
gofastpdf command
Command gofastpdf extracts the text and structure of PDF files.
Command gofastpdf extracts the text and structure of PDF files.
internal
ccitt
Package ccitt decodes images coded as fax machines code them: ITU-T T.4 (Group 3, one- and two-dimensional) and T.6 (Group 4), as the CCITTFaxDecode filter of a PDF gives them.
Package ccitt decodes images coded as fax machines code them: ITU-T T.4 (Group 3, one- and two-dimensional) and T.6 (Group 4), as the CCITTFaxDecode filter of a PDF gives them.
charset
Package charset holds the fixed tables that turn what a PDF file says about text into Unicode: glyph names, the encodings the specification names, the widths of the standard fonts, and the encoding of text strings outside content streams.
Package charset holds the fixed tables that turn what a PDF file says about text into Unicode: glyph names, the encodings the specification names, the widths of the standard fonts, and the encoding of text strings outside content streams.
content
Package content reads content streams: the operators that draw a page and their operands.
Package content reads content streams: the operators that draw a page and their operands.
extract
Package extract interprets a page's content streams and produces its text and image list.
Package extract interprets a page's content streams and produces its text and image list.
file
Package file reads the structure of a PDF file: the cross-reference data, the objects, the streams and the page tree.
Package file reads the structure of a PDF file: the cross-reference data, the objects, the streams and the page tree.
font
Package font turns a font dictionary into what text extraction needs: how a string splits into character codes, the text of each code, and how far each glyph advances.
Package font turns a font dictionary into what text extraction needs: how a string splits into character codes, the text of each code, and how far each glyph advances.
function
Package function evaluates the functions of a PDF file (ISO 32000-2, 7.10): sampled (type 0), exponential (type 2), stitching (type 3) and PostScript calculator (type 4) functions.
Package function evaluates the functions of a PDF file (ISO 32000-2, 7.10): sampled (type 0), exponential (type 2), stitching (type 3) and PostScript calculator (type 4) functions.
inflate
Package inflate decompresses zlib streams (RFC 1950, RFC 1951) that are held in memory.
Package inflate decompresses zlib streams (RFC 1950, RFC 1951) that are held in memory.
layout
Package layout turns the text runs of a page into blocks in reading order.
Package layout turns the text runs of a page into blocks in reading order.
pdftest
Package pdftest holds the test harness for go-fast-pdf: a builder that assembles PDF files in memory, the pdftotext oracle, the accuracy scorer, the golden-file helper and the runner of the defect cases.
Package pdftest holds the test harness for go-fast-pdf: a builder that assembles PDF files in memory, the pdftotext oracle, the accuracy scorer, the golden-file helper and the runner of the defect cases.
syntax
Package syntax reads PDF objects from a byte slice.
Package syntax reads PDF objects from a byte slice.

Jump to

Keyboard shortcuts

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