Cómo extraer contenido de un PDF en C# con Xceed PdfLibrary para .NET
Lo que necesitas
- .NET 5 a .NET 10
- Xceed PdfLibrary for .NET (trial or license). Add it via NuGet or reference the DLL.
- A PDF to read from (or create one in code using the create-PDF or split-PDF snippets from the other posts)
Configurar el proyecto y la licencia
Crea un proyecto de consola o web y agrega la biblioteca. Desde la línea de comandos (.CLI de .NET):
dotnet add package Xceed.PdfLibrary.NETConcesión de licencias: Set your license key once at startup, before any DocumentoPdf calls. Get a clave de prueba gratuita o una licencia completa de la página de producto. See the create a PDF in C# post for a full setup snippet.
Extract text from each page
To extract content from a PDF in C#, start with the text on each page. Load the document with PdfDocument.Load(path) (or a Transmitir), then loop over doc.Pages and use the Text property on each page. In the PDF’s native order, that property returns the page text with spacing preserved.
using (var doc = PdfDocument.Load("document.pdf"))
{
for (int i = 0; i < doc.Pages.Count; i++)
{
string text = doc.Pages[i].Text;
Console.WriteLine($"--- Page {i + 1} ---");
Console.WriteLine(text?.Trim() ?? "");
}
}On empty pages or those with no extractable text, Text may be null or an empty string. Trimming and null-checking (as above) keeps output clean. This approach is ideal for building a full-text index, dumping content to a .txt file, or feeding text into another process.
Extract text from a specific area
Sometimes you only need the text inside a given rectangle (e.g. one column of a multi-column layout, a header strip, or a form-like zone). In that case, call GetTextFromArea(rectangle) on the page. Pass (x, y, width, height) in page coordinates (origin top-left, Y downward) to the Rectángulo constructor.
using (var doc = PdfDocument.Load("document.pdf"))
{
var page = doc.Pages[0];
var area = new Rectangle(50, 100, 400, 200); // left, top, width, height
string textInArea = page.GetTextFromArea(area);
Console.WriteLine(textInArea ?? "");
}This is useful for template-based PDFs where you know the approximate position of the content you care about, or when you want to ignore headers and footers by only extracting the main body rectangle.
Words and reading order
Text returns a single string per page in the order it appears in the PDF. If you need word boundaries or a reading-order view, the library also exposes Words (a collection of Word objects with bounds and text) and OrderedText (text in top-left to bottom-right order). For many use cases (search, logging, or simple export), Text is enough.
Extract form field values (form control extraction)
When a PDF contains form controls (AcroForm fields), you can extract their values programmatically. After loading the document, doc.FormFields gives you all form fields in the document; page.FormFields limits the result to a given page. Each field has a Nombre, and its type determines how to read the value.
Text box fields: Cast to TextBoxFormField and use the Text propiedad. Checkbox fields: Cast to CheckBoxFormField and use the IsChecked property. You can handle both in one loop:
using (var doc = PdfDocument.Load("form.pdf"))
{
foreach (var field in doc.FormFields)
{
if (field is TextBoxFormField textBox)
Console.WriteLine($"{textBox.Name}: {textBox.Text}");
else if (field is CheckBoxFormField checkBox)
Console.WriteLine($"{checkBox.Name}: {(checkBox.IsChecked ? "checked" : "unchecked")}");
}
}Other control types: The library supports other form field types (e.g. ComboBoxFormField, ListBoxFormField, RadioButtonGroupFormField). Similarly, iterate doc.FormFields o page.FormFields, check the type, and read the appropriate property. For full details and properties per type, see the Documentación de Xceed PdfLibrary para .NET.
Combining text and form extraction
You can extract content from a PDF in C# by combining text and form extraction in one pass. Load the document once, then loop pages for Text o GetTextFromArea where needed) and loop doc.FormFields for form values. As a result, you get both the visible text and the form data for indexing, validation, or export.
Ejecutar el código
Paste the snippets above into a console or web project, set your license key, and ensure you have a PDF at the path you pass to PdfDocument.Load (por ejemplo. document.pdf o form.pdf).
From Visual Studio the current directory is usually the project folder; from the command line it is the folder from which you invoked the app.
If you don’t have a PDF yet, use the create a PDF in C# snippet to generate one, or create a form with FormFields (see the documentation) and then run the extraction code on it. Finally, open the console output or any file you write to and confirm the extracted text and form values match the PDF.
Preguntas frecuentes
¿Necesito desechar el documento? Yes. Prefer usando (as in the snippets) or call Eliminar Así se liberan los manejadores de archivo y los flujos.
Can I load from a stream instead of a file? Yes. The overloads of PdfDocument.Load that accept a Transmitir are useful when the PDF comes from memory or a web request.
What if Text or OrderedText is null? For pages with no extractable text, the library may return null. Rely on null-coalescing (e.g. text ?? "") or explicit null checks before using the value.
How do I know a form field’s type before casting? Rely on is checks (e.g. if (field is TextBoxFormField)) or field.GetType(). The documentation lists all form field types and their properties.
¿Dónde puedo ver más muestras? Ver el Documentación de Xceed PdfLibrary para .NET for advanced topics, more form field types, and extraction in reading order.
Need help? Visita nuestra support page.
¿Puedo usar esto en una aplicación ASP.NET Core? Yes. The same code runs in any .NET host. Set the license key at startup, then load and extract in your controllers or services. For user-uploaded PDFs, load from the upload stream and extract text or form values to store or return as JSON.
Resumen: You’ve seen how to extract content from a PDF in C#: load with PdfDocument.Load, use Pages[i].Text o GetTextFromArea for text, and use FormFields with TextBoxFormField.Text y CheckBoxFormField.IsChecked for form control values. Dispose the document when done.
The same API works on Windows, macOS, and Linux.
¿Qué más puedes hacer con Xceed PdfLibrary?
With Xceed PdfLibrary for .NET you can create PDFs, add form fields, sign documents, split by page or bookmark, and add watermarks. The same patterns (load, read or modify, save) apply.
Once you’re comfortable extracting content from a PDF in C#, try creating or filling form fields, or splitting and extracting in one workflow. The documentación has samples for each of these.
Ready to extract content from PDFs in .NET?
Descarga Xceed PdfLibrary para .NET y pruébala gratis por 45 días, sin compromiso.
Próximos pasos
- Descargar Xceed PdfLibrary para .NET o llave de prueba gratuita. Learn more on the página de producto.
- Instalar vía NuGet: Xceed.PdfLibrary.NET. From the .NET CLI run:
- Need help? Visit our support page.
dotnet add package Xceed.PdfLibrary.NETSet your license key at startup, then load a PDF and use Pages[i].Text y doc.FormFields as shown above to extract content from a PDF in C#.