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.

ASP.NET

Integrate document processing into your applications to create documents such as PDFs and MS Word documents, including client-side document editing, viewing, and electronic signatures.

ASP.NET Core
Angular
Blazor
JavaScript
React
  • Angular
  • Blazor
  • React
  • JavaScript
  • ASP.NET MVC, ASP.NET Core, and WebForms

Learn more Trial token Download trial

Related Posts

ASP.NETASP.NET CoreDigital Signatures

Why Digitally Signing your PDFs is the Only Reliable Way to Prevent Tampering

PDF documents are widely used for sharing information because of their fixed layout and cross-platform compatibility. However, it is crucial to ensure the integrity and authenticity of these…


ASP.NETAIASP.NET Core

Automating PDF/UA Accessibility with AI: Describing DOCX Documents Using TX…

This article shows how to use TX Text Control together with the OpenAI API to automatically add descriptive texts (alt text and labels) to images, links, and tables in a DOCX. The resulting…


ASP.NETASP.NET CoreJava

Converting Office Open XML (DOCX) to PDF in Java

Learn how to convert Office Open XML (DOCX) documents to PDF in Java using the powerful ServerTextControl library. This guide provides step-by-step instructions and code examples to help you…


ASP.NETASP.NET CoreDS Server

Extending DS Server with Custom Digital Signature APIs

In this article, we will explore how to extend the functionality of DS Server by integrating custom digital signature APIs. We will cover the necessary steps to create a plugin that allows DS…


ASP.NETASP.NET CorePDF

Why PDF/UA and PDF/A-3a Matter: Accessibility, Archiving, and Legal Compliance

It is more important than ever to ensure that documents are accessible, archivable, and legally compliant. PDF/UA and PDF/A-3a are two effective standards for addressing these needs. This article…