Docs / Guides

Text extraction

PdfReader interprets a page's content stream and decodes its text, as plain text or as runs with their position, font and size.

Plain text and positioned runs

ExtractText(pageIndex) returns a page's text, with newlines between lines and spaces where there is a visible gap. ExtractTextWithPositions returns the individual runs.

Program.cs
using SoftZenPdf;

var reader = PdfReader.Open("hello.pdf");
Console.WriteLine(reader.ExtractText(0));

foreach (var run in reader.ExtractTextWithPositions(0))
    Console.WriteLine($"{run.Text} at ({run.X1:0}, {run.Y1:0}), {run.FontSize}pt {run.FontName}");
PdfTextRunMeaning
TextThe decoded text of one text-showing operation
X1, Y1, X2, Y2Bounding box in points, from the font's descent to its ascent
FontSizeEffective size on the page, after any scaling
FontNameFont name without the subset prefix
AngleText direction in degrees, counter-clockwise; 0 for horizontal text

All pages at once

Program.cs
using SoftZenPdf;

var pages = PdfReader.Open("report.pdf").ExtractText();
for (var i = 0; i < pages.Count; i++)
    Console.WriteLine($"--- page {i + 1}: {pages[i]}");

Reading order and options

By default text comes out in content-stream order, the order the page draws it. That is usually reading order, but not always. TextOrder.Visual groups runs into lines from top to bottom, each left to right, which helps with forms and simple layouts. IncludeAnnotations (on by default) includes text shown in annotation appearances, such as filled form fields.

Program.cs
using SoftZenPdf;

var reader = PdfReader.Open("form-filled.pdf");
var options = new TextExtractionOptions { Order = TextOrder.Visual, IncludeAnnotations = true };
Console.WriteLine(reader.ExtractText(0, options));

foreach (var warning in reader.Warnings)
    Console.WriteLine($"warning: {warning}");

Neither order reconstructs multi-column layouts: lines from side-by-side columns are interleaved in visual order.

How characters are decoded

Characters are mapped to Unicode through, in order: the font's ToUnicode CMap, its encoding (standard encodings and differences arrays), glyph names via the Adobe Glyph List, and the embedded font's own tables. Where the page marks text with its actual reading order (/ActualText, as SoftZenPdf does for right-to-left text), that text is used instead of the glyphs. Text inside form XObjects is included. Characters with no mapping come out as U+FFFD (�), and a note is added to reader.Warnings.

Limits

There is no OCR: scanned pages, which are images, yield no text. Content streams must use filters SoftZenPdf can decode (Flate, LZW, ASCIIHex, ASCII85, RunLength); others are skipped with a warning. Encrypted files need the password.

API: PdfReader.ExtractText, PdfTextRun, TextExtractionOptions.