Skip to content
Docs: Hypapdf for .NETMenu

Hypapdf for .NET

Read PDFs in C#: text in content or reading order, words with bounding boxes, AcroForm fields, images, bookmarks and links, in parallel and with no dependencies.

v0.1.0Last updated View as Markdown

Reading PDFs in .NET usually means a choice between a managed library that is slow and allocates gigabytes, and native PDFium or MuPDF binaries you have to ship. Hypapdf is a managed reader without dependencies that extracts text 5 to 35 times faster than every other open-source .NET option measured, native PDFium and MuPDF included. It is safe for untrusted input, and thread-safe so pages can be read in parallel.

Compatibilityv0.1.0
Package
Hypapdf
Requires
.NET 8, 9, 10, 11
Engine
Native .NET, no dependencies; reads, does not render or write
Web
ASP.NET Core: PdfDocument.OpenAsync(request.Body)
Registry
NuGet
License
Apache-2.0

Install#

Install · NuGet
dotnet add package Hypapdf

Hypapdf on NuGet

PackagePurpose
HypapdfThe PDF reader (net8.0, net9.0, net10.0, net11.0), no dependencies

Open a document#

using Hypapdf;

using var pdf = await PdfDocument.OpenAsync("report.pdf"); // or Open(byte[] | ReadOnlyMemory<byte> | Stream)
Console.WriteLine($"{pdf.PageCount} pages, PDF {pdf.Version}, title: {pdf.Info.Title}");

The file is held in memory; a byte[] you pass is used in place, not copied. Only the cross-reference data is read on open. Info has the title, author, subject, keywords, creator, producer and dates, XmpMetadata the XMP packet, and IsEncrypted and Permissions describe the encryption.

Text#

foreach (var page in pdf.Pages)
{
    Console.WriteLine(page.ExtractText());
}

// All pages at once, on every processor; pages are separated by form feeds.
string all = pdf.ExtractText(new PdfTextOptions { MaxDegreeOfParallelism = 0 });

Text comes in content order by default, like pdftotext -raw, with spaces and line breaks inserted from the glyph positions. Over the 210 files of the pdf.js test suite with text, it matches Poppler’s pdftotext -raw with a word-level F1 of 0.95 weighted by length.

Fonts are handled broadly: simple fonts with standard encodings and Differences, the Adobe Glyph List, built-in Type 1 encodings, Type 3 fonts, and composite fonts with ToUnicode maps, embedded and predefined CMaps (including Shift JIS, EUC, GBK, Big Five and UHC) and embedded TrueType cmap and post tables. Vertical writing, Form XObjects and annotation appearances such as filled-in form fields are included; duplicate glyphs from fake bold are removed and Latin ligatures expanded.

Reading order, words and blocks#

// Blocks (paragraphs, columns, cells) column by column.
string ordered = pdf.Pages[0].ExtractText(new PdfTextOptions { Layout = PdfTextLayout.ReadingOrder });

foreach (var block in pdf.Pages[0].GetTextBlocks())
{
    Console.WriteLine($"{block.Bounds}: {block.Text}");          // block.Lines[i].Words[j].Bounds, FontName, ...
}

foreach (var word in pdf.Pages[0].GetWords())
{
    Console.WriteLine($"{word.Text} {word.Bounds} {word.FontName} {word.FontSize:F1}");
}

Reading order uses a recursive XY cut on blocks, and text in other directions is laid out in its own frame. It costs about twice the time of content order.

Glyphs#

// Glyphs with their positions in user space (points, origin bottom left).
foreach (var letter in pdf.Pages[0].GetLetters())
{
    Console.WriteLine($"{letter.Value} at ({letter.X:F1}, {letter.Y:F1}) size {letter.FontSize:F1} {letter.FontName}");
}

Form fields#

foreach (var field in pdf.FormFields)
{
    Console.WriteLine($"{field.FullName} ({field.Type}, page {field.PageNumber}) = {field.Value}");
}

FormFields lists the terminal fields of the AcroForm with inherited attributes: text, check box, radio group, push button, combo box, list box (multi-select) and signature. Each has its full name, value and default (Values for multi-select, IsChecked for check boxes), options with export values and display texts, flags, tooltip, and the page and rectangle of each widget. XFA-only forms are not read.

Images#

// JPEG and JPEG 2000 bytes as stored, other images as PNG.
foreach (var image in pdf.Pages[0].GetImages())
{
    var bytes = image.Format == PdfImageFormat.Raw ? image.ToPng() : image.GetEncodedData();
    if (bytes is not null) File.WriteAllBytes($"image-{image.Name}{image.FileExtension}", bytes);
}

GetImages lists image XObjects (also inside Form XObjects and annotation appearances) and inline images, with the rectangle each covers on the page, the size, colour space, bits per component and format. ToPng converts raw images in gray, RGB, CMYK, indexed and ICC-based colour spaces and image masks.

foreach (var item in pdf.Outlines)
{
    Console.WriteLine($"{item.Title} -> page {item.PageNumber}");      // item.Children, item.Uri, item.Destination
}

foreach (var link in pdf.Pages[0].GetLinks())
{
    Console.WriteLine($"{link.Bounds}: {link.Uri ?? $"page {link.PageNumber}"}");
}

Destinations are resolved from explicit and named destinations (the name tree and old-style /Dests) and from GoTo, GoToR, Launch and URI actions, with fit types and coordinates.

Encryption and damaged files#

Encrypted documents open with the empty password, or with new PdfReadOptions { Password = "..." } (user or owner password). The standard security handler is supported: RC4 from 40 to 128 bit, AES-128 and AES-256 (revisions 2 to 6) and crypt filters.

Cross-reference tables and streams, hybrid files, incremental updates, object streams, linearized files, junk before the header and wrong /Length values are all read. Damaged or missing cross-reference data is rebuilt by scanning the file, and WasRepaired is then true.

Untrusted input#

PdfReadOptions limits what a document may cost:

OptionDefaultLimits
MaxDecodedStreamBytes256 MiBThe decoded size of one stream
MaxObjects16 millionThe number of objects
MaxFormDepth32The nesting of Form XObjects

Malformed input is meant to surface only as PdfFormatException or PdfEncryptedException, never as a crash or a hang. Mutation fuzzing over the pdf.js test suite (50,000 damaged files so far) checks this.

Threads and memory#

PdfDocument, PdfPage and the object model are safe to use from several threads at once. The file is held in memory; decoded page content is pooled and released after each page. Extracting the text of 1,298 pages allocates about 79 MB.

The object model#

var catalog = pdf.Catalog;                       // PdfDictionary
var obj = pdf.GetObject(12);                     // by object number, null if missing
var pages = catalog.Get("Pages");                // resolves references; GetRaw keeps them
byte[] content = pdf.Pages[0].GetContentData();  // decoded content stream

Strings are decoded from PDFDocEncoding, UTF-16 and UTF-8. PdfStream.GetData() returns decoded bytes and GetRawData() the bytes as stored. FlateDecode (lenient about headers, checksums and truncation), LZWDecode, ASCII85Decode, ASCIIHexDecode and RunLengthDecode are decoded, with PNG and TIFF predictors; image filters (DCT, JPX, JBIG2, CCITT) are left encoded.