How to extract text from a PDF in C#

Updated · Tested with .NET 10, PdfPig 0.1.16

In short

Use PdfPig, which is free under the Apache licence. Open the file with PdfDocument.Open and call ContentOrderTextExtractor.GetText(page) for each page. Do not use page.Text for this: it returns the letters with no spaces or line breaks between words that were placed apart.

Most well-known .NET PDF libraries are commercial, or under licences that require you to open your own source. PdfPig is the exception: it is free, under the Apache licence, and reads text well. The examples use company-extract.pdf and run on .NET 10.

LibraryLicence
PdfPigApache 2.0: free, including in closed-source products
iTextAGPL, or a paid licence
PDFsharpMIT, but built for creating PDFs, not for reading text

Add PdfPig

Shell
dotnet add package PdfPig

Extract the text

C#
using UglyToad.PdfPig;
using UglyToad.PdfPig.DocumentLayoutAnalysis.TextExtractor;

using var document = PdfDocument.Open(args[0]);
foreach (var page in document.GetPages())
{
    Console.WriteLine(ContentOrderTextExtractor.GetText(page));
}
Output
COMPANY EXTRACT
Company name Harbor Lane Logistics Ltd
Company number 51-482913-6
Status Active
Registered 14 March 2019
Registered office 22 Quay Street, Haifa
Share capital 1,250.50
Directors

Do not use page.Text for this

The first thing most people try is page.Text. It returns the letters of the page with no spaces between words that were placed apart and no line breaks:

Output
COMPANY EXTRACTCompany nameHarbor Lane Logistics LtdCompany number51-482913-6StatusActiveRegistered14 March 20

That is not a bug. A PDF often has no space or line-break characters at all, only letters at positions, and page.Text gives you exactly what is stored. ContentOrderTextExtractor looks at the positions and puts the spaces and line breaks back.

Words with positions

C#
using UglyToad.PdfPig;

using var document = PdfDocument.Open(args[0]);
foreach (var page in document.GetPages())
{
    Console.WriteLine($"page {page.Number}: {page.Width} x {page.Height}");
    foreach (var word in page.GetWords().Skip(2).Take(4))
    {
        var box = word.BoundingBox;
        Console.WriteLine($"{box.Left:F1} {page.Height - box.Top:F1} {box.Right:F1} {page.Height - box.Bottom:F1} {word.Text}");
    }
}
Output
page 1: 595.275591 x 841.889764
68.4 132.8 117.6 140.8 Company
120.5 134.8 149.9 140.8 name
204.4 132.4 241.3 140.8 Harbor
244.1 132.9 269.0 140.8 Lane

PdfPig measures from the bottom left of the page, as the PDF format does. The code subtracts from the page height so the numbers read from the top, like most other tools. With positions you can pair a label with the value to its right: here name ends at x = 149.9 and the value starts at x = 204.4 on the same line.

What to expect on harder files

FilePdfPig 0.1.16
Two-column pageRead column by column, in the right order
HebrewEvery line reversed
Font without a Unicode mapGibberish
ScanEmpty: there is no text in the file
Password-protectedPdfDocumentEncryptedException

For a protected file, pass the password when you open it:

C#
using var document = PdfDocument.Open(path, new ParsingOptions { Password = "sands2026" });

For Hebrew, PdfPig returns each line in the order it is stored, which for many files is back to front. The cause and the repair are the same in every language; see why Hebrew text comes out backwards.

Text in reading order from an API

PdfPig reads the text stored in a PDF. A scanned page has none, and Word and Excel files need other libraries. 100sands reads PDFs and HTML files that contain text, and returns the lines in reading order in every language, Hebrew included, with no repair step. With HttpClient:

C#
using System.Net.Http.Headers;
using System.Text.Json;

using var http = new HttpClient();
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("SANDS_API_KEY"));

using var form = new MultipartFormDataContent();
form.Add(new ByteArrayContent(await File.ReadAllBytesAsync(args[0])), "file", Path.GetFileName(args[0]));

var response = await http.PostAsync("https://api.100sands.com/v1/text", form);
response.EnsureSuccessStatusCode();
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Console.WriteLine(json.RootElement.GetProperty("text").GetString());

For company-extract.pdf, the response has this shape:

JSON
{
  "pages": 1,
  "text": "COMPANY EXTRACT\nCompany name\tHarbor Lane Logistics Ltd\nCompany number\t51-482913-6\nStatus\tActive\n..."
}

A label and its value set apart on one line are separated by a tab, and pages by a form feed (\f). 100sands does not read scans, Word or Excel files: company-scan.pdf is refused with status 422 and the code NO_TEXT_IN_FILE, and a Word file with 415 and UNSUPPORTED_FILE.

Questions

What is a free C# library to extract text from a PDF?

PdfPig. It is under the Apache 2.0 licence, so it is free in commercial and closed-source products. iText requires a paid licence unless your own code is open source under the AGPL.

Why does PdfPig return text with no spaces?

page.Text returns the letters exactly as the file stores them, and many PDFs store no space characters. Use ContentOrderTextExtractor.GetText(page), which works out spaces and line breaks from the positions of the letters.

How do I get the position of each word in C#?

Call page.GetWords() and read each word's BoundingBox. PdfPig measures from the bottom left of the page, so subtract from page.Height to measure from the top.

Can PdfPig read scanned PDFs?

No. A scanned page contains a picture and no text, and PdfPig returns an empty result for it. Run OCR first or use an OCR service.

Try it on your own documents

A free plan every month, no credit card. See the PDF to text API.

Start free