Classifying documents
Sorting incoming documents — is this an invoice, a contract, a resume, a bank statement? — is the first step in most document workflows. When you don’t have a fixed, pre-trained set of categories, you need zero-shot classification: you supply the candidate labels at call time and the model scores the document against exactly those.
This sample shows how to classify a document against your own set of candidate labels using Nutrient .NET SDK. By default, classification combines two signals — the document’s text and its visual layout — and fuses them into a single ranked prediction. Both run locally. An optional local decision-model backend replaces this two-branch pipeline.
Download sampleHow Nutrient helps
Nutrient .NET SDK runs the full zero-shot classification pipeline behind a single method call. The SDK handles:
- Rendering the page to a bitmap at the resolution the image model expects
- Scoring the document text against your candidate labels
- Scoring the page image against your candidate labels
- Fusing the two branches by the weights you choose into one ranked prediction
- Optionally replacing both branches with a local decision-model backend
- Serializing the result to JSON
The result is a predicted label plus the full ranked list of candidates with their probabilities — including the per-branch (text and image) contributions, so you can see why a label won.
Why two branches
Some document types are obvious from their text (a contract’s legal language), others from their layout (an invoice’s table of line items, an ID card’s photo block). Scoring both and fusing them is more robust than either alone. You control the balance with two weights — lean on text, lean on image, or weight them equally (the default).
Choosing where the text comes from
The text branch needs the document’s text. By default it reads the text with AdaptiveOcr (fast OCR); set the engine in Vision Settings to read it with another one (Icr for local models, VlmEnhancedIcr for VLM-enhanced). Multi-page documents are extracted in full. This is the zero-config path.
To classify text you already have (from your own pipeline, a database, or an email body), set the Text property directly — it’s scored as-is and extraction is skipped. To run image-only and skip the text extraction cost entirely, set the text weight to 0.
Classification requires the vision image classification feature in your license.
Multi-page documents
With the default two-branch classifier, every page of a multi-page document contributes. The image branch scores each page independently; the text branch reads text from every page. Pages with a confident, decisive result count for more, while pages that look like boilerplate are softly silenced, so the most distinctive page drives the prediction.
When the text is derived from the document, the text branch reads the full structure of every page — paragraphs, tables, key-value regions, and form fields — in reading order, not just running paragraphs. This matters for invoices, statements, and forms, where the identifying signal often lives in tabular numbers or filled fields rather than prose.
Complete implementation
Import the Nutrient namespace:
using Nutrient;Loading the document
Open the document with a using statement(opens in a new tab) so the handle is released when the block ends:
try{ using Document document = Document.Open("input_forms_detection.pdf");Configuring classification
Build a ClassificationRequest carrying your candidate labels (at least two are required), and tune the behavior on the document’s classification settings. This example derives the text from the document via the extraction pipeline and weights both branches equally:
DocumentClassificationSettings classification = document.Settings.DocumentClassificationSettings;
// Balance the text and image branches (defaults are 0.5 each). classification.TextWeight = 0.5f; classification.ImageWeight = 0.5f;
// Required: at least two candidate classes to score against (zero-shot). using ClassificationRequest request = new ClassificationRequest(); request.AddCandidateLabel("Invoice"); request.AddCandidateLabel("Contract"); request.AddCandidateLabel("Resume"); request.AddCandidateLabel("Bank statement"); request.AddCandidateLabel("ID card");By default the text is read from the document with AdaptiveOcr (fast OCR), or with the engine set in Vision Settings (Icr for local models, VlmEnhancedIcr for VLM-enhanced). To classify text you already have, set classification.Text = "INVOICE Bill to: ... Amount due: $1,240.00";. The supplied text is scored as-is and text extraction is skipped; the image branch still uses the opened document.
To run image-only (and skip the text extraction cost entirely), set the text weight to 0.
Describing each class
A bare label like “Invoice” works, but ambiguous or domain-specific classes match better when you describe them. Pass an optional description as the second argument with AddCandidateLabel() — the label is the short name shown in your results; the description is longer context used only to improve matching. Adding a label that’s already on the request replaces its entry, so you can start bare and upgrade to descriptions:
request.AddCandidateLabel("Invoice", "An itemized bill listing goods or services and the total amount due"); request.AddCandidateLabel("Contract", "A legal agreement between parties stating terms and obligations"); request.AddCandidateLabel("Resume", "A summary of a person's work experience, skills, and education"); request.AddCandidateLabel("Bank statement", "A periodic summary of account transactions and balances"); // "ID card" keeps its bare label — descriptions are optional per class.Labels and descriptions are plain strings with no delimiter rules — commas, pipes, and newlines are all fine. The result still reports only the label; the description never appears in the output.
Choosing the label language
Classification runs fully offline in any language. The text branch picks a multilingual model automatically when the document or the labels aren’t English, and a dedicated English model when both are English — there’s nothing to configure, the language is detected from the text and the labels. A document that mixes languages is treated as multilingual and uses the multilingual model too.
Predictions are sharpest when the document and its labels share a language, so:
- Prefer English labels. English documents with English labels take the dedicated English model (the strongest path), and English labels stay reliable even on non-English documents.
- When the source text isn’t English, give the labels in the document’s language or fall back to English labels.
- An English document with non-English labels is the lowest-confidence pairing — prefer one of the two options above.
A language mismatch — say an English document with non-English labels — still classifies correctly (the multilingual model is selected automatically), but with lower confidence. Keeping the document and labels in the same language, or using English labels for non-English documents, keeps the prediction sharp.
Opting in to the decision-model backend
Instead of the two-branch classifier, you can classify with a local decision model. Run the packaged sample with dotnet run -- --decision-model to opt in; without that argument, the sample keeps the two-branch classifier:
if (args.Contains("--decision-model")) { classification.EnableDocumentDecisionClassifier = true; }This is a replacement backend, not a third signal combined with the text and image branches. It uses the same candidate-label request and reads rendered page images together with their OCR text, starting from the first page. It considers at most the first 30 pages and includes only as many as fit its token budget. It ignores Text, TextWeight, ImageWeight, and AutoWeight. MultiLabel still selects independent per-label confidence or single-label classification; single-label mode supports at most 26 candidate labels. The model files are resolved from the Nutrient CDN, so prepare the resource cache before running offline. The decision model is slower than the default classifier, so enable it explicitly only for workflows that need it.
Classifying the document
Create a vision instance bound to the document with Vision.Set(document), then call Classify(request):
Vision vision = Vision.Set(document); string resultJson = vision.Classify(request);Write the JSON result to a file for downstream routing:
File.WriteAllText("output.json", resultJson);}catch (NutrientException e){ Console.Error.WriteLine($"Error: {e.Message}"); Environment.Exit(1);}Understanding the output
Classify(request) returns JSON with a top-level classification object:
predictedLabel— The highest-ranked label.confidence— The fused probability of the predicted label (0.0 to 1.0).predictions— Every candidate, ranked by fused probability descending. Each entry carries:label— The candidate label.probability— The fused probability.textProbability— The text branch’s probability for this label (0 when the text branch didn’t run).imageProbability— The image branch’s probability for this label (0 when the image branch didn’t run).
Because the per-branch contributions are included, you can tell whether a prediction was driven by the text, the layout, or both — useful for debugging and for tuning the weights.
With the decision-model backend, the result still contains predictedLabel, confidence, and ranked predictions, but the per-branch textProbability and imageProbability values are zero. The pagesClassified and pageCount fields report how many pages the model read out of the document’s total, so don’t assume this backend reads every page.
Text-only classification
When you already have the text — an email body, a database field, your own extraction pipeline — and no file to open, classify it directly with the static Vision.ClassifyText(request, text). It takes the same ClassificationRequest as Classify() — build it with the same AddCandidateLabel methods as above. No document is opened, nothing is rendered, and only the text branch runs; it returns the same JSON shape as Classify().
When you already have a document open and only want to skip the extraction cost, the equivalent is to set the Text property directly and turn off the image branch by setting ImageWeight to 0 (text branch only). To classify on layout alone instead, set TextWeight to 0. Either way the disabled branch is skipped and the fused probability equals the remaining branch’s probability.
Error handling
Vision API throws a NutrientException when classification fails.
Common failure scenarios include:
- The document can’t be read due to path or permission issues
- The page produces no renderable image
- A classification model is missing or inaccessible, or the feature isn’t licensed
- Fewer than two candidate labels were supplied (classification needs an output space to choose from)
In production code:
- Catch
NutrientException. - Return a clear error message.
- Log failure details for debugging.
Conclusion
The workflow for zero-shot document classification is:
- Open the source document with a
usingstatement for automatic resource cleanup. - Build a
ClassificationRequestwith at least two candidate labels (optionally with descriptions), and tune the text/image weights (or supply the text directly) on the classification settings. - Optionally, enable
EnableDocumentDecisionClassifierto classify with the local decision-model backend. - Create a vision instance with
Vision.Set(). - Call
Classify(request)to score the document and export the ranked result as JSON. - Write the JSON to a file for routing or downstream processing.
- Handle
NutrientExceptionfailures for robust error recovery.
To find where each document starts in a merged PDF, refer to the split documents guide. To answer yes/no or multiple-choice questions about extracted data, refer to the Decision API guide.
For related image extraction workflows, refer to the .NET SDK guides.
Download this ready-to-use sample package to explore document classification.