Skip to content
Docs: Getting startedMenu

Getting started

Install Hypapdf from NuGet, open a PDF, extract its text, read uploaded files in ASP.NET Core and handle encrypted or damaged documents.

v0.1.0Last updated View as Markdown

This page takes you from installing the package to the text of a first document and a PDF upload in a web endpoint. Hypapdf for .NET has the full details.

Install#

Install · NuGet
dotnet add package Hypapdf

Hypapdf on NuGet

The package targets .NET 8, 9, 10 and 11 and has no other dependencies.

Read a document#

using Hypapdf;

using var pdf = await PdfDocument.OpenAsync("report.pdf");
Console.WriteLine($"{pdf.PageCount} pages, PDF {pdf.Version}, title: {pdf.Info.Title}");

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

OpenAsync reads a file or a Stream asynchronously; Open takes a byte[], a ReadOnlyMemory<byte> or a Stream. Only the cross-reference data is read when the document opens; everything else is parsed on first use.

All pages at once#

// Pages are separated by form feeds (\f). MaxDegreeOfParallelism = 0 uses every processor.
string all = pdf.ExtractText(new PdfTextOptions { MaxDegreeOfParallelism = 0 });

For multi-column layouts, ask for reading order. It costs about twice the time of content order:

string ordered = pdf.ExtractText(new PdfTextOptions { Layout = PdfTextLayout.ReadingOrder });

Read an upload in ASP.NET Core#

using Hypapdf;

app.MapPost("/pdf/text", async (IFormFile file, CancellationToken ct) =>
{
    using var pdf = await PdfDocument.OpenAsync(file.OpenReadStream(), cancellationToken: ct);
    return Results.Text(pdf.ExtractText());
}).DisableAntiforgery();

With a raw request body, use await PdfDocument.OpenAsync(request.Body). The whole file is held in memory, so limit the request size of the endpoint to what you are willing to load.

Errors, passwords and damaged files#

try
{
    using var pdf = await PdfDocument.OpenAsync("upload.pdf", new PdfReadOptions { Password = "secret" });
    if (pdf.WasRepaired) Console.WriteLine("The cross-reference data was rebuilt.");
}
catch (PdfEncryptedException)
{
    // A password is needed or wrong, or the file uses public-key encryption.
}
catch (PdfFormatException)
{
    // Not a PDF, damaged beyond repair, or a stream above MaxDecodedStreamBytes.
}

Encrypted documents open with the empty password unless you pass one; both user and owner passwords work. Damaged or missing cross-reference data is rebuilt by scanning the file, and WasRepaired tells you it happened.