{"id":61302,"date":"2026-11-24T10:05:00","date_gmt":"2026-11-24T18:05:00","guid":{"rendered":"https:\/\/devblogs.microsoft.com\/dotnet\/?p=61302"},"modified":"2026-11-24T10:05:00","modified_gmt":"2026-11-24T18:05:00","slug":"document-extraction-dotnet-preview","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/dotnet\/document-extraction-dotnet-preview\/","title":{"rendered":"Introducing DocumentExtractionClient (preview): Extract documents in .NET"},"content":{"rendered":"<p>A lot of the information your apps need lives in documents. Invoices, contracts, reports, forms, and slide decks arrive as PDFs, scans, images, and Office files. Getting their content and structure out is the first step for search, automation, data entry, and archiving. It&#8217;s also how AI apps get the context they need. Before a model can answer questions about a document, your app has to turn that document into something the model can work with. Until now, each parser or service came with its own SDK and object model. Moving to another tool meant rewriting the code that used the results.<\/p>\n<p>Today we&#8217;re introducing a preview of <code>DocumentExtractionClient<\/code> in <code>Microsoft.Extensions.DocumentExtraction<\/code>, along with a set of starter providers in the <a href=\"https:\/\/github.com\/CommunityToolkit\/AI\/tree\/main\/DocumentExtraction\">.NET AI Community Toolkit<\/a>. Whichever provider you choose, the flow is the same. You load a document, pick a provider, and extract its contents into a common structure. Providers include a PDF parser that runs in process, a vision model behind any <code>IChatClient<\/code>, and cloud services like Azure Content Understanding.<\/p>\n<p>In this post, you&#8217;ll learn what document extraction is, where <code>DocumentExtractionClient<\/code> fits among the .NET AI building blocks, and how to extract your first document, swap providers, and add middleware. Then you&#8217;ll feed the results into a data ingestion pipeline with <code>Microsoft.Extensions.DataIngestion<\/code>, the foundation for context engineering, agentic workflows, and retrieval-augmented generation (RAG). Every sample is a single C# file you can run with <code>dotnet run<\/code>. They&#8217;re all in the <a href=\"https:\/\/github.com\/luisquintanilla\/dotnet-document-extraction-samples\">document extraction samples repo<\/a>.<\/p>\n<h2>What is document extraction?<\/h2>\n<p>Document extraction turns a file, such as a PDF, a scanned image, or an Office document, into structured content. A document shows text on a page, but the file often doesn&#8217;t say what that text <em>is<\/em>. A heading, a table cell, and a page number can all look like ordinary characters. Extraction recovers that structure, including:<\/p>\n<ul>\n<li><strong>Headings and paragraphs<\/strong>, so you know how the document is organized.<\/li>\n<li><strong>Tables<\/strong>, as a grid of cells, including merged header cells.<\/li>\n<li><strong>Figures<\/strong>, with their position and any description the provider can produce.<\/li>\n<li><strong>Sources<\/strong>, the page and region each element came from, so you can cite it or highlight it later.<\/li>\n<\/ul>\n<p>Getting there is harder than it sounds. Office files and many PDFs store their text digitally, so you can read it directly. Scans and photos are only pictures of pages, so they need optical character recognition (OCR). Tables have merged header cells, pages have running headers and footers, and multi-column layouts confuse a naive reading order. Different tools solve different parts of the problem. Each one returns its results in a different shape.<\/p>\n<p>Structure matters wherever you use the content, especially in AI apps. Models answer better when you give them the right context, and the right context depends on structure. When you chunk a document at its headings, each chunk covers one topic. When you flatten a table into a list of words, the model can no longer tell which number belongs to which row.<\/p>\n<h2>Introducing DocumentExtractionClient<\/h2>\n<p><code>DocumentExtractionClient<\/code> gives you one API for document extraction in .NET, regardless of which tool does the work. Its main method, <code>ExtractAsync<\/code>, takes a stream and returns an <code>ExtractionDocument<\/code>. That&#8217;s a tree of sections that contain text, tables, and images. Each element has sources that point back to where it came from. Providers implement this abstraction, so your code works with the same result type whether a PDF parser, a vision model, or a cloud service read the document.<\/p>\n<p>If you&#8217;ve used <code>IChatClient<\/code> or <code>IEmbeddingGenerator<\/code> from <code>Microsoft.Extensions.AI<\/code>, the pattern will feel familiar, with a common abstraction, interchangeable providers, and middleware you can layer on top.<\/p>\n<h2>Where it fits<\/h2>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/dotnet\/wp-content\/uploads\/sites\/10\/2026\/11\/document-extraction-ai-stack.webp\" alt=\".NET AI stack by library, from your app and agents down to models, with DocumentExtraction as the read step in context\" \/><\/p>\n<p>The .NET AI stack is a set of libraries, organized in layers:<\/p>\n<ul>\n<li><strong>Your app<\/strong>: web, desktop, mobile, and service apps built with .NET.<\/li>\n<li><strong>Agents and tools<\/strong>: agents that reason and call tools.\n<ul>\n<li><a href=\"https:\/\/www.nuget.org\/packages\/Microsoft.Agents.AI\"><code>Microsoft.Agents.AI<\/code><\/a>: Microsoft Agent Framework, for agents and workflows.<\/li>\n<li><a href=\"https:\/\/www.nuget.org\/packages\/ModelContextProtocol\"><code>ModelContextProtocol<\/code><\/a>: the MCP C# SDK, to connect tools and data.<\/li>\n<\/ul>\n<\/li>\n<li><strong>Context<\/strong>: the data your app and agents work with. Document extraction is the <em>read<\/em> step of this layer.\n<ul>\n<li><a href=\"https:\/\/www.nuget.org\/packages\/Microsoft.Extensions.DocumentExtraction\"><code>Microsoft.Extensions.DocumentExtraction<\/code><\/a>: turns files into structured documents.<\/li>\n<li><a href=\"https:\/\/www.nuget.org\/packages\/Microsoft.Extensions.DataIngestion\"><code>Microsoft.Extensions.DataIngestion<\/code><\/a>: chunks and enriches them.<\/li>\n<li><a href=\"https:\/\/www.nuget.org\/packages\/Microsoft.Extensions.VectorData.Abstractions\"><code>Microsoft.Extensions.VectorData<\/code><\/a>: stores them so you can search them.<\/li>\n<\/ul>\n<\/li>\n<li><strong>Models<\/strong>: models that work with text, images, or audio, whether they run locally or in the cloud.\n<ul>\n<li><a href=\"https:\/\/www.nuget.org\/packages\/Microsoft.Extensions.AI\"><code>Microsoft.Extensions.AI<\/code><\/a>: one way to call any model, with middleware.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p>Think of these libraries as building blocks. You compose the ones you need to build rich AI experiences, add capabilities as your app grows, and swap in a different provider or implementation without rewriting the rest of your app. You don&#8217;t need the whole stack, either. Document extraction works on its own, with or without AI.<\/p>\n<h2>Pick a provider<\/h2>\n<p>To help you get started, the <a href=\"https:\/\/github.com\/CommunityToolkit\/AI\/tree\/main\/DocumentExtraction\">.NET AI Community Toolkit<\/a> includes a set of starter providers. Like <code>DocumentExtractionClient<\/code>, they&#8217;re in preview. PdfPig runs in process. The vision language model runs wherever your <code>IChatClient<\/code> does, locally or hosted. The rest are hosted services.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/dotnet\/wp-content\/uploads\/sites\/10\/2026\/11\/document-extraction-providers.webp\" alt=\"Document extraction providers, including PdfPig in process, a vision model on any IChatClient, hosted services, or your own\" \/><\/p>\n<table>\n<thead>\n<tr>\n<th>Provider<\/th>\n<th>Package<\/th>\n<th>Runs<\/th>\n<th>Good for<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>PdfPig<\/td>\n<td><a href=\"https:\/\/www.nuget.org\/packages\/CommunityToolkit.DocumentExtraction.PdfPig\"><code>CommunityToolkit.DocumentExtraction.PdfPig<\/code><\/a><\/td>\n<td>In process<\/td>\n<td>PDFs that already have a text layer<\/td>\n<\/tr>\n<tr>\n<td>Vision language model<\/td>\n<td><a href=\"https:\/\/www.nuget.org\/packages\/CommunityToolkit.DocumentExtraction.VisionLanguageModel\"><code>CommunityToolkit.DocumentExtraction.VisionLanguageModel<\/code><\/a><\/td>\n<td>Any <code>IChatClient<\/code> that accepts images, local or hosted<\/td>\n<td>Scans and images, when you can review the output<\/td>\n<\/tr>\n<tr>\n<td>Azure Content Understanding<\/td>\n<td><a href=\"https:\/\/www.nuget.org\/packages\/CommunityToolkit.DocumentExtraction.AzureContentUnderstanding\"><code>CommunityToolkit.DocumentExtraction.AzureContentUnderstanding<\/code><\/a><\/td>\n<td>Azure<\/td>\n<td>OCR, layout, tables, and figures, plus analyzers you can customize<\/td>\n<\/tr>\n<tr>\n<td>Azure AI Document Intelligence<\/td>\n<td><a href=\"https:\/\/www.nuget.org\/packages\/CommunityToolkit.DocumentExtraction.AzureDocumentIntelligence\"><code>CommunityToolkit.DocumentExtraction.AzureDocumentIntelligence<\/code><\/a><\/td>\n<td>Azure<\/td>\n<td>OCR, layout, tables, and page coordinates<\/td>\n<\/tr>\n<tr>\n<td>Mistral OCR<\/td>\n<td><a href=\"https:\/\/www.nuget.org\/packages\/CommunityToolkit.DocumentExtraction.Mistral\"><code>CommunityToolkit.DocumentExtraction.Mistral<\/code><\/a><\/td>\n<td>Microsoft Foundry or the Mistral API<\/td>\n<td>Fast OCR to Markdown<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>There&#8217;s no single best provider, because their capabilities differ. PdfPig is fast, but it reads only PDFs and only the text that&#8217;s already in them. A vision model can read scans and images, but you should review its output. A local model can also be slow. Mistral OCR reads PDFs and images. The Azure services also accept formats like Office documents and handle OCR and layout analysis for tables and figures. With any hosted provider, including a hosted vision model, your document leaves your machine. Choose the provider whose capabilities match your documents, and change it later if your needs change.<\/p>\n<p>These providers are a starting point to help bootstrap the ecosystem. If you need a different parser, an internal service, or a model they don&#8217;t cover, you can write your own provider. Derive from <code>DocumentExtractionClient<\/code> and implement <code>ExtractAsync<\/code>. Your provider works with the same middleware, dependency injection, and data ingestion code as the starter providers. We&#8217;d love to see the community build and share providers for more tools and services.<\/p>\n<h2>What you&#8217;ll need<\/h2>\n<ul>\n<li><a href=\"https:\/\/dotnet.microsoft.com\/download\/dotnet\/11.0\">.NET 11 SDK<\/a>. On Windows, you can install it with <code>winget install Microsoft.DotNet.SDK.11<\/code>.<\/li>\n<li>Optional: <a href=\"https:\/\/ollama.com\">Ollama<\/a> for the vision model and embedding samples.<\/li>\n<li>Optional: an Azure subscription and the <a href=\"https:\/\/aka.ms\/azd\">Azure Developer CLI<\/a> for the cloud providers.<\/li>\n<\/ul>\n<p>Don&#8217;t want to install anything? Open the samples repo in <a href=\"https:\/\/codespaces.new\/luisquintanilla\/dotnet-document-extraction-samples\">GitHub Codespaces<\/a>. The dev container has .NET 11 and an Ollama sidecar with the models already pulled.<\/p>\n<p>The samples use three short intro books I wrote for this post: <em>Tokens, Explained<\/em>, <em>Tensors in Ten Pages<\/em>, and <em>Agents Propose, Tools Decide<\/em>. Each one has headings, running headers and footers, a table with a merged header cell, a figure, and code. That&#8217;s enough structure to see how each provider handles a real document. Each book also comes as a scanned copy with no text layer, which you&#8217;ll use later in this post.<\/p>\n<h2>Extract your first document<\/h2>\n<p>Clone the repo:<\/p>\n<pre><code class=\"language-bash\">git clone https:\/\/github.com\/luisquintanilla\/dotnet-document-extraction-samples\ncd dotnet-document-extraction-samples<\/code><\/pre>\n<p>Here&#8217;s the first sample, <code>01-extract.cs<\/code>. It reads a PDF with PdfPig and prints the outline.<\/p>\n<pre><code class=\"language-csharp\">#!\/usr\/bin\/env dotnet\n#:package Microsoft.Extensions.DocumentExtraction@11.0.0-preview.1.26560.3\n#:package CommunityToolkit.DocumentExtraction.PdfPig@1.0.0-preview\n#:property PublishAot=false\n#:property NoWarn=$(NoWarn);MEDE0001;EXTEXP0019;CTDE0001\n\nusing CommunityToolkit.DocumentExtraction.PdfPig;\nusing Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DocumentExtraction;\nusing Microsoft.Extensions.Documents;\nusing UglyToad.PdfPig.DocumentLayoutAnalysis.PageSegmenter;\n\nstring path = args.Length &gt; 0 ? args[0] : Path.Combine(\"books\", \"pdf\", \"tokens-explained.pdf\");\n\n\/\/ PdfPig reads the PDF text layer. Docstrum groups words into paragraph-sized blocks,\n\/\/ and the role callback marks large text as a heading. Both are local heuristics.\nusing DocumentExtractionClient extractor = new PdfPigDocumentExtractionClient(\n    pageSegmenter: DocstrumBoundingBoxes.Instance,\n    roleResolver: block =&gt; block.TextLines[0].Words[0].Letters[0].PointSize &gt;= 13 ? \"heading\" : null);\n\nawait using var input = File.OpenRead(path);\nExtractionDocument document = await extractor.ExtractAsync(input, Path.GetFileName(path), \"application\/pdf\");\n\nConsole.WriteLine($\"{document.Identifier}: {document.Sections.Count} sections\");\nConsole.WriteLine();\n\nforeach (var section in document.Sections)\n{\n    int? page = section.Sources.FirstOrDefault()?.Page.PageNumber;\n    Console.WriteLine($\"Section (page {page?.ToString() ?? \"?\"}), {section.Elements.Count} elements\");\n\n    foreach (var element in section.Elements)\n    {\n        string text = element.Content is TextContent t ? t.Text.ReplaceLineEndings(\" \") : \"\";\n        if (text.Length &gt; 70) text = text[..67] + \"...\";\n\n        string kind = element switch\n        {\n            ExtractionDocumentTextElement { HeadingLevel: { } level } =&gt; $\"heading {level}\",\n            ExtractionDocumentTextElement e =&gt; e.Role ?? \"text\",\n            ExtractionDocumentTableElement table =&gt; $\"table {table.Cells.RowCount}x{table.Cells.ColumnCount}\",\n            ExtractionDocumentImageElement =&gt; \"image\",\n            _ =&gt; element.GetType().Name,\n        };\n        Console.WriteLine($\"  [{kind}] {text}\");\n    }\n}<\/code><\/pre>\n<h2>Run the app<\/h2>\n<pre><code class=\"language-bash\">dotnet run 01-extract.cs<\/code><\/pre>\n<p>You&#8217;ll see one section per page. Here&#8217;s the start of the output:<\/p>\n<pre><code class=\"language-text\">tokens-explained.pdf: 5 sections\n\nSection (page 1), 5 elements\n  [heading] Tokens, Explained\n  [heading] A short introduction to tokenization in .NET By Luis Quintanilla In...\n  [text] What a token is, and why models read tokens instead of words The to...\n  [text] Before you start. All examples use the Microsoft.ML.Tokenizers NuGe...\n  [text] Page 1 of 5\nSection (page 2), 14 elements\n  [text] Tokens, Explained\n  [text] Sample book for document extraction\n  [heading] What is a token?\n  [text] A language model never sees your text directly. Before the model ru...\n  ...<\/code><\/pre>\n<h2>How it works<\/h2>\n<p><code>DocumentExtractionClient<\/code> is the abstraction every provider derives from, so the rest of your code depends only on it. You call <code>ExtractAsync<\/code> with a stream, an identifier such as the file name, and a media type, and you get back an <code>ExtractionDocument<\/code>.<\/p>\n<p>That result is a tree. An <code>ExtractionDocument<\/code> has <code>Sections<\/code>, and each section has <code>Elements<\/code> such as text, tables, and images. Text elements can carry a heading level or a role like <code>pageHeader<\/code>, and every element can carry <code>Sources<\/code> that point back to the page it came from.<\/p>\n<p>A PDF text layer records where letters are on the page but not what they mean. So the sample tells PdfPig how to group words into blocks and which text to treat as a heading (anything 13 points or larger). You can see that heuristic misfire in the output above, where the subtitle and byline are tagged as a heading. It&#8217;s a reasonable first pass. When you need more structure, you can swap providers.<\/p>\n<h2>Swap providers without changing your code<\/h2>\n<p>The second sample, <code>02-swap-providers.cs<\/code>, picks a provider by name, and everything after that line is the same for every provider:<\/p>\n<pre><code class=\"language-csharp\">using DocumentExtractionClient? extractor = Providers.Create(provider, out string? skipped);\n\n\/\/ From here down, nothing knows or cares which provider is running.\nExtractionDocument document = await Samples.ExtractFileAsync(extractor, path);\nSamples.PrintOutline(document);<\/code><\/pre>\n<p><code>Providers.Create<\/code> lives in <a href=\"https:\/\/github.com\/luisquintanilla\/dotnet-document-extraction-samples\/blob\/main\/common\/Providers.cs\"><code>common\/Providers.cs<\/code><\/a>. Here&#8217;s how it creates each provider. The Azure providers sign in with <code>DefaultAzureCredential<\/code>, so there are no keys in the code.<\/p>\n<pre><code class=\"language-csharp\">\/\/ Azure Content Understanding\nDocumentExtractionClient contentUnderstanding = new ContentUnderstandingClient(new Uri(endpoint), new DefaultAzureCredential())\n    .AsDocumentExtractionClient(new() { AnalyzerId = \"prebuilt-layout\" });\n\n\/\/ Azure AI Document Intelligence\nDocumentExtractionClient docIntel = new DocumentIntelligenceClient(new Uri(endpoint), new DefaultAzureCredential())\n    .AsDocumentExtractionClient(new() { DefaultModel = \"prebuilt-layout\" });\n\n\/\/ Mistral OCR in Microsoft Foundry\nDocumentExtractionClient mistral = new MistralDocumentExtractionClient(\n    new MistralDocumentExtractionClientOptions\n    {\n        OcrEndpoint = new Uri(mistralUri),\n        DefaultModel = \"mistral-ocr-4-0\",\n        TokenScope = \"https:\/\/cognitiveservices.azure.com\/.default\",\n    },\n    new DefaultAzureCredential());\n\n\/\/ A vision language model, using any IChatClient. Here, Ollama.\nIChatClient chat = new OllamaApiClient(new Uri(\"http:\/\/localhost:11434\"), \"qwen3.5:4b\");\nDocumentExtractionClient vision = new VisionLanguageModelDocumentExtractionClient(\n    chat, new() { UseStructuredOutput = true });<\/code><\/pre>\n<p>The vision model provider takes any <code>IChatClient<\/code> that accepts images, so you can use a local or a hosted model. This sample uses a local model through Ollama, which accepts images but not PDFs. So <code>Providers.cs<\/code> renders each PDF page as an image before sending it to the model.<\/p>\n<p>Samples 02 through 04 all read the same page, page 3 of <em>Tokens, Explained<\/em> (<code>books\/pages\/tokens-explained-hero.pdf<\/code>), because it has a bit of everything, including running headers, a heading, a table with merged cells, a figure, and code. Here it is, labeled with the roles that a service like Azure Content Understanding might return for each part:<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/dotnet\/wp-content\/uploads\/sites\/10\/2026\/11\/document-extraction-sample-page.webp\" alt=\"Page 3 of Tokens, Explained labeled with header, heading, text, table, image, and page number roles\" \/><\/p>\n<p>Now run that page through a few providers:<\/p>\n<pre><code class=\"language-bash\">dotnet run 02-swap-providers.cs -- pdfpig\ndotnet run 02-swap-providers.cs -- cu\ndotnet run 02-swap-providers.cs -- ollama<\/code><\/pre>\n<p>Here&#8217;s what came back:<\/p>\n<pre><code class=\"language-text\">PdfPig (local, text layer) took 0.4s\n  p1 [text] Tokens, Explained\n  p1 [text] Sample book for document extraction\n  p1 [heading] Tokenizers in .NET\n  p1 [text] The Microsoft.ML.Tokenizers library brings popular model tokenizers...\n  p1 [text] Tokenizer\n  p1 [text] Algorithm\n  p1 [text] .NET type\n  ... 23 more lines, one per table cell ...\n\nAzure Content Understanding took 10.2s\n  p1 [pageHeader] Tokens, Explained\n  p1 [pageHeader] Sample book for document extraction\n  p1 [heading] Tokenizers in .NET\n  p1 [text] The Microsoft. ML. Tokenizers library brings popular model tokenize...\n  p1 [table 6x5]\n  p1 [image]\n  ...\n  p1 [pageNumber] Page 3 of 5\n\nVision language model (Ollama) took 23.6s\n  p1 [text] # Tokens, Explained  Sample book for document extraction  ## Tokeni...\n  p1 [table 6x5]\n  p1 [image]<\/code><\/pre>\n<p>The same extraction code produces different results because each provider handles extraction differently. PdfPig was fastest, but it returned the table as loose lines of text. Content Understanding recognized the table, the figure, and the running headers, and labeled each one with a role. The vision model also found the table, and it returned the text as Markdown.<\/p>\n<p>The third sample, <code>03-compare.cs<\/code>, runs every provider you&#8217;ve configured on the same page and writes a side-by-side report:<\/p>\n<pre><code class=\"language-text\">pdfpig      0.4s  1 headings, 34 text, 0 tables, 0 images\nollama     26.9s  0 headings, 1 text, 1 tables, 1 images\nmistral    10.2s  0 headings, 2 text, 0 tables, 1 images\ndocintel   13.0s  2 headings, 9 text, 1 tables, 1 images\ncu         10.4s  1 headings, 10 text, 1 tables, 1 images<\/code><\/pre>\n<p>Even the two Azure services differ here. Document Intelligence tagged both headings on the page, while Content Understanding returned the second one as plain text. These timings come from my machine and the cloud services I provisioned, so yours might vary depending on your setup. The shape of the results is what matters, so try a few providers on your own documents before you choose one.<\/p>\n<h2>Work with the results<\/h2>\n<h3>Walk the whole tree<\/h3>\n<p>An <code>ExtractionDocument<\/code> is a tree by design. <code>document.Sections<\/code> holds the root sections, and a section&#8217;s <code>Elements<\/code> can include nested sections as well as content. How deeply sections nest depends on the provider. PdfPig returns one section per page, while layout-aware providers like Content Understanding and Document Intelligence map the document&#8217;s own hierarchy into nested sections. On the sample page, a loop over <code>document.Sections<\/code> and their <code>Elements<\/code> reaches only 4 of the 13 content elements that Content Understanding returns.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/dotnet\/wp-content\/uploads\/sites\/10\/2026\/11\/document-extraction-result-tree.webp\" alt=\"Content Understanding result tree where a two-level loop reaches 4 of 13 elements and EnumerateContent reaches all 13\" \/><\/p>\n<p>To reach all of the content, use <code>EnumerateContent()<\/code>, which walks the tree depth-first in document order and returns every element that isn&#8217;t a section:<\/p>\n<pre><code class=\"language-csharp\">foreach (var table in document.EnumerateContent().OfType&lt;ExtractionDocumentTableElement&gt;())\n{\n    Console.WriteLine($\"Table: {table.Cells.RowCount} rows x {table.Cells.ColumnCount} columns\");\n}<\/code><\/pre>\n<h3>Read tables cell by cell<\/h3>\n<p>Tables are a grid in which each cell knows its row, its column, and how many rows and columns it spans. A merged cell appears once, at its top-left position. The fourth sample, <code>04-tables-and-sources.cs<\/code>, prints every cell:<\/p>\n<pre><code class=\"language-csharp\">foreach (var cell in table.Cells)\n{\n    if (cell is null) continue; \/\/ an empty position in the grid\n\n    string span = (cell.RowSpan, cell.ColumnSpan) switch\n    {\n        (1, 1) =&gt; \"\",\n        var (rows, cols) =&gt; $\" spans {rows}x{cols}\",\n    };\n    string role = cell.Role is null ? \"\" : $\" ({cell.Role})\";\n    Console.WriteLine($\"  [{cell.RowIndex},{cell.ColumnIndex}]{span}{role} {Samples.TextOf(cell.Content)}\");\n}<\/code><\/pre>\n<p>Here&#8217;s the start of the table from Content Understanding (<code>dotnet run 04-tables-and-sources.cs -- cu<\/code>). It found the merged header cells and marked them as column headers:<\/p>\n<pre><code class=\"language-text\">Table: 6 rows x 5 columns\n  [0,0] spans 2x1 (columnHeader) Tokenizer\n  [0,1] spans 2x1 (columnHeader) Algorithm\n  [0,2] spans 2x1 (columnHeader) .NET type\n  [0,3] spans 1x2 (columnHeader) Where you'll see it\n  [1,3] (columnHeader) Model families\n  [1,4] (columnHeader) Typical use\n  [2,0] (content) Tiktoken\n  [2,1] (content) Optimized BPE\n  [2,2] (content) TiktokenTokenizer\n  ...<\/code><\/pre>\n<p>The vision model also got every cell&#8217;s text right, but it didn&#8217;t report the spans. Differences like that matter when you turn a table back into Markdown for a model to read.<\/p>\n<h3>Know where things came from<\/h3>\n<p>Each element has <code>Sources<\/code>. A source points to a page and, when the provider knows it, a polygon around the element on that page:<\/p>\n<pre><code class=\"language-text\">\"Tokenizers in .NET\"\n  page 1, Inch: (0.79,0.81) (2.95,0.81) (2.95,1.06) (0.79,1.06)<\/code><\/pre>\n<p>That&#8217;s what you need to show a citation or highlight the paragraph an answer came from.<\/p>\n<h2>Add logging and middleware<\/h2>\n<p>Because every provider is a <code>DocumentExtractionClient<\/code>, you can wrap any of them with middleware, the same way you do with <code>IChatClient<\/code>. Register a client in dependency injection, then layer behavior on top:<\/p>\n<pre><code class=\"language-csharp\">services.AddKeyedDocumentExtractionClient(\"documents\", sp =&gt; new PdfPigDocumentExtractionClient())\n    .UseLogging()\n    .Use((inner, sp) =&gt; new ScannedPdfFallback(inner, sp.GetRequiredKeyedService&lt;DocumentExtractionClient&gt;(\"ocr\")));<\/code><\/pre>\n<p>To write your own middleware, derive from <code>DelegatingDocumentExtractionClient<\/code> and override <code>ExtractAsync<\/code>. Providers have different capabilities, and documents have different needs. A PDF with a text layer only needs PdfPig, a scan needs OCR, and a page full of tables benefits from layout analysis. The fallback in <code>05-pipeline.cs<\/code> tries PdfPig first. If the PDF comes back with almost no text, it treats the file as a scan and sends the same bytes to an OCR provider instead.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/dotnet\/wp-content\/uploads\/sites\/10\/2026\/11\/document-extraction-middleware.webp\" alt=\"Flow where PdfPig reads PDFs with a text layer and a scanned PDF falls back to Content Understanding for OCR\" \/><\/p>\n<pre><code class=\"language-csharp\">sealed class ScannedPdfFallback(DocumentExtractionClient inner, DocumentExtractionClient ocr) : DelegatingDocumentExtractionClient(inner)\n{\n    public override async Task&lt;ExtractionDocument&gt; ExtractAsync(Stream stream, string identifier, string mediaType,\n        DocumentExtractionOptions? options = null, CancellationToken cancellationToken = default)\n    {\n        \/\/ Buffer the input so it can be read twice.\n        using var buffer = new MemoryStream();\n        await stream.CopyToAsync(buffer, cancellationToken);\n        buffer.Position = 0;\n\n        var document = await base.ExtractAsync(buffer, identifier, mediaType, options, cancellationToken);\n        int characters = document.EnumerateContent().Sum(e =&gt; e.Content is TextContent t ? t.Text.Trim().Length : 0);\n        if (characters &gt; 100)\n        {\n            return document;\n        }\n\n        Console.WriteLine($\"   No text layer in {identifier} ({characters} characters). Falling back to OCR.\");\n        buffer.Position = 0;\n        return await ocr.ExtractAsync(buffer, identifier, mediaType, options, cancellationToken);\n    }\n}<\/code><\/pre>\n<p>Here it is on the regular book and on its scanned copy, with Content Understanding as the OCR provider:<\/p>\n<pre><code class=\"language-text\">== tokens-explained.pdf\n   pdfpig read tokens-explained.pdf in 1.1s\n   5 sections, about 739 words\n\n== tokens-explained-scanned.pdf\n   pdfpig read tokens-explained-scanned.pdf in 0.0s\n   No text layer in tokens-explained-scanned.pdf (0 characters). Falling back to OCR.\n   cu read tokens-explained-scanned.pdf in 13.1s\n   5 sections, about 767 words<\/code><\/pre>\n<p>The app asked for a document and got one, without needing to know that the second file was a scan. The same pattern works for any capability. You can route documents with tables to a layout-aware provider or images to a vision model, and the rest of your code stays the same.<\/p>\n<h2>Feed a data ingestion pipeline<\/h2>\n<p>Last year we introduced <a href=\"https:\/\/devblogs.microsoft.com\/dotnet\/introducing-data-ingestion-building-blocks-preview\/\">data ingestion building blocks for .NET<\/a>. <code>Microsoft.Extensions.DataIngestion<\/code> gives you a pipeline that reads documents, splits them into chunks, and writes them to a vector store. Document extraction fits in at the start. What you ingest becomes context you can use in many ways. You can ground answers in a RAG app, engineer the context you give a model, or give an agent knowledge to search with a tool.<\/p>\n<p>The sixth sample, <code>06-ingest.cs<\/code>, shows the RAG case. It extracts the three books, chunks them at their headings, embeds the chunks with an embedding model, and searches them:<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/dotnet\/wp-content\/uploads\/sites\/10\/2026\/11\/document-extraction-rag-pipeline.webp\" alt=\"Pipeline that extracts, chunks, embeds, and stores three books, then answers a question with matching sections\" \/><\/p>\n<pre><code class=\"language-csharp\">\/\/ Any DocumentExtractionClient works here. This one uses Azure Content Understanding.\nDocumentExtractionClient extractor = new ContentUnderstandingClient(new Uri(endpoint), new DefaultAzureCredential())\n    .AsDocumentExtractionClient(new() { AnalyzerId = \"prebuilt-layout\" });\n\nIngestionDocumentReader reader = new ExtractionReader(extractor);\n\nvar tokenizer = TiktokenTokenizer.CreateForModel(\"gpt-4o\");\nIngestionChunker&lt;string&gt; chunker = new HeaderChunker(new IngestionChunkerOptions(tokenizer)\n{\n    MaxTokensPerChunk = 256,\n    OverlapTokens = 32,\n});\n\nIEmbeddingGenerator&lt;string, Embedding&lt;float&gt;&gt; embeddings =\n    new OllamaApiClient(new Uri(\"http:\/\/localhost:11434\"), \"embeddinggemma\");\nusing var store = new InMemoryVectorStore(new() { EmbeddingGenerator = embeddings });\nusing var writer = new VectorStoreWriter&lt;string&gt;(store, dimensionCount: 768);\n\nusing var pipeline = new IngestionPipeline&lt;string&gt;(reader, chunker, writer);\nawait foreach (var result in pipeline.ProcessAsync(books))\n{\n    Console.WriteLine($\"Ingested {Path.GetFileName(result.DocumentId)}: {(result.Succeeded ? \"ok\" : result.Exception?.Message)}\");\n}<\/code><\/pre>\n<p>The pipeline reads documents through an <code>IngestionDocumentReader<\/code>, so the sample includes its own reader, <code>ExtractionReader<\/code>, for convenience. It calls <code>ExtractAsync<\/code> and maps the resulting <code>ExtractionDocument<\/code> to the <code>IngestionDocument<\/code> the pipeline chunks:<\/p>\n<pre><code class=\"language-csharp\">sealed class ExtractionReader(DocumentExtractionClient client) : IngestionDocumentReader\n{\n    public override async Task&lt;IngestionDocument&gt; ReadAsync(Stream source, string identifier, string mediaType,\n        CancellationToken cancellationToken = default)\n    {\n        var extracted = await client.ExtractAsync(source, identifier, mediaType, cancellationToken: cancellationToken);\n        var document = new IngestionDocument(identifier);\n        \/\/ Map each section's headings, paragraphs, and tables to ingestion elements.\n        ...\n        return document;\n    }\n}<\/code><\/pre>\n<p>It walks every nested section, keeps headings as headings, and turns tables into Markdown. It skips running headers and page numbers, which only add noise to chunks. For now, if you&#8217;re combining the two in your own apps, you can copy the <a href=\"https:\/\/github.com\/luisquintanilla\/dotnet-document-extraction-samples\/blob\/main\/06-ingest.cs\">full reader from the sample<\/a>. We intend to make composing document extraction and data ingestion simpler in upcoming releases.<\/p>\n<p>Run it with Content Understanding and ask a question:<\/p>\n<pre><code class=\"language-bash\">dotnet run 06-ingest.cs -- cu \"How do I count tokens before calling a model?\"<\/code><\/pre>\n<pre><code class=\"language-text\">Ingested agents-propose-tools-decide.pdf: ok\nIngested tensors-in-ten-pages.pdf: ok\nIngested tokens-explained.pdf: ok\n\nQ: How do I count tokens before calling a model?\n\n[0.60] tokens-explained.pdf | Plan your budget\n   Plan your budget Think of the context window as a budget you split between the parts of your\n   prompt. ... | Part of the request | Example tokens | | --- | --- | | System prompt | 1,000 | ...\n\n[0.60] tokens-explained.pdf | Three things to remember\n   Three things to remember . A token is not a word. A token often includes its leading space...\n\n[0.55] tokens-explained.pdf | Counting tokens and staying in budget\n   Counting tokens and staying in budget Every model has a context window, the maximum number...<\/code><\/pre>\n<p>Each result knows which section it came from, because extraction found the headings and the chunker split there. The top result even includes the budget table as Markdown. Good structure gives you chunks that each cover one topic, with enough context to be useful.<\/p>\n<h2>Next steps<\/h2>\n<p>We&#8217;re excited to see what you build. Here&#8217;s where to go next:<\/p>\n<ul>\n<li>Try out the <a href=\"https:\/\/github.com\/luisquintanilla\/dotnet-document-extraction-samples\">document extraction samples<\/a> and run them on your own documents.<\/li>\n<li>Learn how <a href=\"https:\/\/learn.microsoft.com\/dotnet\/ai\/conceptual\/data-ingestion\">data ingestion works in .NET<\/a>.<\/li>\n<\/ul>\n<p>We want to hear from you. Share your feedback, ideas, and suggestions, and let us know if something doesn&#8217;t work as expected. For <code>DocumentExtractionClient<\/code> itself, <a href=\"https:\/\/github.com\/dotnet\/extensions\/issues\">open an issue in dotnet\/extensions<\/a>. For a specific provider, <a href=\"https:\/\/github.com\/CommunityToolkit\/AI\/issues\">open an issue in the .NET AI Community Toolkit<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Meet DocumentExtractionClient, a preview .NET API that turns PDFs, images, and other documents into structured content, with a set of starter providers to choose from.<\/p>\n","protected":false},"author":26108,"featured_media":61303,"comment_status":"open","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[685,7781],"tags":[8250,8249,7242,8247,7885,8246,8245,8251,8248,7888,7811],"class_list":["post-61302","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-dotnet","category-ai","tag-azure-ai-document-intelligence","tag-azure-content-understanding","tag-communitytoolkit","tag-document-extraction","tag-microsoft-extensions-ai","tag-microsoft-extensions-dataingestion","tag-microsoft-extensions-documentextraction","tag-mistral","tag-ocr","tag-ollama","tag-rag"],"acf":[],"blog_post_summary":"<p>Meet DocumentExtractionClient, a preview .NET API that turns PDFs, images, and other documents into structured content, with a set of starter providers to choose from.<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/posts\/61302","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/users\/26108"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/comments?post=61302"}],"version-history":[{"count":1,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/posts\/61302\/revisions"}],"predecessor-version":[{"id":61324,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/posts\/61302\/revisions\/61324"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/media\/61303"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/media?parent=61302"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/categories?post=61302"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/tags?post=61302"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}