Extractor Plugin
The Extractor plugin adds a full‑text extraction service to a Doconut.NET8 application. It reads supported documents (PDF, .docx, XPS, spreadsheets, …) and returns an ExtractionResult containing ordered ExtractedBlocks, document metadata, hidden content, and any extraction warnings. The result can be emitted as deterministic JSON (the source of truth) or as Markdown (a readable view). When the optional OCR engine package is installed, pages without a native text layer are processed according to ExtractOptions.Ocr (Auto | Off).
| Surface | How to use |
|---|---|
DocumentExtractor (DI) | Inject the service and call ExtractAsync to obtain an ExtractionResult. |
HTTP endpoints (?extract=) | POST ?extract=open – upload a file and receive a token.POST ?extract=run – run extraction for the uploaded token.GET ?extract=download&token=<token> – download the JSON or Markdown result. |
| Extractor widget | Enable with options.AddExtractorWidget(widget => { … }). The widget respects ExtractorWidgetOptions.MaxUploadMb and provides the same three ?extract= endpoints behind a ready‑made UI. |
Install the package
Install the Extractor plugin at the release this documentation describes:
dotnet add package Doconut.NET8.Extractor --version 26.11.0Keep Doconut.NET8.Extractor at the same version as Doconut.NET8.
The plugin's license file, Doconut.Viewer.Extractor.lic, goes in the same folder as Doconut.Viewer.lic; it is read together with the viewer license.
Platforms. The plugin runs wherever Doconut.NET8 runs: Windows, and glibc-based Linux on x64 (not Alpine or other musl-based distributions). On Linux, install the font configuration library before the first document opens:
apt-get update && apt-get install -y libfontconfig1On RHEL, Fedora and similar distributions the package is fontconfig. Without it, opening a document fails with The system library libfontconfig1 is missing. Install it (Debian/Ubuntu: apt-get install -y libfontconfig1) and see the Linux section of the Doconut documentation.
Register the plugin
Like every Doconut plugin, Extractor registers with AddPlugin inside AddDoconut:
builder.Services.AddDoconut(options =>
{
options.LicensePath = "Doconut.Viewer.lic";
options.AddPlugin<Doconut.Plugins.Extractor.ExtractorPlugin>();
});Licensing & watermark
The Extractor plugin needs a license that grants the Extractor capability. Without one, AddDoconut() throws an InvalidOperationException at startup, before the app serves a request:
The Extractor plugin is registered via AddPlugin but no active license grants Extractor. Remove the AddPlugin<...>() call or install a license that includes Extractor (a temporary license includes every capability).It throws for no license, a legacy TRIAL file, a license without Extractor, and a paid license used outside its version window. Temporary Demo/NFR licenses are accepted. See License Setup for how licenses are loaded.
| License state | Startup | Output |
|---|---|---|
Paid license granting Extractor, within its version window | Starts | Without the evaluation watermark |
| Temporary Demo/NFR license | Starts | With the evaluation watermark |
No license, a legacy TRIAL file, a license without Extractor, or a paid license outside its version window | AddDoconut() throws | — |
Use from C#
Injecting the extractor
Resolve DocumentExtractor from DI; never new it.
using Doconut;
using Doconut.Core.Models.Extraction;
public sealed class MyService
{
private readonly DocumentExtractor _extractor;
public MyService(DocumentExtractor extractor) => _extractor = extractor;
}Basic extraction
var extractor = app.Services.GetRequiredService<DocumentExtractor>();
ExtractionResult result = await extractor.ExtractAsync("contract.docx", ct: ct);Walking the blocks
foreach (ExtractedBlock block in result.Blocks)
{
Console.WriteLine($"{block.Id} {block.Type} page {block.Page}: {block.Text}");
}Controlling extraction with ExtractOptions
var extractor = app.Services.GetRequiredService<DocumentExtractor>();
var options = new ExtractOptions
{
MaxPages = 200,
Ocr = OcrMode.Auto,
CheckVisibility = true,
Password = "secret"
};
ExtractionResult result = await extractor.ExtractAsync("secret.pdf", options, ct);Handling OCR warnings
foreach (ExtractionWarning warning in result.Warnings)
{
if (warning.Code == ExtractionWarningCodes.OcrUnavailable)
{
Console.WriteLine("OCR not available for pages: " + string.Join(", ", warning.Pages));
}
}Reviewing low‑confidence OCR blocks
var toReview = result.Blocks
.Where(b => b.Source == BlockSource.Ocr && b.Confidence is < 0.8)
.ToList();
foreach (var block in toReview)
{
Console.WriteLine($"Low‑confidence OCR block {block.Id} (page {block.Page}): {block.Text}");
}Linking a block to the viewer
var extractor = app.Services.GetRequiredService<DocumentExtractor>();
ExtractionResult result = await extractor.ExtractAsync("contract.pdf", ct: ct);
// Declare the block id you want to locate; replace with a real id at runtime.
string quotedBlockId = "p1-b3";
ExtractedBlock? block = result.Blocks.FirstOrDefault(b => b.Id == quotedBlockId);
if (block != null)
{
// Pass `block` to the viewer on the client side, e.g. objViewer.ShowBlock(block).
}Asynchronous stream extraction
var extractor = app.Services.GetRequiredService<DocumentExtractor>();
// `stream` is a placeholder for any `Stream` you already have (e.g. a file upload).
ExtractionResult result = await extractor.ExtractAsync(
document: stream,
extension: ".pdf",
options: null,
ct: ct);Guarantees
Deterministic output
- The same input file always produces the same JSON byte‑for‑byte via
ExtractionResult.ToJson(). - Property order is fixed, culture‑invariant, numbers are rounded to two decimals, line endings are LF, and any dates come from the document itself – never from the extraction time.
- This guarantee holds for a given SDK version, and for pages read by OCR it also holds for a given OCR engine version.
Offline processing
- Extraction runs entirely on the server; no network calls or AI models are involved.
- The document never leaves your host.
Hidden content stays out
- Text that is hidden, invisible, a comment, a tracked change, a hidden sheet/row/column, a hidden slide, or speaker notes is never mixed into
ExtractionResult.Blocks. - Such content is reported only in
ExtractionResult.HiddenasHiddenContent.
Redaction‑safe
- When the Redactor plugin removes (“burns out”) text, that text is no longer present in the source file, so it cannot appear in any extracted block.
Never truncated
- If a document exceeds
ExtractOptions.MaxPages(default 500), extraction fails with a clear error instead of returning a partial result.
These guarantees apply as long as the Extractor plugin is registered (see Register the plugin) and the required license is present (see Licensing & watermark).
Output: JSON and Markdown
JSON
ExtractionResult.ToJson() returns the deterministic source of truth. The output uses LF line endings and omits any property that does not apply (no nulls).
{
"schemaVersion":1,
"source":{"fileName":"contract.pdf","format":"pdf","pageCount":12,"sha256":"…"},
"metadata":{"title":"Service agreement"},
"watermarked":false,
"warnings":[{"code":"ocrUnavailable","pages":[4,5]}],
"blocks":[
{"id":"p1-b1","type":"heading","level":1,"order":1,"page":1,"bounds":{"x":72,"y":90.5,"w":300.2,"h":18,"pageW":612,"pageH":792},"source":"native","text":"Service agreement"},
{"id":"s1-b1","type":"table","order":2,"page":2,"sheet":"Sales","range":"A1:D20","source":"native","rows":[["Name","Total"],["Ana","42"]]},
{"id":"p4-b1","type":"paragraph","order":14,"page":4,"source":"ocr","confidence":0.93,"text":"…"}
]
}| JSON field | Model property |
|---|---|
schemaVersion | ExtractionResult.SchemaVersion |
source | ExtractionResult.Source |
metadata | ExtractionResult.Metadata |
watermarked | ExtractionResult.Watermarked |
warnings | ExtractionResult.Warnings |
blocks | ExtractionResult.Blocks |
id | ExtractedBlock.Id |
type | ExtractedBlock.Type |
text | ExtractedBlock.Text |
Markdown
ExtractionResult.ToMarkdown() creates a human‑readable view. It begins with a YAML front‑matter block mirroring source, metadata and watermarked. Each block is preceded by an invisible anchor (<!-- ref:<id> -->) for viewer linking.
---
source:
fileName: "contract.pdf"
format: "pdf"
pageCount: 12
sha256: "…"
metadata:
title: "Service agreement"
watermarked: false
---
<!-- page:1 -->
<!-- ref:p1-b1 -->
# Service agreement
<!-- ref:p1-b2 -->
The parties agree…
<!-- ref:s1-b1 -->
| Name | Total |
|------|-------|
| Ana | 42 |
<!-- ref:p4-b1 -->
> … (OCR confidence 0.93)| Block type | Markdown |
|---|---|
| heading | #… (level determines number of #) |
| paragraph | plain text |
| listItem | - or 1. (ordered) |
| table | GFM table |
| image |  |
| attachment | - Attachment: <name> |
| watermark | empty anchor (<!-- ref:<id> -->) |
OCR
Enabling OCR
The Extractor works without the OCR engine: pages that have no text layer (scans, images) then give no blocks, and their numbers come back in the ocrUnavailable warning. To read those pages, install the OCR engine package:
dotnet add package Doconut.NET8.Engines.Ocr --version 26.11.0The package has no API and no license of its own, and there is nothing to register in code: installing it is the opt-in. It depends on the matching version of Doconut.NET8, which NuGet installs automatically. The engine turns on only when your license includes Search or Extractor; otherwise it stays off and the application logs one line at startup saying so. An expired temporary license also turns it off. It runs fully offline, on Windows (x64, x86) and Linux (x64). The same engine also makes scanned documents searchable in the viewer when the license includes Search.
OCR modes
ExtractOptions.Ocr selects the policy (default OcrMode.Auto). - OcrMode.Auto: reads only pages without a native text layer. - OcrMode.Off: never runs OCR; such pages produce no blocks.
Platform requirements
On Windows the engine needs the Microsoft Visual C++ 2015‑2022 Redistributable (x64; for a 32-bit process, the x86 one). Without it OCR stays off, the application logs one warning starting with Doconut OCR is off: that names the missing runtime, and everything else (viewing, text search, extraction) works as usual. Install it and restart the application.
Extraction warnings related to OCR
ExtractionWarningCodes.OcrUnavailable – no OCR engine or unsupported platform. ExtractionWarningCodes.PageFailed – a page could not be read; extraction continues. ExtractionWarningCodes.VisibilityUnchecked – page could not be rendered for visibility check; its text is kept.
Sample: extracting a scanned PDF
var extractor = app.Services.GetRequiredService<DocumentExtractor>();
ExtractionResult result = await extractor.ExtractAsync(
"scanned.pdf",
new ExtractOptions { Ocr = OcrMode.Auto },
ct);
foreach (ExtractionWarning w in result.Warnings)
if (w.Code == ExtractionWarningCodes.OcrUnavailable)
Console.WriteLine("Not read, no OCR engine: " + string.Join(", ", w.Pages));
var toReview = result.Blocks
.Where(b => b.Source == BlockSource.Ocr && b.Confidence is < 0.8)
.ToList();
Console.WriteLine($"Low‑confidence OCR blocks: {toReview.Count}");Low‑confidence blocks have ExtractedBlock.Confidence (0‑1) or null. Link their Id to the viewer with objViewer.ShowBlock (see “ShowBlock in the viewer”).
ShowBlock in the viewer
ShowBlock in the viewer
ShowBlock lives in docViewer.js – it is not part of the Extractor widget, so you can call it from any UI you build on top of the Doconut viewer.
// `block` can be an `ExtractedBlock` you obtained from the C# extraction result
// (see “Linking a block to the viewer” in the *Use from C#* section), or a plain
// object that contains the page number and the bounds in PDF points.
objViewer.ShowBlock(block); // → true if the viewer can navigate to the page
objViewer.ClearBlock(); // removes the highlight boxWhat it does
- Navigates to
block.page. - Draws a box (
.docBlock) using the coordinates inblock.bounds(x,y,w,h,pageW,pageH). - If
boundsis missing or invalid, only the page navigation occurs. - A subsequent
ShowBlockcall replaces the previous highlight. - The box is re‑drawn automatically on scroll, zoom, and when the page is rotated or flipped.
- The call returns
falsewhen there is no document open (or the requested page does not exist).
It returnstruewhile the viewer is still loading the document; if the page later turns out to be missing, nothing is drawn.
Limitation
The viewer learns a page’s rotation only from its own Rotate/Flip calls.
If a viewer is re‑attached to a session that already has rotated pages (e.g., after a browser refresh that keeps the same token), the highlight may be misplaced until the next rotation operation.
Use this API to let users jump from a piece of extracted text back to the exact location in the PDF/XPS document, without affecting any active search state.
Drop-in widget
Enable the endpoints
The Extractor widget’s ?extract= endpoints are off by default. Turn them on when you register the plugin:
// Program.cs – enable the widget
builder.Services.AddDoconut(options =>
{
// see “Licensing & watermark” for licence setup
options.AddPlugin<Doconut.Plugins.Extractor.ExtractorPlugin>();
options.AddExtractorWidget(widget =>
{
// client‑side limit; keep it in sync with the server
widget.MaxUploadMb = 25;
});
});If AddExtractorWidget() is omitted, every ?extract= request returns 404 and the widget shows Extraction is not enabled on this server..
Embed the widget
Add a static HTML file (e.g. wwwroot/extract.html) that loads the script and creates a mount point:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Extract a document</title>
</head>
<body>
<div id="extractor"></div>
<script src="/doconut-res/js/doconutExtractor.js"></script>
<script>
// mount the widget
Doconut.extractor('#extractor', { basePath: '/doconut' });
</script>
</body>
</html>UseDoconutResources() (see the “Register the plugin” section) serves the script at /doconut-res/js/doconutExtractor.js. The widget works without a viewer; pairing with a viewer is optional.
Initialise the widget with options
// JavaScript – customise the widget
var extractor = Doconut.extractor('#extractor', {
basePath: '/doconut', // where the ?extract= endpoints live
maxUploadMb: 25, // client‑side size check (must match server)
ocr: 'auto', // 'off' disables OCR, any other value => 'auto'
viewer: objViewer, // optional docViewer instance (see “ShowBlock in the viewer”)
licenseUrl: '/pricing', // link for the evaluation note
labels: {
dropPrompt: 'Drop a document here',
chooseFile: 'or pick a file',
downloadJson: 'Download JSON',
downloadMarkdown: 'Download Markdown'
},
onReady: () => console.log('widget ready'),
onSourceLoaded: info => console.log('uploaded', info),
onExtracted: result => console.log('extracted', result),
onBlockClick: block => console.log('block clicked', block.id),
onDownload: dl => console.log('downloaded', dl.downloadName),
onError: err => console.warn('error', err.message)
});The call throws if the selector does not match an element. It returns a handle that lets you control the widget programmatically.
Options
| Option | Type | Default | Description |
|---|---|---|---|
basePath | string | '/doconut' | URL prefix for the ?extract= endpoints. |
maxUploadMb | number | 25 | Client‑side file‑size limit; must match ExtractorWidgetOptions.MaxUploadMb. |
ocr | 'auto' | 'off' | 'auto' | 'off' skips OCR; any other value selects the default auto mode. |
viewer | object | null | A docViewer instance to pair with (see “ShowBlock in the viewer”). |
licenseUrl | string | null | Turns the evaluation note into a hyperlink. |
labels | object | {} | Overrides any of the widget’s UI strings (see “Localization”). |
onReady, onSourceLoaded, onExtracted, onBlockClick, onDownload, onError | function | — | Callback hooks (see “Callbacks”). |
Callbacks
A callback that throws is caught and logged; it never aborts the widget.
| Callback | When it fires | Argument |
|---|---|---|
onReady | After the widget is mounted (once). | — |
onSourceLoaded | The file has been uploaded and a token obtained. | { token, name, pages, ext } |
onExtracted | Extraction has completed successfully. | The full ExtractionResult object (same shape as the JSON download). |
onBlockClick | The user clicks a block in the list. | The ExtractedBlock that was clicked. |
onDownload | A download button finishes. | { downloadName } |
onError | Upload, extraction, or download fails, or the file exceeds the size limit. | { message } |
Imperative handle
| Method | Effect |
|---|---|
result() | Returns the last ExtractionResult (identical to the JSON download) or null if none. |
reset() | Returns to the drop zone, clears any viewer highlight, and discards the current result. |
loadFile(file) | Starts the flow with a File object. No‑op unless the widget is showing the drop screen. |
destroy() | Removes all listeners, empties the mount element, and disables further calls. |
// Example: reset the widget from a button
document.getElementById('resetBtn').addEventListener('click', () => extractor.reset());Localization (labels)
Every visible string can be replaced via the labels option. Keys not supplied keep their English defaults.
Doconut.extractor('#extractor', {
labels: {
dropPrompt: 'Suelta un documento aquí',
chooseFile: 'o elige un archivo',
downloadJson: 'Descargar JSON',
downloadMarkdown: 'Descargar Markdown',
// …other keys as needed
}
});Label keys (grouped for reference):
- Drop screen:
dropAriaLabel,dropPrompt,dropHint,chooseFile - Progress:
uploading,extracting - Summary:
summary,page,pages,block,blocks - Notes:
evaluationNote,evaluationLinkPrefix,evaluationLink,hiddenSummary,warningOcrUnavailable,warningPageFailed,warningVisibilityUnchecked,warningOther - Hidden kinds:
hiddenText,invisibleText,hiddenSheet,hiddenRow,hiddenColumn,hiddenSlide,speakerNotes,comment,trackedChange - List:
filterLabel,filterPlaceholder,noMatches,noBlocks,showMore,blockPage,ocrTag - Block types:
typeHeading,typeParagraph,typeListItem,typeTable,typeImage,typePageText,typeEmailHeader,typeAttachment - Actions:
downloadJson,downloadMarkdown,runAnother,retry - Errors:
sizeLimit,serverError,badResponse,networkError,downloadFailed,genericError - Screen readers:
annReady,annWorking,annDone,annFiltered,annError
Server‑side error messages are shown verbatim (e.g. "File is too large.").
Theming (CSS custom properties)
The widget adds the class dxw to its mount element. Override its colours, radius and font via CSS custom properties:
#extractor.dxw {
--dxw-accent: #0f766e; /* links, buttons, highlights */
--dxw-bg: #ffffff; /* background */
--dxw-fg: #1a202c; /* primary text */
--dxw-muted: #718096; /* secondary text */
--dxw-border: #cbd5e0; /* borders */
--dxw-danger: #c53030; /* error states */
--dxw-warn-bg: #fffbeb; /* warning background */
--dxw-radius: 12px; /* corner radius */
--dxw-font: system-ui, sans-serif; /* font stack */
}| Property | Default |
|---|---|
--dxw-accent | #2b6cb0 |
--dxw-bg | #ffffff |
--dxw-fg | #1a202c |
--dxw-muted | #718096 |
--dxw-border | #cbd5e0 |
--dxw-danger | #c53030 |
--dxw-warn-bg | #fffbeb |
--dxw-radius | 8px |
--dxw-font | system UI font stack |
All widget styles are scoped under .dxw, so they do not affect other page elements. Adjust the variables to match your site’s visual identity.
Build your own frontend
Overview
The Extractor plugin exposes three HTTP routes (under the path where UseDoconut() is mounted, e.g. /doconut) that you can call from any front‑end.
| Route | Purpose |
|---|---|
POST ?extract=open | Upload a document and receive a token (also usable as a viewer token). |
POST ?extract=run | Ask the server to extract the uploaded file. |
GET ?extract=download&token={token} | Download the JSON or Markdown result. |
All error responses are JSON { "error": "…" } unless the table lists “status only”. Protect these endpoints with your own authentication – anyone who can reach the path can upload files.
1. Upload a file (open)
<form id="uploadForm">
<input type="file" id="fileInput" name="file" />
<button type="submit">Upload</button>
</form>
<script type="text/javascript">
document.getElementById('uploadForm').addEventListener('submit', async e => {
e.preventDefault();
const file = document.getElementById('fileInput').files[0];
const fd = new FormData();
fd.append('file', file, file.name);
const resp = await fetch('/doconut?extract=open', { method: 'POST', body: fd });
if (!resp.ok) {
const err = await resp.json();
alert('Upload failed: ' + err.error);
return;
}
const { token, name, pages, ext } = await resp.json();
sessionStorage.setItem('extractToken', token);
console.log(`Uploaded ${name} (${pages} pages, ${ext})`);
});
</script>Success → 200 with JSON { token, name, pages, ext }.
2. Run the extraction (run)
<button id="runBtn">Extract</button>
<script type="text/javascript">
document.getElementById('runBtn').addEventListener('click', async () => {
const token = sessionStorage.getItem('extractToken');
if (!token) { alert('Upload a file first.'); return; }
const resp = await fetch('/doconut?extract=run', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token, ocr: 'auto' }) // use "off" to skip OCR
});
if (!resp.ok) {
const err = await resp.json();
alert('Extraction failed: ' + err.error);
return;
}
const { result, downloads } = await resp.json();
sessionStorage.setItem('jsonToken', downloads.json);
sessionStorage.setItem('mdToken', downloads.markdown);
console.log('Schema version:', result.schemaVersion);
});
</script>Success → 200 with JSON containing watermarked, downloads.{json,markdown}, and the full result object.
3. Download the result (download)
<button id="dlJson">Download JSON</button>
<button id="dlMd">Download Markdown</button>
<script type="text/javascript">
function download(token) {
const url = `/doconut?extract=download&token=${encodeURIComponent(token)}`;
window.location.href = url; // browser handles the attachment
}
document.getElementById('dlJson').addEventListener('click', () => {
const t = sessionStorage.getItem('jsonToken');
if (!t) { alert('Run extraction first.'); return; }
download(t);
});
document.getElementById('dlMd').addEventListener('click', () => {
const t = sessionStorage.getItem('mdToken');
if (!t) { alert('Run extraction first.'); return; }
download(t);
});
</script>The response includes the appropriate Content‑Type (application/json or text/markdown) and a Content‑Disposition: attachment header.
4. Linking a block to the viewer
After you have the ExtractionResult on the server, each ExtractedBlock carries a stable Id. Send the desired block IDs to the front‑end and call objViewer.ShowBlock({ Id: blockId }) there. The mechanics are described in the ShowBlock in the viewer section.
In production
Hosting considerations
Running the Extractor plugin in production means you have to think about the ASP .NET Core host, the request limits that ASP .NET Core and Kestrel impose, and the way Doconut stores temporary upload data.
var builder = WebApplication.CreateBuilder(args);
// 1️⃣ Distributed cache – required for the session that Doconut uses for document security.
builder.Services.AddDistributedMemoryCache(); // replace with Redis or SQL cache in a farm
builder.Services.AddSession(); // the session middleware must run before Doconut
// 2️⃣ Increase the request‑body limit if you raise the widget’s `maxUploadMb`.
// Kestrel’s default is ~28 MiB, so a 50 MiB upload needs an explicit increase.
builder.WebHost.ConfigureKestrel(k =>
{
k.Limits.MaxRequestBodySize = 60L * 1024 * 1024; // 60 MiB
});
// 3️⃣ Add Doconut with the Extractor plugin and the widget.
// The licence file is placed outside *wwwroot* so it isn’t served publicly.
builder.Services.AddDoconut(options =>
{
options.LicensePath = "Doconut.Viewer.lic"; // see “Licensing & watermark”
options.UnsafeMode = false; // keep the ASP .NET Session check (default)
options.AddPlugin<ExtractorPlugin>();
options.AddExtractorWidget(widget =>
{
widget.MaxUploadMb = 50; // match the Kestrel limit above
});
});
var app = builder.Build();
// The session middleware must be added **before** the Doconut middleware.
app.UseStaticFiles(); // serves the widget’s HTML page
app.UseSession(); // required for token‑based security
app.UseDoconutResources(); // serves /doconut-res/* assets
app.Map("/doconut", branch => branch.UseDoconut());
app.Run();Key points
- Session – Doconut’s document‑security layer stores the upload token in the ASP .NET session. If the session middleware is missing, every download returns 500 with the plain‑text body
ASP.NET Session is required for Doconut document security. - Request size – The widget returns 413 when the upload exceeds
ExtractorWidgetOptions.MaxUploadMb. The same limit is enforced by Kestrel, so raiseMaxRequestBodySizeaccordingly. - Upload lifetime – An upload and its extraction result are kept for 30 minutes. After that the
runendpoint answers 404 and thedownloadendpoint 403. Tokens are the only way to retrieve a result, so never log them or expose them in shared URLs.
Scaling out (multiple nodes)
By default the upload store lives in the memory of the node that handled the open request. In a single‑instance deployment this is sufficient. In a web‑farm or behind a load balancer you must provide a shared store so that a subsequent run or download request can be served by any node.
Deploy a shared, encrypted store (e.g., a network share or a distributed cache) and configure Doconut to use it. The exact registration call is documented in the “Web farm” guidance of the Extractor plugin; the important thing is that the store is encrypted (AES‑256) and bound to the token, preventing one client from reading another’s upload.
License deployment
The licence can be supplied in three ways; pick the one that fits your CI/CD pipeline:
| Method | How to set it |
|---|---|
| File | Place Doconut.Viewer.lic (and, if you have a paid licence, Doconut.Viewer.Extractor.lic) in a folder that the process can read, then set options.LicensePath = "full\\path\\to\\Doconut.Viewer.lic"; in the registration code. |
| Content string | Load the XML licence into a string and assign options.LicenseContent = licenceXml;. |
| Stream | Open a FileStream (or a stream from a secret manager) and assign options.LicenseStream = stream;. |
Only one of the three is used; the order of precedence is Stream → Content → Path. Changing the licence file requires an application restart because the licence is read once at startup.
Monitoring and diagnostics
- Startup log – After
AddDoconutruns you will see eitherDoconut Extraction: licensed — output is clean.orDoconut Extraction: temporary licence — extracted output is watermarked. - Memory pressure – Each upload is kept in memory (or the shared store) until it expires. Monitor the process’s working‑set if you expect many concurrent uploads.
- Health checks – The middleware does not expose its own health endpoint, but you can probe the
/doconutpath with a simpleGETrequest; a 200 response means the middleware is loaded.
API reference
BlockSource
Where a block's text came from.
Native
OcrExtractedBlockType
What a block is.
Attachment
EmailHeader
Heading
Image
ListItem
PageText
Paragraph
Table
WatermarkExtractionResult
A document's content and metadata. JSON (ToJson) is the source of truth; Markdown is a view of it.
int CurrentSchemaVersion
ExtractionResult()
bool Equals(ExtractionResult other)
bool Equals(object obj)
int GetHashCode()
string ToJson()
string ToMarkdown()
string ToString()
bool op_Equality(ExtractionResult left, ExtractionResult right)
bool op_Inequality(ExtractionResult left, ExtractionResult right)
IReadOnlyList<ExtractedBlock> Blocks { get; set; }
IReadOnlyList<HiddenContent> Hidden { get; set; }
IReadOnlyList<KeyValuePair<string, string>> Metadata { get; set; }
int SchemaVersion { get; set; }
ExtractedSource Source { get; set; }
IReadOnlyList<ExtractionWarning> Warnings { get; set; }
bool Watermarked { get; set; }ToJson: The result as JSON (the source of truth): deterministic, LF line endings.ToMarkdown: The result as Markdown, a view of ToJson with a reference anchor before each block.Metadata: Document properties, sorted by key (ordinal) so the output is deterministic.Watermarked: True when the output carries the evaluation watermark (temporary licence or no paid viewer licence).
ExtractionWarningCodes
Warning codes.
string OcrUnavailable
string PageFailed
string VisibilityUncheckedOcrUnavailable: Pages without text could not be read: no OCR engine installed, not licensed, or unsupported platform.PageFailed: A page could not be read; the rest of the document was extracted.VisibilityUnchecked: The page could not be rendered, so its text was not checked against the rendered page: text in the colour of what is under it, or covered by something painted over it, may be in the blocks. Text marked invisible, outside the page or too small to read is still left out.
OcrMode
Whether pages without a text layer are read by OCR.
Auto
OffAuto: OCR only the pages that have no text layer (scans). The default.Off: Never OCR; pages without text produce no blocks.
BlockBounds
A box on a page in PDF points, origin top-left, with the page size — the convention of the viewer's search highlights.
BlockBounds(double X, double Y, double W, double H, double PageW, double PageH)
void Deconstruct(ref double X, ref double Y, ref double W, ref double H, ref double PageW, ref double PageH)
bool Equals(BlockBounds other)
bool Equals(object obj)
int GetHashCode()
string ToString()
bool op_Equality(BlockBounds left, BlockBounds right)
bool op_Inequality(BlockBounds left, BlockBounds right)
double H { get; set; }
double PageH { get; set; }
double PageW { get; set; }
double W { get; set; }
double X { get; set; }
double Y { get; set; }ExtractOptions
Options for DocumentExtractor.ExtractAsync.
ExtractOptions()
bool Equals(ExtractOptions other)
bool Equals(object obj)
int GetHashCode()
string ToString()
bool op_Equality(ExtractOptions left, ExtractOptions right)
bool op_Inequality(ExtractOptions left, ExtractOptions right)
bool CheckVisibility { get; set; }
string FileName { get; set; }
bool IncludeHidden { get; set; }
int MaxCells { get; set; }
int MaxPages { get; set; }
OcrMode Ocr { get; set; }
string Password { get; set; }CheckVisibility: PDF and XPS: compare text against the rendered page, to hold back text that does not show (same colour as what is under it, or painted over). Default on. It renders every page, which costs about 100 ms per page: turn it off only for documents you trust. The checks that need no render always run, in every format.FileName: File name reported in FileName; defaults to "document" + extension.IncludeHidden: Reserved. Hidden content is always reported in Hidden and never extracted.MaxCells: Spreadsheets: maximum number of cells in the used ranges of the visible sheets, empty ones included (the used range of a sheet runs from its first to its last cell with a value). A larger workbook fails instead of being truncated. Default 1,000,000.MaxPages: Maximum number of pages; a longer document fails instead of being truncated. Default 500.Ocr: OCR policy for pages without text. Default Auto.Password: Password of a protected document.
ExtractedBlock
One unit of content in reading order.
ExtractedBlock()
bool Equals(ExtractedBlock other)
bool Equals(object obj)
int GetHashCode()
string ToString()
bool op_Equality(ExtractedBlock left, ExtractedBlock right)
bool op_Inequality(ExtractedBlock left, ExtractedBlock right)
BlockBounds Bounds { get; set; }
double? Confidence { get; set; }
string Id { get; set; }
int? Level { get; set; }
string Name { get; set; }
int Order { get; set; }
bool? Ordered { get; set; }
int? Page { get; set; }
string Range { get; set; }
IReadOnlyList<IReadOnlyList<string>> Rows { get; set; }
string Sheet { get; set; }
int? SheetIndex { get; set; }
BlockSource Source { get; set; }
string Text { get; set; }
ExtractedBlockType Type { get; set; }Confidence: OCR confidence 0..1 when the engine reports a real value; otherwise null (never invented).Id: Stable positional id: p{page}-b{n}, s{sheet}-b{n}, or p{page}-wm for a watermark block.Level: Heading or list level (1-based).Name: Header field name (emailHeader) or file name (attachment).Order: 1-based reading order over the content blocks; 0 for watermark blocks.Ordered: For a list item: numbered (true) or bulleted (false).Rows: Table cells, row by row.SheetIndex: 1-based position of Sheet in the workbook (hidden sheets counted). Not written to JSON: the block id (s{SheetIndex}-b{n}) carries it.
ExtractedSource
The document the result came from.
ExtractedSource(string FileName, string Format, int PageCount, string Sha256)
void Deconstruct(ref string FileName, ref string Format, ref int PageCount, ref string Sha256)
bool Equals(ExtractedSource other)
bool Equals(object obj)
int GetHashCode()
string ToString()
bool op_Equality(ExtractedSource left, ExtractedSource right)
bool op_Inequality(ExtractedSource left, ExtractedSource right)
string FileName { get; set; }
string Format { get; set; }
int PageCount { get; set; }
string Sha256 { get; set; }ExtractionWarning
Something the caller should know about the extraction, with the pages it concerns.
ExtractionWarning(string Code, IReadOnlyList<int> Pages)
void Deconstruct(ref string Code, ref IReadOnlyList<int> Pages)
bool Equals(ExtractionWarning other)
bool Equals(object obj)
int GetHashCode()
string ToString()
bool op_Equality(ExtractionWarning left, ExtractionWarning right)
bool op_Inequality(ExtractionWarning left, ExtractionWarning right)
string Code { get; set; }
IReadOnlyList<int> Pages { get; set; }HiddenContent
Content that exists in the document but is not extracted (hidden text, hidden sheets, comments...).
HiddenContent(string Kind, int? Page, string Sheet, int Count)
void Deconstruct(ref string Kind, ref int? Page, ref string Sheet, ref int Count)
bool Equals(HiddenContent other)
bool Equals(object obj)
int GetHashCode()
string ToString()
bool op_Equality(HiddenContent left, HiddenContent right)
bool op_Inequality(HiddenContent left, HiddenContent right)
int Count { get; set; }
string Kind { get; set; }
int? Page { get; set; }
string Sheet { get; set; }DoconutOptions
Configuration options for the Doconut middleware. Register via AddDoconut(options => ...) in Program.cs.
DoconutOptions()
DoconutOptions AddComparerWidget(Action<ComparerWidgetOptions> configure)
DoconutOptions AddCompressorWidget(Action<CompressorWidgetOptions> configure)
DoconutOptions AddConverterWidget(Action<ConverterWidgetOptions> configure)
DoconutOptions AddDocumentToolsWidget(Action<DocumentToolsWidgetOptions> configure)
DoconutOptions AddEditorWidget(Action<EditorWidgetOptions> configure)
DoconutOptions AddExtractorWidget(Action<ExtractorWidgetOptions> configure)
DoconutOptions AddFormsWidget(Action<FormsWidgetOptions> configure)
DoconutOptions AddPlugin<TPlugin>()
DoconutOptions AddProtectorWidget(Action<ProtectorWidgetOptions> configure)
DoconutOptions AddRedactorWidget(Action<RedactorWidgetOptions> configure)
DoconutOptions AddSignerWidget(Action<SignerWidgetOptions> configure)
DoconutOptions RegisterViewer(string extension, Func<IFormatViewer> factory, Func<BaseConfig> defaultConfig)
ComparerWidgetOptions ComparerWidget { get; }
CompressorWidgetOptions CompressorWidget { get; }
ConverterWidgetOptions ConverterWidget { get; }
DocumentToolsWidgetOptions DocumentToolsWidget { get; }
int EditorEvictionIdleMinutes { get; set; }
int EditorSnapshotEveryOps { get; set; }
EditorWidgetOptions EditorWidget { get; }
ExtractorWidgetOptions ExtractorWidget { get; }
FormsWidgetOptions FormsWidget { get; }
string LicenseContent { get; set; }
string LicensePath { get; set; }
Stream LicenseStream { get; set; }
int MaxConcurrentEditorSessions { get; set; }
string MiddlewarePath { get; set; }
DoconutPluginRegistry PluginRegistry { get; }
ProtectorWidgetOptions ProtectorWidget { get; }
RedactorWidgetOptions RedactorWidget { get; }
bool ResetLicense { get; set; }
string ResourcesPath { get; set; }
bool ShowDoconutInfo { get; set; }
SignerWidgetOptions SignerWidget { get; }
bool UnsafeMode { get; set; }AddComparerWidget: Enables the opt-in Comparer widget (?compare=open|run|download).AddCompressorWidget: Enables the opt-in Compressor widget (?compress=open|run|download).AddConverterWidget: Enables the opt-in Converter widget (its ?convert=open|run|download endpoints and served JS). OFF by default — secure by default. Consistent Add<Plugin>Widget() convention across plugins. Requires the Converter plugin (AddPlugin<ConverterPlugin>()) and a license granting Converter.AddDocumentToolsWidget: Enables the opt-in DocumentTools widget (?tools=open|run|download).AddEditorWidget: Enables the opt-in Editor self-service widget — the ?edit=open self-upload endpoint that accepts a .docx and returns a live edit-session token. OFF by default (secure by default): it lets untrusted clients open live, memory-pinned editing sessions, so a host must opt in. Requires the Editor plugin (AddPlugin<EditorPlugin>()) and a license granting Editor.AddExtractorWidget: Enables the opt-in Extractor widget (?extract=open|run|download).AddFormsWidget: Enables the opt-in Forms widget (?forms=open|run|download).AddPlugin: Registers a Doconut plugin (a viewer or a service). Returns the options, so calls can be chained.AddProtectorWidget: Enables the opt-in Protector widget (?protect=open|run|download).AddRedactorWidget: Enables the opt-in Redactor widget (?redact=open|run|download).AddSignerWidget: Enables the opt-in Signer widget (?sign=open|run|download).RegisterViewer: Registers a custom viewer for the given file extension, taking precedence over the built-in viewers. The optional supplies the config used when a document of this type is opened without an explicit config.ComparerWidget: The opt-in Comparer widget options, or null when disabled (the default). Enable via AddComparerWidget. When null, the ?compare= endpoints are inert.CompressorWidget: The opt-in Compressor widget options, or null when disabled (the default). Enable via AddCompressorWidget. When null, the ?compress= endpoints are inert.ConverterWidget: The Converter widget config, or null when the widget is disabled (default). Enable via AddConverterWidget. When null, the ?convert= endpoints are inert.DocumentToolsWidget: The opt-in DocumentTools widget options, or null when disabled (the default). Enable via AddDocumentToolsWidget. When null, the ?tools= endpoints are inert.EditorEvictionIdleMinutes: When MaxConcurrentEditorSessions is reached, a new editing session closes the least recently used one only if that one has had no request for at least this many minutes. When every session is in use, the new open is refused (The editor is busy: too many documents are open. Try again in a few minutes., a 503 from the widget) instead of discarding another user's work. Default 5. 0 or less: the least recently used session is always closed, as before.EditorSnapshotEveryOps: When opt-in editor persistence is enabled (AddDoconutEditorPersistence), snapshot the live document every N recorded mutations (and drop the log up to that point). Bounds both replay time on a rehydration AND how far back undo survives a failover (the "recent window" is the mutations since the last snapshot). Default 50. Set to 0 (or negative) to never mid-session snapshot (replay always runs from the original — larger window, longer replay). No effect when persistence is disabled.EditorWidget: The opt-in Editor self-service widget options, or null when the widget is disabled (default). Enable via AddEditorWidget. When null, the self-upload ?edit=open endpoint is inert (returns 404). The token-bound edit channel (?geometry/?edit/?save/…) is independent of this flag and stays available to any host that opens a document with EditMode.ExtractorWidget: The opt-in Extractor widget options, or null when disabled (the default). Enable via AddExtractorWidget. When null, the ?extract= endpoints are inert.FormsWidget: The opt-in Forms widget options, or null when disabled (the default). Enable via AddFormsWidget. When null, the ?forms= endpoints are inert.LicenseContent: Optional raw XML content of the Doconut license. Use this when the license is stored somewhere other than a file on disk (database, environment variable, secret manager). Takes precedence over LicensePath.LicensePath: Optional path to the Doconut license file. The per-plugin license files in the same folder (Doconut.Viewer.<Capability>.lic) are read with it. A relative path is resolved against the current directory; a path that does not exist loads no license and does not fall back to the search below. If omitted, Doconut searches {CurrentDirectory}/wwwroot, then {AppContext.BaseDirectory}/wwwroot - and nowhere else - for Doconut.lic, then Doconut.Viewer.lic and the plugin licenses; when nothing is found the library runs in evaluation mode (watermarked).LicenseStream: Optional stream containing the Doconut license. Read once at startup. Takes precedence over LicenseContent and LicensePath.MaxConcurrentEditorSessions: Maximum number of concurrent LIVE editor sessions (documents opened with EditMode). When a new editor session would exceed this, the least-recently-used idle editor session is evicted (and disposed) on top of the normal sliding TTL — a self-service widget lets untrusted clients open sessions and walk away, and each editor session pins a live document + undo stacks. Only editor sessions are counted; normal viewer sessions are never counted or evicted by this cap. Default 200. Set to 0 (or negative) for no cap — TTL-only, the pre-widget behavior.MiddlewarePath: URL path prefix for the Doconut page-image endpoint. Default: "/doconut".PluginRegistry: Records viewer and service contributions from plugins registered via AddPlugin{TPlugin}. Consumed by the viewer factory during request dispatch.ProtectorWidget: The opt-in Protector widget options, or null when disabled (the default). Enable via AddProtectorWidget. When null, the ?protect= endpoints are inert.RedactorWidget: The opt-in Redactor widget options, or null when disabled (the default). Enable via AddRedactorWidget. When null, the ?redact= endpoints are inert.ResetLicense: Kept for compatibility; not read. The license is loaded once, when AddDoconut() builds the services: after replacing a license file, restart the application.ResourcesPath: URL path prefix for embedded JS/CSS/image resources. Default: "/doconut-res".ShowDoconutInfo: When true, the middleware writes version information when hit without a token. Default: false.SignerWidget: The opt-in Signer widget options, or null when disabled (the default). Enable via AddSignerWidget. When null, the ?sign= endpoints are inert.UnsafeMode: When true, the middleware skips the ASP.NET Session security check. Leave false in production (default).
DocumentExtractor
Extracts a document's content and metadata as JSON (ToJson) and Markdown (ToMarkdown). Public DI facade over the Extractor plugin's IDocumentExtractor. Pages without a text layer are read by the OCR engine when its package is installed, one page at a time.
Task<ExtractionResult> ExtractAsync(byte[] document, string extension, ExtractOptions options, CancellationToken ct)
Task<ExtractionResult> ExtractAsync(Stream document, string extension, ExtractOptions options, CancellationToken ct)
Task<ExtractionResult> ExtractAsync(string path, ExtractOptions options, CancellationToken ct)ExtractAsync: Extracts ; (incl. the dot) identifies the format.ExtractAsync: Extracts ; (incl. the dot) identifies the format.ExtractAsync: Path overload: the extension and (when not set) FileName come from the path.
ExtractorWidgetOptions
Options for the opt-in Extractor widget (?extract=open|run|download).
ExtractorWidgetOptions()
int MaxUploadMb { get; set; }MaxUploadMb: Largest accepted upload, in megabytes. Default 25.
ExtractorPlugin
The Doconut Extractor plugin: contributes the IDocumentExtractor service, gated by the Extractor capability.
ExtractorPlugin()
void Register(IDoconutPluginBuilder builder)
string Name { get; }
LicenseCapability RequiredCapability { get; }Troubleshooting
Troubleshooting
| What you see | Cause | Fix |
|---|---|---|
Startup: AddExtractorWidget() was called but the Extractor plugin is not registered. Add options.AddPlugin<Doconut.Plugins.Extractor.ExtractorPlugin>() (the widget needs it), or remove the AddExtractorWidget() call. | The widget was enabled without its plugin. | Add options.AddPlugin<ExtractorPlugin>() (see Register the plugin) or remove AddExtractorWidget(). |
Startup: The Extractor plugin is registered via AddPlugin but no active license grants Extractor… | No licence, a legacy TRIAL file, or missing Doconut.Viewer.Extractor.lic. | Place the licence files (including Doconut.Viewer.Extractor.lic) in the wwwroot folder (see Licensing & watermark). |
Widget: The server could not process this document. (immediately after drop) | The endpoint returned 404 because the widget is not registered or the request never reaches UseDoconut(). | Call options.AddExtractorWidget(...) and ensure the request path matches the middleware mounted with app.Map. |
Console: Doconut is not defined (page shows nothing) | The static resources were not served. | Add app.UseDoconutResources() (see In production). |
Widget: This file is over the 25 MB limit. | Uploaded file exceeds the widget’s maxUploadMb. | Increase ExtractorWidgetOptions.MaxUploadMb on the server and the maxUploadMb value used by the UI. |
Widget: File is too large. | Server‑side MaxUploadMb is smaller than the UI’s limit. | Set the same MaxUploadMb value in AddExtractorWidget. |
Widget: This document is password protected. | The widget does not accept a password. | Use the C# façade with ExtractOptions.Password. |
Widget: This file format is not supported. | The file’s extension is not recognised by the SDK. | Verify the file’s extension is supported. |
Widget: The document has 612 pages; the maximum of 500 page(s) was exceeded. | ExtractOptions.MaxPages default (500) was exceeded. | Call ExtractAsync(..., new ExtractOptions { MaxPages = <higher> }, ct). |
Widget: The spreadsheet has 1,250,000 cells in its used ranges; the maximum of 1,000,000 cells was exceeded. | ExtractOptions.MaxCells default (1 000 000) was exceeded. | Call ExtractAsync(..., new ExtractOptions { MaxCells = <higher> }, ct). |
Widget: Upload expired — please re-open the file. | More than 30 minutes passed or the upload hit another node in a farm. | Re‑upload the document; in a web‑farm ensure all nodes share the same IDocumentAccessStore (see In production). |
Widget: The download failed. Please extract the document again. | The download endpoint returned an error (often missing app.UseSession() or token expired). | Add AddDistributedMemoryCache(), AddSession(), and app.UseSession() before app.Map; then re‑run extraction. |
Widget: Evaluation only. Processed with Doconut… | A temporary or missing licence. | Install a paid licence that grants the Extractor capability. |
Log: Doconut OCR is off: the OCR engine could not load onnxruntime.dll because the Microsoft Visual C++ 2015‑2022 Redistributable (x64) is not installed… | Required C++ runtime missing on Windows. | Install the x64 Visual C++ 2015‑2022 Redistributable (https://aka.ms/vs/17/release/vc_redist.x64.exe) and restart the app. |
Log: Doconut OCR: the OCR engine package is installed, but the licence includes neither Search nor Extractor — scanned pages are not read. | Licence does not grant OCR/Extractor. | Add a licence that includes the Extractor (and Search if needed) capability. |
Widget: Clicking a block does nothing | No viewer instance was supplied or viewer.css is missing. | Pass a viewer to the UI and ensure viewer.css is loaded (see ShowBlock in the viewer). |
| Viewer: Block box appears in the wrong place | ExtractOptions.CheckVisibility was left on for a document with invisible text, or the page size differs. | For trusted PDFs set ExtractOptions.CheckVisibility = false; otherwise verify page dimensions. |
Result JSON: hidden contains invisibleText and the text is missing from blocks | Text colour matches background; visibility check filtered it out. | Disable the visibility check (CheckVisibility = false) for documents you trust. |
Was this page helpful?