Skip to main content

How to: Extract Text from a Document

  • 2 minutes to read

Important

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

Extract All Text

The code snippet below uses the PdfDocumentProcessor.Text property to extract the text of a PDF file at runtime.

View Example

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 = 
pdfDocumentProcessor.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