Click or drag to resize

Getting Started with PDF to Text Converter for .NET

ExpertPdf PDF to Text Converter extracts the text of PDF documents in any .NET application: console and Windows Forms applications, services, ASP.NET web sites. It extracts the text of a whole document or of a range of pages, keeping the original layout or in reading order, finds words in a document and reads the text of an area of a page.

The main class is PdfToTextConverter, in the eppdftotext.dll assembly.

Features
  • Extract the text of a whole document or of a range of pages, from a file, a stream or a byte array.

  • Keep the original layout of the pages (columns side by side), or put the text in reading order.

  • Extract the text page by page in one call: one string for each page.

  • Mark the page breaks, to split the text into pages.

  • Skip or include the text hidden by clipping paths.

  • Produce a HTML document with the title, author, subject and keywords of the PDF document as meta tags.

  • Find a text in a document: the page, the position and the size of every match.

  • Search for several texts at once, with the results grouped by text and by page.

  • Read the text of an area of a page, for example the fields of an invoice.

  • Open password protected documents; read the document information, the page count and the size and rotation of each page without extracting the text.

Requirements
  • .NET Framework 4.0 or later. A build for .NET Framework 2.0 - 3.5 applications is also included.

  • .NET Core 2.0 or later and .NET 5 to .NET 11, through the .NET Standard 2.0 build of the NuGet package.

  • Windows 10, Windows 11, Windows Server 2016 or later, 32-bit or 64-bit.

  • The eptools.dep file, the PDF engine of the library, in the same folder as eppdftotext.dll at run time. The NuGet package copies it to the output folder of your application.

Installation using the NuGet package

