Skip to main content
A newer version of this page is available. .

How to: Extract Text from a Document

  • 3 minutes to read

Important

You need a license to the DevExpress Office File API or DevExpress Universal Subscription to use these examples in production code. Refer to the DevExpress Subscription page for pricing information.

Extract All Text

This tutorial describes how to extract the text of a PDF file at runtime using the PDF Document API.

To extract the text of a PDF file, do the following.

  1. Create a PdfDocumentProcessor.
  2. To open a PDF file, pass a stream that contains the document data to the PdfDocumentProcessor.LoadDocument method.
  3. After the document is loaded, you can extract its plain text using the PdfDocumentProcessor.Text property.

The following code implements this functionality.

string ExtractTextFromPDF(string filePath) {
    string documentText = "";
    try {
        using (PdfDocumentProcessor documentProcessor = new PdfDocumentProcessor()) {
            documentProcessor.LoadDocument(filePath);
            documentText = documentProcessor.Text;
        }
    }
    catch { }
    return documentText;
}

Note

The PdfDocumentProcessor.Text property retrieves the content clipped to the crop box. Use the PdfDocumentProcessor.GetText method to get text without clipping. Set the PdfTextExtractionOptions.ClipToCropBox property to false and pass the PdfTextExtractionOptions object as a method parameter.

Extract Text from a Page

Use the PdfDocumentProcessor.GetPageText method to retrieve text from the specified page. This method returns text as a string of lines separated by newlines (“\r\n”). If a document does not contain the specified page, the GetPageText method returns an empty string.

The code sample below extracts text from the first page without clipping:

PdfDocumentProcessor pdfDocumentProcessor = new PdfDocumentProcessor();
pdfDocumentProcessor.LoadDocument("PDF32000_2008.pdf");
string firstPageText = 
processor.GetPageText(1, new PdfTextExtractionOptions { ClipToCropBox = false });

Extract Text from an Area

The PdfDocumentProcessor.GetText method allows you to retrieve text from the specified document area. You can use PdfDocumentPosition objects or the PdfDocumentArea instance to define the area.

The GetText method uses the page coordinate system. Refer to the following help topic for more details: Coordinate Systems.

The code sample below extracts text between two positions on the first page:

using (DevExpress.Pdf.PdfDocumentProcessor processor = new DevExpress.Pdf.PdfDocumentProcessor())
{
    processor.LoadDocument("TextExtraction.pdf");
    PdfDocumentPosition startPosition = new PdfDocumentPosition(1, new PdfPoint(0, 0));
    PdfDocumentPosition endPosition = new PdfDocumentPosition(1, new PdfPoint(500, 500));

    string pageText = 
    processor.GetText(startPosition, endPosition, new PdfTextExtractionOptions { ClipToCropBox = false });
    Console.WriteLine(pageText);
}
See Also