![]() |
|
[DevBlog MS] Introducing DocumentExtractionClient (preview): Extract documents in .NE - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: C#, Visual Basic & .NET (https://sickgaming.net/forum-79.html) +--- Thread: [DevBlog MS] Introducing DocumentExtractionClient (preview): Extract documents in .NE (/thread-116220.html) |
[DevBlog MS] Introducing DocumentExtractionClient (preview): Extract documents in .NE - xSicKxBot - 11-24-2026 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’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. Today we’re introducing a preview of Code: DocumentExtractionClientCode: Microsoft.Extensions.DocumentExtractionCode: IChatClientIn this post, you’ll learn what document extraction is, where Code: DocumentExtractionClientCode: Microsoft.Extensions.DataIngestionCode: dotnet runWhat is document extraction? 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’t say what that text is. A heading, a table cell, and a page number can all look like ordinary characters. Extraction recovers that structure, including:
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. 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. Introducing DocumentExtractionClient Code: DocumentExtractionClientCode: ExtractAsyncCode: ExtractionDocumentIf you’ve used Code: IChatClientCode: IEmbeddingGeneratorCode: Microsoft.Extensions.AIWhere it fits ![]() The .NET AI stack is a set of libraries, organized in layers:
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’t need the whole stack, either. Document extraction works on its own, with or without AI. Pick a provider To help you get started, the .NET AI Community Toolkit includes a set of starter providers. Like Code: DocumentExtractionClientCode: IChatClient![]() Provider | Package | Runs | Good for PdfPig | CommunityToolkit.DocumentExtraction.PdfPig | In process | PDFs that already have a text layer Vision language model | CommunityToolkit.DocumentExtraction.VisionLanguageModel | Any Code: IChatClientAzure Content Understanding | CommunityToolkit.DocumentExtraction.AzureContentUnderstanding | Azure | OCR, layout, tables, and figures, plus analyzers you can customize Azure AI Document Intelligence | CommunityToolkit.DocumentExtraction.AzureDocumentIntelligence | Azure | OCR, layout, tables, and page coordinates Mistral OCR | CommunityToolkit.DocumentExtraction.Mistral | Microsoft Foundry or the Mistral API | Fast OCR to Markdown There’s no single best provider, because their capabilities differ. PdfPig is fast, but it reads only PDFs and only the text that’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. 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’t cover, you can write your own provider. Derive from Code: DocumentExtractionClientCode: ExtractAsyncWhat you’ll need
Don’t want to install anything? Open the samples repo in GitHub Codespaces. The dev container has .NET 11 and an Ollama sidecar with the models already pulled. The samples use three short intro books I wrote for this post: Tokens, Explained, Tensors in Ten Pages, and Agents Propose, Tools Decide. Each one has headings, running headers and footers, a table with a merged header cell, a figure, and code. That’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’ll use later in this post. Extract your first document Clone the repo: Code: git clone https://github.com/luisquintanilla/dotnet-document-extraction-samples
cd dotnet-document-extraction-samplesHere’s the first sample, Code: 01-extract.csCode: #!/usr/bin/env dotnet
#:package Microsoft.Extensions.DocumentExtraction@11.0.0-preview.1.26560.3
#:package CommunityToolkit.DocumentExtraction.PdfPig@1.0.0-preview
#:property PublishAot=false
#:property NoWarn=$(NoWarn);MEDE0001;EXTEXP0019;CTDE0001
using CommunityToolkit.DocumentExtraction.PdfPig;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.DocumentExtraction;
using Microsoft.Extensions.Documents;
using UglyToad.PdfPig.DocumentLayoutAnalysis.PageSegmenter;
string path = args.Length > 0 ? args[0] : Path.Combine("books", "pdf", "tokens-explained.pdf");
// PdfPig reads the PDF text layer. Docstrum groups words into paragraph-sized blocks,
// and the role callback marks large text as a heading. Both are local heuristics.
using DocumentExtractionClient extractor = new PdfPigDocumentExtractionClient(
pageSegmenter: DocstrumBoundingBoxes.Instance,
roleResolver: block => block.TextLines[0].Words[0].Letters[0].PointSize >= 13 ? "heading" : null);
await using var input = File.OpenRead(path);
ExtractionDocument document = await extractor.ExtractAsync(input, Path.GetFileName(path), "application/pdf");
Console.WriteLine($"{document.Identifier}: {document.Sections.Count} sections");
Console.WriteLine();
foreach (var section in document.Sections)
{
int? page = section.Sources.FirstOrDefault()?.Page.PageNumber;
Console.WriteLine($"Section (page {page?.ToString() ?? "?"}), {section.Elements.Count} elements");
foreach (var element in section.Elements)
{
string text = element.Content is TextContent t ? t.Text.ReplaceLineEndings(" ") : "";
if (text.Length > 70) text = text[..67] + "...";
string kind = element switch
{
ExtractionDocumentTextElement { HeadingLevel: { } level } => $"heading {level}",
ExtractionDocumentTextElement e => e.Role ?? "text",
ExtractionDocumentTableElement table => $"table {table.Cells.RowCount}x{table.Cells.ColumnCount}",
ExtractionDocumentImageElement => "image",
_ => element.GetType().Name,
};
Console.WriteLine($" [{kind}] {text}");
}
}Run the app Code: dotnet run 01-extract.csYou’ll see one section per page. Here’s the start of the output: Code: tokens-explained.pdf: 5 sections
Section (page 1), 5 elements
[heading] Tokens, Explained
[heading] A short introduction to tokenization in .NET By Luis Quintanilla In...
[text] What a token is, and why models read tokens instead of words The to...
[text] Before you start. All examples use the Microsoft.ML.Tokenizers NuGe...
[text] Page 1 of 5
Section (page 2), 14 elements
[text] Tokens, Explained
[text] Sample book for document extraction
[heading] What is a token?
[text] A language model never sees your text directly. Before the model ru...
...How it works Code: DocumentExtractionClientCode: ExtractAsyncCode: ExtractionDocumentThat result is a tree. An Code: ExtractionDocumentCode: SectionsCode: ElementsCode: pageHeaderCode: SourcesA 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’s a reasonable first pass. When you need more structure, you can swap providers. Swap providers without changing your code The second sample, Code: 02-swap-providers.csCode: using DocumentExtractionClient? extractor = Providers.Create(provider, out string? skipped);
// From here down, nothing knows or cares which provider is running.
ExtractionDocument document = await Samples.ExtractFileAsync(extractor, path);
Samples.PrintOutline(document);Code: Providers.CreateCode: DefaultAzureCredentialCode: // Azure Content Understanding
DocumentExtractionClient contentUnderstanding = new ContentUnderstandingClient(new Uri(endpoint), new DefaultAzureCredential())
.AsDocumentExtractionClient(new() { AnalyzerId = "prebuilt-layout" });
// Azure AI Document Intelligence
DocumentExtractionClient docIntel = new DocumentIntelligenceClient(new Uri(endpoint), new DefaultAzureCredential())
.AsDocumentExtractionClient(new() { DefaultModel = "prebuilt-layout" });
// Mistral OCR in Microsoft Foundry
DocumentExtractionClient mistral = new MistralDocumentExtractionClient(
new MistralDocumentExtractionClientOptions
{
OcrEndpoint = new Uri(mistralUri),
DefaultModel = "mistral-ocr-4-0",
TokenScope = "https://cognitiveservices.azure.com/.default",
},
new DefaultAzureCredential());
// A vision language model, using any IChatClient. Here, Ollama.
IChatClient chat = new OllamaApiClient(new Uri("http://localhost:11434"), "qwen3.5:4b");
DocumentExtractionClient vision = new VisionLanguageModelDocumentExtractionClient(
chat, new() { UseStructuredOutput = true });The vision model provider takes any Code: IChatClientCode: Providers.csSamples 02 through 04 all read the same page, page 3 of Tokens, Explained ( Code: books/pages/tokens-explained-hero.pdf![]() Now run that page through a few providers: Code: dotnet run 02-swap-providers.cs -- pdfpig
dotnet run 02-swap-providers.cs -- cu
dotnet run 02-swap-providers.cs -- ollamaHere’s what came back: Code: PdfPig (local, text layer) took 0.4s
p1 [text] Tokens, Explained
p1 [text] Sample book for document extraction
p1 [heading] Tokenizers in .NET
p1 [text] The Microsoft.ML.Tokenizers library brings popular model tokenizers...
p1 [text] Tokenizer
p1 [text] Algorithm
p1 [text] .NET type
... 23 more lines, one per table cell ...
Azure Content Understanding took 10.2s
p1 [pageHeader] Tokens, Explained
p1 [pageHeader] Sample book for document extraction
p1 [heading] Tokenizers in .NET
p1 [text] The Microsoft. ML. Tokenizers library brings popular model tokenize...
p1 [table 6x5]
p1 [image]
...
p1 [pageNumber] Page 3 of 5
Vision language model (Ollama) took 23.6s
p1 [text] # Tokens, Explained Sample book for document extraction ## Tokeni...
p1 [table 6x5]
p1 [image]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. The third sample, Code: 03-compare.csCode: pdfpig 0.4s 1 headings, 34 text, 0 tables, 0 images
ollama 26.9s 0 headings, 1 text, 1 tables, 1 images
mistral 10.2s 0 headings, 2 text, 0 tables, 1 images
docintel 13.0s 2 headings, 9 text, 1 tables, 1 images
cu 10.4s 1 headings, 10 text, 1 tables, 1 imagesEven 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. Work with the results Walk the whole tree An Code: ExtractionDocumentCode: document.SectionsCode: ElementsCode: document.SectionsCode: Elements![]() To reach all of the content, use Code: EnumerateContent()Code: foreach (var table in document.EnumerateContent().OfType<ExtractionDocumentTableElement>())
{
Console.WriteLine($"Table: {table.Cells.RowCount} rows x {table.Cells.ColumnCount} columns");
}Read tables cell by cell 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.csCode: foreach (var cell in table.Cells)
{
if (cell is null) continue; // an empty position in the grid
string span = (cell.RowSpan, cell.ColumnSpan) switch
{
(1, 1) => "",
var (rows, cols) => $" spans {rows}x{cols}",
};
string role = cell.Role is null ? "" : $" ({cell.Role})";
Console.WriteLine($" [{cell.RowIndex},{cell.ColumnIndex}]{span}{role} {Samples.TextOf(cell.Content)}");
}Here’s the start of the table from Content Understanding ( Code: dotnet run 04-tables-and-sources.cs -- cuCode: Table: 6 rows x 5 columns
[0,0] spans 2x1 (columnHeader) Tokenizer
[0,1] spans 2x1 (columnHeader) Algorithm
[0,2] spans 2x1 (columnHeader) .NET type
[0,3] spans 1x2 (columnHeader) Where you'll see it
[1,3] (columnHeader) Model families
[1,4] (columnHeader) Typical use
[2,0] (content) Tiktoken
[2,1] (content) Optimized BPE
[2,2] (content) TiktokenTokenizer
...The vision model also got every cell’s text right, but it didn’t report the spans. Differences like that matter when you turn a table back into Markdown for a model to read. Know where things came from Each element has Code: SourcesCode: "Tokenizers in .NET"
page 1, Inch: (0.79,0.81) (2.95,0.81) (2.95,1.06) (0.79,1.06)That’s what you need to show a citation or highlight the paragraph an answer came from. Add logging and middleware Because every provider is a Code: DocumentExtractionClientCode: IChatClientCode: services.AddKeyedDocumentExtractionClient("documents", sp => new PdfPigDocumentExtractionClient())
.UseLogging()
.Use((inner, sp) => new ScannedPdfFallback(inner, sp.GetRequiredKeyedService<DocumentExtractionClient>("ocr")));To write your own middleware, derive from Code: DelegatingDocumentExtractionClientCode: ExtractAsyncCode: 05-pipeline.cs![]() Code: sealed class ScannedPdfFallback(DocumentExtractionClient inner, DocumentExtractionClient ocr) : DelegatingDocumentExtractionClient(inner)
{
public override async Task<ExtractionDocument> ExtractAsync(Stream stream, string identifier, string mediaType,
DocumentExtractionOptions? options = null, CancellationToken cancellationToken = default)
{
// Buffer the input so it can be read twice.
using var buffer = new MemoryStream();
await stream.CopyToAsync(buffer, cancellationToken);
buffer.Position = 0;
var document = await base.ExtractAsync(buffer, identifier, mediaType, options, cancellationToken);
int characters = document.EnumerateContent().Sum(e => e.Content is TextContent t ? t.Text.Trim().Length : 0);
if (characters > 100)
{
return document;
}
Console.WriteLine($" No text layer in {identifier} ({characters} characters). Falling back to OCR.");
buffer.Position = 0;
return await ocr.ExtractAsync(buffer, identifier, mediaType, options, cancellationToken);
}
}Here it is on the regular book and on its scanned copy, with Content Understanding as the OCR provider: Code: == tokens-explained.pdf
pdfpig read tokens-explained.pdf in 1.1s
5 sections, about 739 words
== tokens-explained-scanned.pdf
pdfpig read tokens-explained-scanned.pdf in 0.0s
No text layer in tokens-explained-scanned.pdf (0 characters). Falling back to OCR.
cu read tokens-explained-scanned.pdf in 13.1s
5 sections, about 767 wordsThe 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. Feed a data ingestion pipeline Last year we introduced data ingestion building blocks for .NET. Code: Microsoft.Extensions.DataIngestionThe sixth sample, Code: 06-ingest.cs![]() Code: // Any DocumentExtractionClient works here. This one uses Azure Content Understanding.
DocumentExtractionClient extractor = new ContentUnderstandingClient(new Uri(endpoint), new DefaultAzureCredential())
.AsDocumentExtractionClient(new() { AnalyzerId = "prebuilt-layout" });
IngestionDocumentReader reader = new ExtractionReader(extractor);
var tokenizer = TiktokenTokenizer.CreateForModel("gpt-4o");
IngestionChunker<string> chunker = new HeaderChunker(new IngestionChunkerOptions(tokenizer)
{
MaxTokensPerChunk = 256,
OverlapTokens = 32,
});
IEmbeddingGenerator<string, Embedding<float>> embeddings =
new OllamaApiClient(new Uri("http://localhost:11434"), "embeddinggemma");
using var store = new InMemoryVectorStore(new() { EmbeddingGenerator = embeddings });
using var writer = new VectorStoreWriter<string>(store, dimensionCount: 768);
using var pipeline = new IngestionPipeline<string>(reader, chunker, writer);
await foreach (var result in pipeline.ProcessAsync(books))
{
Console.WriteLine($"Ingested {Path.GetFileName(result.DocumentId)}: {(result.Succeeded ? "ok" : result.Exception?.Message)}");
}The pipeline reads documents through an Code: IngestionDocumentReaderCode: ExtractionReaderCode: ExtractAsyncCode: ExtractionDocumentCode: IngestionDocumentCode: sealed class ExtractionReader(DocumentExtractionClient client) : IngestionDocumentReader
{
public override async Task<IngestionDocument> ReadAsync(Stream source, string identifier, string mediaType,
CancellationToken cancellationToken = default)
{
var extracted = await client.ExtractAsync(source, identifier, mediaType, cancellationToken: cancellationToken);
var document = new IngestionDocument(identifier);
// Map each section's headings, paragraphs, and tables to ingestion elements.
...
return document;
}
}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’re combining the two in your own apps, you can copy the full reader from the sample. We intend to make composing document extraction and data ingestion simpler in upcoming releases. Run it with Content Understanding and ask a question: Code: dotnet run 06-ingest.cs -- cu "How do I count tokens before calling a model?"Code: Ingested agents-propose-tools-decide.pdf: ok
Ingested tensors-in-ten-pages.pdf: ok
Ingested tokens-explained.pdf: ok
Q: How do I count tokens before calling a model?
[0.60] tokens-explained.pdf | Plan your budget
Plan your budget Think of the context window as a budget you split between the parts of your
prompt. ... | Part of the request | Example tokens | | --- | --- | | System prompt | 1,000 | ...
[0.60] tokens-explained.pdf | Three things to remember
Three things to remember . A token is not a word. A token often includes its leading space...
[0.55] tokens-explained.pdf | Counting tokens and staying in budget
Counting tokens and staying in budget Every model has a context window, the maximum number...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. Next steps We’re excited to see what you build. Here’s where to go next:
We want to hear from you. Share your feedback, ideas, and suggestions, and let us know if something doesn’t work as expected. For Code: DocumentExtractionClientThe post Introducing DocumentExtractionClient (preview): Extract documents in .NET appeared first on .NET Blog. |