PDF to Text Converter |
The PDF to text part of ExpertPdf Anywhere extracts the text of PDF documents on Windows, Linux and macOS. 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 ExpertPdf.Anywhere namespace. The text is read by the native PDF tool of the library, ExpertPdf.Tools (ExpertPdf.Tools.exe on Windows), which the converter runs as a separate process. The converter is disposable: a using statement, or Close, releases the document read by the last call.
Extract the text of a whole document or of a range of pages, from a file or a stream (a MemoryStream for a document in memory).
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.
Run the same code on Windows, Linux and macOS.
The converter is part of the ExpertPdf.Anywhere package. The PDF tool comes with the native package of your platform (ExpertPdf.Anywhere.Native.<rid>) or with a platform package (ExpertPdf.Anywhere.Windows, .Linux, .Linux.Arm64, .MacOS), which copies it next to your application when it builds and when it is published. See Installation.
dotnet add package ExpertPdf.Anywhere.Windows
The tool is found next to the application. If it is in another folder, set its full path, or the folder that holds it, with the PdfToolsFullPath property.
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.Anywhere; PdfToTextConverter converter = new PdfToTextConverter(); // the text in reading order: a whole column, then the next one converter.Layout = TextLayout.ReadingLayout; string text = converter.ConvertToText("report.pdf"); File.WriteAllText("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);
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("protected.pdf"); File.WriteAllText("protected.html", html, System.Text.Encoding.UTF8); // the text of each page string[] pages = html.Split(PdfToTextConverter.PAGE_BREAK_MARK);
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("report.pdf"); for (int i = 0; i < pages.Length; i++) { int pageNumber = converter.StartPageNumber + i; File.WriteAllText("report-page" + pageNumber + ".txt", pages[i]); } DocumentInformation info = converter.GetDocumentInformation("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.#} pt, rotated {3}, shown as {4:0.#} x {5:0.#}", page.PageNumber, page.Width, page.Height, page.Rotation, page.DisplayWidth, page.DisplayHeight); }
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 = "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("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 page elements of Document, so you can, for example, highlight the words found in a document:
using ExpertPdf.Anywhere; using ExpertPdf.Anywhere.PdfDocument; TextPosition[] positions = new PdfToTextConverter().ExtractTextPositions(pdfFile, "harbor", false, true); using (Document document = new Document(pdfFile)) { foreach (TextPosition position in positions) { RectangleElement highlight = new RectangleElement(position.X, position.Y, position.Width, position.Height); highlight.BackColor = Color.Yellow; highlight.Transparency = 50; document.Pages[position.PageNumber - 1].AddElement(highlight); } document.Save("highlighted.pdf"); }
The samples download has these console applications, in C# and VB.NET, for Windows, Linux and macOS. 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.
The ConvertPdfToText sample is a complete command line tool:
ConvertPdfToText [/pdf:file.pdf] [/out:file] [/layout:original|reading]
[/start:n] [/end:n] [/pagebreaks] [/pages] [/html[:charset]] [/noclip]
[/userpswd:password]/pages saves the text of each page in a file of its own (sample-page1.txt, ...). Examples:
ConvertPdfToText /pdf:sample.pdf /layout:reading /pagebreaks ConvertPdfToText /pdf:sample.pdf /html /start:2 /end:3 ConvertPdfToText /pdf:sample.pdf /pages /layout:reading ConvertPdfToText /pdf:sample-protected.pdf /userpswd:open
Set LicenseKey once when the application starts, or the LicenseKey property before you call it. Without a license key the converter works fully and adds an evaluation notice to the extracted text. See Licensing.