The easiest way to install the library is the ExpertPdf.PdfToText package (https://www.nuget.org/packages/ExpertPdf.PdfToText/). It works for .NET Framework, .NET Core and .NET 5 to .NET 11 projects. In Visual Studio open the NuGet Package Manager and install the package, or run:

dotnet add package ExpertPdf.PdfToText

The package is for AnyCPU and x86 applications. ExpertPdf.PdfToText.x64 (https://www.nuget.org/packages/ExpertPdf.PdfToText.x64/) is the x64 optimized build, for applications that target the x64 platform.

Installation using the downloaded assemblies

The download contains:

  • Bin\.NET_4.0\eppdftotext.dll - the library for .NET Framework 4.0 and later

  • Bin\eppdftotext.dll - the library for .NET Framework 2.0 - 3.5

  • eptools.dep next to each of them - the PDF engine

  • Samples (.NET Framework 4.6.2) and Samples_NET_10 (.NET 10 and .NET 11, NuGet package) - C# and VB.NET samples

Add a reference to eppdftotext.dll and copy eptools.dep from the same folder to the output folder of your application. In a project file you can add it as a linked file that is copied to the output folder:

XML
<None Include="..\Bin\.NET_4.0\eptools.dep" Link="eptools.dep" CopyToOutputDirectory="PreserveNewest" />

If eptools.dep has to be in another folder, set its full path with the PdfToolsFullPath property.

Getting started

Create a PdfToTextConverter, set the options and call ConvertToText(String) for a file or ConvertToText(Stream) for a stream. The result is a string:

using ExpertPdf;

PdfToTextConverter converter = new PdfToTextConverter();
// converter.LicenseKey = "your license key";

// the text in reading order: a whole column, then the next one
converter.Layout = TextLayout.ReadingLayout;

string text = converter.ConvertToText(@"C:\Documents\report.pdf");
System.IO.File.WriteAllText(@"C:\Documents\report.txt", text, System.Text.Encoding.UTF8);

// the document information is available after the conversion
DocumentInformation info = converter.DocumentInformation;
Console.WriteLine("{0} by {1}, {2} pages", info.Title, info.Author, info.PageCount);
Text extraction options
  • Layout - OriginalLayout (the default) keeps the layout of the page: when a page has two columns of text, the lines of the two columns stay side by side. ReadingLayout gives the text in reading order, the whole first column, then the second one - the best choice for indexing and search.

  • StartPageNumber and EndPageNumber - the pages to convert. The first page is 1; an end page of 0 means the last page of the document.

  • MarkPageBreaks - adds the PAGE_BREAK_MARK character (a form feed) after the text of each page, so that you can split the text into pages.

  • ClipText - the text hidden by a clipping path is in the document but not visible on the page. It is skipped by default; set ClipText to false to extract it too.

  • AddHtmlMetaTags - the result is a HTML document with the text and, as meta tags, the title, subject, keywords and author of the PDF document. HtmlCharset sets the charset meta tag: save the file with the same encoding.

  • UserPassword - the password of a protected document.

  • GetPageCount(String) - the number of pages of a document; DocumentInformation - the title, author, subject, keywords, dates and page count, after an operation; GetDocumentInformation(String) - the same information without extracting the text, with the size and rotation of each page.

  • PdfToolsTimeout - the maximum time of an operation, in seconds (600 by default).

PdfToTextConverter converter = new PdfToTextConverter();
converter.StartPageNumber = 2;
converter.EndPageNumber = 3;
converter.MarkPageBreaks = true;
converter.AddHtmlMetaTags = true;
converter.HtmlCharset = "utf-8";
converter.UserPassword = "open";

string html = converter.ConvertToText(@"C:\Documents\protected.pdf");
System.IO.File.WriteAllText(@"C:\Documents\protected.html", html, System.Text.Encoding.UTF8);

// the text of each page
string[] pages = html.Split(PdfToTextConverter.PAGE_BREAK_MARK);
Text per page and document information

ConvertToTextPages(String) extracts the text of the pages in one call and returns one string for each page, from StartPageNumber to EndPageNumber (an empty string for a page without text). It uses the Layout and ClipText options; each entry is the plain text of its page, without page break marks or HTML.

GetDocumentInformation(String) returns the title, author, subject, keywords, creator, producer, dates and page count of a document without extracting its text, and the size of each page in Pages: a PdfPageInfo for each page, in page order, with the width and height of the visible area of the page (the crop box) and of the whole page (the media box) in points (1/72 inch), and the rotation of the page (0, 90, 180 or 270 degrees). The sizes do not include the rotation: DisplayWidth and DisplayHeight are the size of the page as a viewer shows it. The Pages property is set by GetDocumentInformation; it is null after the other operations.

PdfToTextConverter converter = new PdfToTextConverter();
converter.Layout = TextLayout.ReadingLayout;

string[] pages = converter.ConvertToTextPages(@"C:\Documents\report.pdf");
for (int i = 0; i < pages.Length; i++)
{
    int pageNumber = converter.StartPageNumber + i;
    System.IO.File.WriteAllText(@"C:\Documents\report-page" + pageNumber + ".txt", pages[i]);
}

DocumentInformation info = converter.GetDocumentInformation(@"C:\Documents\report.pdf");
Console.WriteLine("{0} - {1} - {2} pages", info.Title, info.Author, info.PageCount);
foreach (PdfPageInfo page in info.Pages)
{
    Console.WriteLine("page {0}: {1:0.##} x {2:0.##} points, rotation {3}, displayed as {4:0.##} x {5:0.##}",
        page.PageNumber, page.Width, page.Height, page.Rotation, page.DisplayWidth, page.DisplayHeight);
}
Finding text and reading the text of an area

ExtractTextPositions(String, String, Boolean, Boolean) finds a text in a document, case sensitive or not, whole words only or not, and returns a TextPosition for every match: the page number, and the position and size of the text in points (1/72 inch) from the top left corner of the page.

ExtractTextAtCoords(String, Int32, Double, Double, Double, Double) returns the text of an area of a page, in the same coordinates. Together they read the fields of documents that have a known structure, like invoices: find the label of a field, then read the text on its right.

PdfToTextConverter converter = new PdfToTextConverter();
string pdfFile = @"C:\Documents\invoice.pdf";

TextPosition[] found = converter.ExtractTextPositions(pdfFile, "Invoice number:", true, false);
if (found.Length > 0)
{
    TextPosition label = found[0];
    double x = label.X + label.Width + 5;
    string invoiceNumber = converter.ExtractTextAtCoords(pdfFile, label.PageNumber,
        x, label.Y - 2, 555 - x, label.Height + 4).Trim();
    Console.WriteLine("Invoice number: " + invoiceNumber);
}

SearchTexts(String, String, Boolean, Boolean) searches for several texts at once and returns a TextSearchResult for each text, in the order of the texts: all the positions, the number of matches, the pages where the text was found (PageNumbers) and the positions on one page (GetPositionsOnPage(Int32)). Arabic words are found whether the document maps its shaped glyphs to the letters or to their presentation forms.

PdfToTextConverter converter = new PdfToTextConverter();
string[] words = { "invoice", "total", "harbor" };

TextSearchResult[] results = converter.SearchTexts(@"C:\Documents\report.pdf", words, false, true);
foreach (TextSearchResult result in results)
{
    Console.WriteLine("{0}: {1} matches", result.SearchText, result.Count);
    foreach (int pageNumber in result.PageNumbers)
        Console.WriteLine("  page {0}: {1}", pageNumber, result.GetPositionsOnPage(pageNumber).Length);
}

The positions use the same coordinates as the elements of ExpertPdf HTML to PDF Converter, so you can, for example, highlight the words found in a document:

using ExpertPdf.HtmlToPdf.PdfDocument;

TextPosition[] positions = new PdfToTextConverter().ExtractTextPositions(pdfFile, "harbor", false, true);

Document document = new Document(pdfFile);
foreach (TextPosition position in positions)
{
    RectangleElement highlight = new RectangleElement(position.X, position.Y, position.Width, position.Height);
    highlight.BackColor = System.Drawing.Color.Yellow;
    highlight.Transparency = 50;
    document.Pages[position.PageNumber - 1].AddElement(highlight);
}
document.Save(@"C:\Documents\highlighted.pdf");
Samples

The download has each sample in C# and VB.NET, for .NET Framework 4.6.2 (Samples folder) and for .NET 10 / .NET 11 (Samples_NET_10 folder). They work on the sample.pdf document that comes with them; sample-protected.pdf is the same document protected with the password "open".

  • ConvertPdfToText - a command line tool with all the extraction options. Without arguments it converts sample.pdf to sample.txt.

  • TextSearch - shows the document information and the size of each page, finds a word in a document read from memory and reads the fields of an invoice.

  • WinForms_PdfToText - a Windows Forms application with all the options, a preview of the text and a text search.

PDF to Text command line tool

The ConvertPdfToText sample is a complete command line tool:

ConvertPdfToText [/pdf:file.pdf] [/out:file] [/layout:original|reading] [/start:n] [/end:n]
                 [/pagebreaks] [/html[:charset]] [/noclip] [/userpswd:password]

Examples:

ConvertPdfToText /pdf:sample.pdf /layout:reading /pagebreaks
ConvertPdfToText /pdf:sample.pdf /html /start:2 /end:3
ConvertPdfToText /pdf:"C:\My Documents\protected.pdf" /userpswd:open
What's new in version 10
  • Version 10 is part of the ExpertPdf 22.0 release and needs a version 10 license key.

  • The text of each page in one call: ConvertToTextPages(String).

  • Several texts searched at once, the results grouped by text and page: SearchTexts(String, String, Boolean, Boolean).

  • The document information without the text: GetDocumentInformation(String).

  • The size (crop box and media box) and the rotation of each page: Pages, set by GetDocumentInformation.

  • New samples for .NET Framework, .NET 10 and .NET 11, in C# and VB.NET: a command line tool, a text search and invoice reader, and a Windows Forms application.

Licensing

A license key is emailed to you when you purchase the product. Set it with the LicenseKey property before you call the converter. Without a license key the converter extracts the text of the first 5 pages of a document and adds an evaluation notice to it (the search and ExtractTextAtCoords read the first 5 pages too: the area of a later page gives the notice alone). For a full evaluation, use the demo license key from the product download page or ask the support team for one.

Support: office@html-to-pdf.net, https://www.html-to-pdf.info