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.
| Library | Licence |
|---|---|
| PdfPig | Apache 2.0: free, including in closed-source products |
| iText | AGPL, or a paid licence |
| PDFsharp | MIT, but built for creating PDFs, not for reading text |
Add PdfPig
dotnet add package PdfPigExtract the text
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));
}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
DirectorsDo 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:
COMPANY EXTRACTCompany nameHarbor Lane Logistics LtdCompany number51-482913-6StatusActiveRegistered14 March 20That 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
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}");
}
}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 LanePdfPig 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
| File | PdfPig 0.1.16 |
|---|---|
| Two-column page | Read column by column, in the right order |
| Hebrew | Every line reversed |
| Font without a Unicode map | Gibberish |
| Scan | Empty: there is no text in the file |
| Password-protected | PdfDocumentEncryptedException |
For a protected file, pass the password when you open it:
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:
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:
{
"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.