Cómo extraer texto e imágenes incrustados de PDFs en C#

How to Extract Embedded Text and Images from PDFs

This article was translated from English: Does it need improvement?
Translated
View the article in English

Extracting embedded text and images involves retrieving textual content and graphical elements within the document. This process allows users to access and repurpose the content for editing, searching, or converting text to other formats and saving images for reuse or analysis.

To extract text and images from a PDF, use IronPdf. The extracted image can be saved to the disk or converted to another image format and embedded in the newly rendered document.

Quickstart: Extract Text and Images with IronPDF

Effortlessly extract text and images from PDFs using IronPDF in just a few lines of code. This quickstart guide equips developers with the tools needed to retrieve embedded content from PDF documents, facilitating content repurposing and analysis. Whether you're extracting text for editing or saving images for further use, IronPDF ensures a streamlined and cost-effective solution. Get started with the IronPdf library today and experience seamless PDF content management.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf

  2. Copy and run this code snippet.

    var pdf = new IronPdf.PdfDocument("sample.pdf");
    string text = pdf.ExtractAllText();
    var images = pdf.ExtractAllImages();
  3. Deploy to test on your live environment

    Start using IronPDF in your project today with a free trial
    arrow pointer


Extract Text Example

Text extraction can be performed on both newly rendered and existing PDF documents. Use the ExtractAllText method to extract the embedded text from the document. The method will return a string containing all the text in the given PDF. Pages are separated by four consecutive new line characters. Let's use a sample PDF that I have rendered from the Wikipedia website.

:path=/static-assets/pdf/content-code-examples/how-to/extract-text-and-images-extract-text.cs
using IronPdf;
using System.IO;

PdfDocument pdf = PdfDocument.FromFile("sample.pdf");

// Extract text
string text = pdf.ExtractAllText();

// Export the extracted text to a text file
File.WriteAllText("extractedText.txt", text);
Imports IronPdf
Imports System.IO

Private pdf As PdfDocument = PdfDocument.FromFile("sample.pdf")

' Extract text
Private text As String = pdf.ExtractAllText()

' Export the extracted text to a text file
File.WriteAllText("extractedText.txt", text)
$vbLabelText   $csharpLabel
Extracted text

Extract Text by Line and Character

Within each PDF page, it is possible to retrieve the coordinates of text lines and characters. First, select a page from the PDF and access the Lines and Characters properties. The coordinates are laid out as Top, Right, Bottom, and Left values, representing the position of the text.

:path=/static-assets/pdf/content-code-examples/how-to/extract-text-and-images-extract-text-by-line-character.cs
using IronPdf;
using System.IO;
using System.Linq;

// Open PDF from file
PdfDocument pdf = PdfDocument.FromFile("sample.pdf");

// Extract text by lines
var lines = pdf.Pages[0].Lines;

// Extract text by characters
var characters = pdf.Pages[0].Characters;

File.WriteAllLines("lines.txt", lines.Select(l => $"at Y={l.BoundingBox.Bottom:F2}: {l.Contents}"));
Imports IronPdf
Imports System.IO
Imports System.Linq

' Open PDF from file
Private pdf As PdfDocument = PdfDocument.FromFile("sample.pdf")

' Extract text by lines
Private lines = pdf.Pages(0).Lines

' Extract text by characters
Private characters = pdf.Pages(0).Characters

File.WriteAllLines("lines.txt", lines.Select(Function(l) $"at Y={l.BoundingBox.Bottom:F2}: {l.Contents}"))
$vbLabelText   $csharpLabel
Extracted text by line and character

Extract Images Example

Use the ExtractAllImages method to extract all images embedded in the document. The method will return the images as a list of AnyBitmap objects. Using the same document from our previous example, we extracted the images and exported them to the 'images' folder.

:path=/static-assets/pdf/content-code-examples/how-to/extract-text-and-images-extract-image.cs
using IronPdf;

PdfDocument pdf = PdfDocument.FromFile("sample.pdf");

// Extract images
var images = pdf.ExtractAllImages();

for(int i = 0; i < images.Count; i++)
{
    // Export the extracted images
    images[i].SaveAs($"images/image{i}.png");
}
Imports IronPdf

Private pdf As PdfDocument = PdfDocument.FromFile("sample.pdf")

' Extract images
Private images = pdf.ExtractAllImages()

For i As Integer = 0 To images.Count - 1
	' Export the extracted images
	images(i).SaveAs($"images/image{i}.png")
Next i
$vbLabelText   $csharpLabel
Extracted images

In addition to the ExtractAllImages method shown above, the user can use the ExtractAllBitmaps and ExtractAllRawImages methods to extract image information from the document. While the ExtractAllBitmaps method will return a List of AnyBitmap, like the code example, the ExtractAllRawImages method extracts all images from a PDF document and returns them as raw data in the form of Byte Arrays (byte[]).


