Products Technologies Demo Docs Blog Support Company

Template-Based Text Extraction from PDF Documents in .NET C#

Template-based text extraction using TX Text Control provides an efficient way to retrieve structured data from PDF documents. This article shows how to extract text from PDF documents using templates.

Template-Based Text Extraction from PDF Documents in .NET C#

When working with PDF documents, extracting specific information such as a company name, social security number, or invoice number can be a challenge. In a perfect world, this data would exist in well-structured form fields that could be easily accessed programmatically (including using TX Text Control functionality). However, many PDF files are flattened, which means that the form fields are removed, leaving only the raw text.

TX Text Control provides a powerful solution for text extraction based on predefined template areas, allowing you to extract structured information even from flattened PDFs.

Template-based text extraction involves defining a rectangle (bounding box) within which specific text is expected to appear in a PDF document. Once this area is defined, TX Text Control can extract lines of text within the defined rectangle, ensuring accurate data retrieval.

  1. Defining a template: Identify a known text string in a sample document and define a bounding box around it.
  2. Applying the template: Use the same selection box on other similar documents to extract relevant text.
  3. Extracting text: The TX Text Control allows you to search for text within the defined rectangle and retrieve meaningful data from it.

Implementing Template-Based Text Extraction

As a first step, we want to identify the text location of a known document with known data. Using a sample PDF, find a known piece of text (such as a company name or invoice number) that appears consistently in a particular location.

Let us take a look at a very typical US tax form, the W9.

PDF form

This document still has form fields enabled, and if we had access to this document, it would be very easy to extract the data using TX Text Control by simply iterating through the form fields.

Learn More

Learn how to extract text from PDF documents using the TX Text Control PDF import feature in C#. This article shows how to extract text, attachments, form field values and metadata from PDF documents.

Extract Data from PDF Documents with C#

But in this scenario, we don't have access to the source document, but to a flattened version where all the form fields have been removed and only the text is visible.

Flattened PDF form

Now we want to define the rectangle to search for the company name.

Rectangle

Creating the Application

To demonstrate how easy this is with the TX Text Control library, we will use a .NET console application.

Make sure that you downloaded the latest version of Visual Studio 2022 that comes with the .NET 8 SDK.

Prerequisites

The following tutorial requires a trial version of TX Text Control .NET Server.

  1. In Visual Studio 2022, create a new project by choosing Create a new project.

  2. Select Console App as the project template and confirm with Next.

  3. Choose a name for your project and confirm with Next.

  4. In the next dialog, choose .NET 8 (Long-term support) as the Framework and confirm with Create.

Adding the NuGet Package

  1. In the Solution Explorer, select your created project and choose Manage NuGet Packages... from the Project main menu.

    Select Text Control Offline Packages from the Package source drop-down.

    Install the latest versions of the following package:

    • TXTextControl.TextControl.ASP.SDK

    ASP.NET Core Web Application

Training Data

The following code uses TX Text Control to find the known value of our training data "Text Control, LLC" and returns the location that will later be used for all other documents.

using TXTextControl.DocumentServer.PDF.Contents;

try
{
    string pdfFilePath = "FormW9.pdf";

    // Check if the file exists before processing
    if (!File.Exists(pdfFilePath))
    {
        Console.WriteLine($"Error: File '{pdfFilePath}' not found.");
        return;
    }

    // Load PDF lines
    var pdfLines = new Lines(pdfFilePath);

    // Find the target text
    var trainLines = pdfLines.Find("Text Control, LLC");

    // Check if any lines were found before accessing the index
    if (trainLines.Count > 0)
    {
        Console.WriteLine(trainLines[0].Rectangle.ToString());
    }
    else
    {
        Console.WriteLine("Text not found in the PDF.");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"An error occurred: {ex.Message}");
}

The console contains the location of the found text.

{X=1192,Y=2566,Width=1510,Height=180}

Extracting Text

The next snippet loads the second document and searches for text in the given rectangle, which we retrieved from our training data.

using System.Drawing;
using TXTextControl.DocumentServer.PDF.Contents;

try
{
    string pdfFilePath = "FormW9_2.pdf";

    // Check if the file exists before processing
    if (!File.Exists(pdfFilePath))
    {
        Console.WriteLine($"Error: File '{pdfFilePath}' not found.");
        return;
    }

    // Load PDF lines
    var pdfLines = new Lines(pdfFilePath);

    // Define the search area
    var searchRectangle = new Rectangle(1192, 2566, 1510, 180);

    // Find text within the defined rectangle (include partial matches)
    var contentLines = pdfLines.Find(searchRectangle, true);

    // Filter only page 1 content lines
    var page1ContentLines = contentLines.Where(cl => cl.Page == 1).ToList();

    // Check if any content was found
    if (page1ContentLines.Count > 0)
    {
        Console.WriteLine(page1ContentLines[0].Text);
    }
    else
    {
        Console.WriteLine("No content found in the specified rectangle on page 1.");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"An error occurred: {ex.Message}");
}

The console contains the extracted text from the second document.

Document Processing Enterprises Ltd.

Because we used true for the second parameter of the Find method, the search will return the entire line, even if the company name is longer in this case.

Even if the company name goes to the end of the line, it will find the correct values.

Long company name

This is a very long company name - This is a very long company name - This is a very long company name

Conclusion

Template-based text extraction is a powerful feature for extracting structured information from PDF documents. By defining a rectangle around known text, TX Text Control can extract text from similar documents, even if the text is not in form fields.

Stay in the loop!

Subscribe to the newsletter to receive the latest updates.

Related Posts

ASP.NETASP.NET CoreExtraction

Mining PDFs with Regex in C#: Practical Patterns, Tips, and Ideas

Mining PDFs with Regex in C# can be a powerful technique for extracting information from documents. This article explores practical patterns, tips, and ideas for effectively using regular…


ASP.NETASP.NET CoreForms

Streamline Data Collection with Embedded Forms in C# .NET

Discover how to enhance your C# .NET applications by embedding forms for data collection. This article explores the benefits of using Text Control's ASP.NET and ASP.NET Core components to create…


ASP.NETASP.NET CorePDF

Adding QR Codes to PDF Documents in C# .NET

This article explains how to add QR codes to PDF documents with the Text Control .NET Server component in C#. It provides the necessary steps and code snippets for effectively implementing this…


ASP.NETASP.NET CorePDF

Adding SVG Graphics to PDF Documents in C# .NET

In this article, we will explore how to add SVG graphics to PDF documents using C# .NET. We will use the TX Text Control .NET Server component to demonstrate the process of rendering SVG images in…


ASP.NETASP.NET CoreKeywords

Enhancing PDF Searchability in Large Repositories by Adding and Reading…

This article explores how to improve the searchability of PDF documents in large repositories by adding and reading keywords with C# .NET. This is especially helpful for applications that manage…