Extract Text and Images on Specific Pages

Both text and image extraction can be performed on single or multiple specified pages. Use the ExtractTextFromPage and ExtractTextFromPages methods to extract text from a single page or multiple pages, respectively. For extracting images, use the ExtractImagesFromPage and ExtractImagesFromPages methods.

:path=/static-assets/pdf/content-code-examples/how-to/extract-text-and-images-extract-text-single-multiple.cs
using IronPdf;

PdfDocument pdf = PdfDocument.FromFile("sample.pdf");

// Extract text from page 1
string textFromPage1 = pdf.ExtractTextFromPage(0);

int[] pages = new[] { 0, 2 };

// Extract text from pages 1 & 3
string textFromPage1_3 = pdf.ExtractTextFromPages(pages);
Imports IronPdf

Private pdf As PdfDocument = PdfDocument.FromFile("sample.pdf")

' Extract text from page 1
Private textFromPage1 As String = pdf.ExtractTextFromPage(0)

Private pages() As Integer = { 0, 2 }

' Extract text from pages 1 & 3
Private textFromPage1_3 As String = pdf.ExtractTextFromPages(pages)
$vbLabelText   $csharpLabel

Preguntas Frecuentes

¿Cómo puedo extraer texto incrustado de un PDF en .NET C#?

Puedes utilizar el método ExtractAllText de la biblioteca IronPdf para extraer texto incrustado de un PDF. Este método devuelve una cadena de texto que contiene el texto separado por cuatro caracteres de nueva línea consecutivos para cada página.

¿Qué pasos están involucrados en la extracción de imágenes de un PDF usando C#?

Para extraer imágenes de un PDF en C#, primero descarga la biblioteca IronPdf a través de NuGet. Luego utiliza el método ExtractAllImages, que devolverá una lista de objetos AnyBitmap que representan las imágenes.

¿Puedo extraer texto de páginas específicas de un documento PDF?

Sí, puedes usar los métodos ExtractTextFromPage y ExtractTextFromPages en IronPdf para extraer texto de páginas específicas o múltiples páginas de un documento PDF.

¿Cuál es el propósito de extraer texto por coordenadas de línea y carácter?

Extraer texto por coordenadas de línea y carácter te permite recuperar la posición exacta del texto dentro de una página PDF. Esto se puede hacer utilizando las propiedades **Lines** y **Characters** en IronPdf, que proporcionan valores de Superior, Derecho, Inferior e Izquierdo.

¿Cómo extraigo imágenes en formato bruto de un PDF?

Para extraer imágenes en formato bruto, utiliza el método ExtractAllRawImages en IronPdf. Este método devuelve las imágenes como Arrays de Bytes, permitiéndote acceder a los datos de la imagen original.

¿Cuáles son los beneficios de usar IronPdf para extraer texto e imágenes?

Usar IronPdf para extraer texto e imágenes de PDFs es rentable, ya que ofrece una solución de pago único. Ayuda a reutilizar contenido para edición, búsqueda, conversión a otros formatos y reutilizar imágenes para análisis.

¿Cómo puedo comenzar a usar IronPdf para la extracción de contenido de PDF?

Para comenzar a usar IronPdf, descarga la biblioteca IronPdf C# desde NuGet y sigue la guía para preparar tu documento PDF y usa métodos como ExtractAllText y ExtractAllImages para la extracción de contenido.

¿Es posible extraer tanto texto como imágenes de una sola página PDF?

Sí, IronPdf te permite extraer tanto texto como imágenes de una sola página PDF usando los métodos ExtractTextFromPage y ExtractImagesFromPage.

¿Qué métodos están disponibles para extraer imágenes de múltiples páginas?

Puedes usar el método ExtractImagesFromPages en IronPdf para extraer imágenes de múltiples páginas de un documento PDF.

¿IronPdf es compatible con .NET 10 para extraer texto e imágenes?

Sí, IronPdf es compatible con .NET 10, así como con versiones modernas anteriores como .NET 9, 8, 7, 6, CORE, Standard y Framework. Puede usar los mismos métodos, como ExtractAllText , ExtractAllImages , ExtractTextFromPage y ExtractImagesFromPages , en un proyecto .NET 10 sin necesidad de soluciones alternativas ni ajustes de compatibilidad.

Chaknith Bin
Ingeniero de Software
Chaknith trabaja en IronXL e IronBarcode. Tiene un profundo conocimiento en C# y .NET, ayudando a mejorar el software y apoyar a los clientes. Sus conocimientos derivados de las interacciones con los usuarios contribuyen a mejores productos, documentación y experiencia en general.
¿Listo para empezar?
Nuget Descargas 16,154,058 | Versión: 2025.11 recién lanzado