Search

Native text search in the Viewer composition

The Doconut Viewer provides normal Search using text extracted by the format viewer or a text-based PDF redirect. It requires the Search license capability. Scanned pages also need the OCR engine package; see Search scanned documents (OCR).

Enable the search UI

Search is a Viewer module, not a standalone toolbar. The complete page must include the Viewer resources, Viewer toolbar, Viewer mount, and initialized objViewer; the Search Ribbon is then mounted and attached to that same instance.

Search and annotation are built-in licensed features, not AddPlugin<T>() packages. Request the search resources from the injected Viewer; their tags are emitted only when the license grants Search.

html
@Html.Raw(Viewer.ReferenceCss(new CssConfig
{
    IncludeViewerCss = true,
    IncludeSearchCss = true
}))

@Html.Raw(Viewer.ReferenceScripts(new ScriptConfig
{
    IncludeJQuery = true,
    IncludeViewerScripts = true,
    IncludeSearchScripts = true,
    IncludeSearchBar = true
}))

The embedded ribbon calls the same JavaScript methods available to a custom UI.

Keep the complete Viewer composition visible in the markup, initialize docViewer first, and then attach the licensed Ribbon:

html
<nav id="toolbar" aria-label="Document viewer controls">
    <!-- Viewer controls, including the button that opens Search -->
</nav>
<div id="searchBarMount"></div>
<div id="divDocViewer"><div id="div_ctlDoc"></div></div>

<script>
    let searchBar = null;
    let currentToken = '';

    const objViewer = $('#div_ctlDoc').docViewer({
        BasePath: 'doconut',
        ResPath: 'doconut-res/images'
    });

    @if (Viewer.IsSearchEnabled)
    {
        <text>
    searchBar = $('#searchBarMount').doconutSearchBar({
        docId: 'ctlDoc',
        getRequestParams: () => ({ token: currentToken }),
        onStatus: (message) => console.log(message),
        onToast: (message, type) => console.log(type, message),
        onLayout: () => requestAnimationFrame(() => objViewer.Refit())
    });
    searchBar.attach(objViewer);
        </text>
    }
</script>

The server-side if matters: without the Search capability, ReferenceScripts leaves out the Ribbon's script, so an unguarded doconutSearchBar(...) call would throw and stop the viewer page from starting.

The component injects Find, Options, and Results groups and handles searching, clearing, match counts, and previous/next match navigation. A host-owned Viewer toolbar only needs to toggle it:

javascript
searchBar.isOpen() ? searchBar.close() : searchBar.open();

Its public API is intentionally small:

MethodPurpose
attach(objViewer)Connect the Ribbon to the initialized viewer; required once
open() / close()Show or hide the Ribbon; closing also clears highlights
reset()Clear the current term, result count, and highlights
isOpen()Report whether the Ribbon is visible
setStatus(message)Forward a status message through the configured callback

The optional onToggle(isOpen) callback lets the host synchronize its Search button, and onLayout lets it resize/refit the viewer when the Ribbon changes height. For the combined Viewer, Search, and Annotation startup sequence, see Quick Start.

Search from JavaScript

javascript
objViewer.Search(keyword, false, function (resultCount) {
    console.log('Matches:', resultCount);
});

The second argument is whole-word/exact matching. The match count arrives in the callback: Search itself goes to the server and returns nothing useful, so var n = objViewer.Search(keyword, false) always reads undefined — and a page built that way reports "nothing found" while the viewer highlights the matches. After the callback:

MethodResult
SearchMatchCount()Total individual matches in the document.
SearchSummary(false)[pageNumber, matchCount] entries without repainting.
SearchSummary(true)Same summary and paints page/thumbnail highlights.
GotoSearchMatch(index)Navigates to a zero-based match index.

A fourth argument, onProgress(resultCount, done, total), reports a search that is still reading scanned pages with OCR: the matches found so far are already highlighted, done pages of total are read, and total is null until the server knows how many pages it has to read. The final count still arrives once, in the callback. The viewer option onSearchProgress receives the same three values for every search, the Search bar's included (see ViewerConfig). Added in 26.11.0.

javascript
objViewer.Search(keyword, false, function (resultCount) {
    console.log('Matches:', resultCount);
}, function (resultCount, done, total) {
    console.log('Read', done, 'of', total === null ? '?' : total, 'pages,', resultCount, 'matches so far');
});

The highlights are drawn by $.fn.ocrSearch (search.js), which the viewer creates on the first Search and owns: call the viewer's methods above, never the plugin directly. To reset or hide a search, the viewer has NewSearch(), ClearSearch() and IsSearchLimited() (see ViewerConfig). IsSearchLimited() is true when the server capped the results at five, which it does under a trial license (the reply carries limited="1").

The middleware route uses search=<term> and exact=true|false and returns XML. Use the widget API rather than parsing that internal response yourself.

Check search capability

The initialization response reports:

text
X-Doconut-Can-Search: 1

After initialization, objViewer.CanSearch() exposes the same format/session verdict. It returns false when the server sends 0; before the response, or with an older server that omits the header, it defaults to true.

Three independent gates must not be confused:

GateQuestion
CanSearch() / response headerDoes the resolved viewer have a native index/search path?
AllowSearchDid this format config request text extraction where the switch exists?
LicenseCapability.SearchIs the application authorized to execute search and receive the UI bundles?

A format can be technically searchable while the current license denies the operation.

Enable extraction per format

csharp
var token = await viewer.OpenDocumentAsync(path, new PdfConfig
{
    AllowSearch = true,
    AllowCopy   = true   // optional: lets the user drag a region and copy its text
});

AllowSearch and AllowCopy exist on PdfConfig, WordConfig, ExcelConfig, and PptConfig. The Office properties delegate to their nested PdfConfig. Both default to false.

Normal native-search adapters exist for PDF, Word, Excel, PowerPoint, TXT, Visio, email, EPUB, and MHT. XPS uses its PDF path by default. HTML and Microsoft Project benefit from a text-based PDF redirect:

csharp
// DefaultRender = false → converted to a text-based PDF → searchable
var token = await viewer.OpenDocumentAsync(path, new HtmlConfig { DefaultRender = false });

For native renderers, CanSearch() describes the viewer capability; it does not guarantee that a particular document contains usable text. A PDF whose pages are only scanned images produces no native results; those pages are read by the OCR engine, described in the next section.

Search scanned documents (OCR)

Text search needs nothing else. Pages that have no text layer (images and TIFF, scanned PDFs, and the scanned pages of a PDF that mixes digital and scanned pages) become searchable only with the OCR engine, which ships as its own package:

bash
dotnet add package Doconut.NET8.Engines.Ocr --version 26.11.0

The 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).

Searching in the viewer still needs the Search capability, and a PDF still needs AllowSearch = true on its PdfConfig, as for its text search (Enable extraction per format). Pages are read in the background from the first search, and the viewer shows the matches as they are found.

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.

Normal Search behavior

The server tries search sources in this order:

  1. Results from the format's native viewer.
  2. A prebuilt .srh search index.
  3. An error/empty result when no search source exists.

The .srh index is the search artifact published alongside the page images when documents are served from shared storage, so a node that never opened the document can still answer searches — see Distributed Deployments.

CanSearch() can be true for a searchable viewer even when a particular document has no text layer and therefore returns no matches.

Search result types

The server-side types behind the widget's search, in namespace Doconut. The viewer uses them itself; you need them only to search an OCR index directly or to implement an OCR engine.

DocSearch: searches a pre-built XML OCR index for matching text and returns bounding-box results used by the viewer to highlight hits on page images. Create it with new DocSearch(XDocument ocrDocument) and call Search(word, exactMatch, optimise = false): word is the term (several space-separated words are a phrase), exactMatch returns whole-word matches only (for a phrase, the words in sequence on one line), and optimise caps the results at 10. An empty term, or one longer than 256 characters, returns no results. Each match is an OcrResult, whose values are strings as the index stores them; OcrResult.ToString() writes the match as the viewer's search reply carries it, XML-escaped:

TypePropertyDefaultDescription
stringPage""Page number (1-based).
stringOW""Original page width in pixels.
stringOH""Original page height in pixels.
stringX""X position of the text bounding box.
stringY""Y position of the text bounding box.
stringW""Width of the text bounding box.
stringH""Height of the text bounding box.
stringC""Confidence score or character data.

OcrDocument is the structured result an OCR engine returns (IOcrService.RecognizeStructuredAsync): its Pages hold OcrPage entries, whose Words hold OcrWord entries.

OcrDocument:

TypePropertyDefaultDescription
IReadOnlyList<OcrPage>PagesemptyThe recognised pages, in order.

OcrPage:

TypePropertyDefaultDescription
intPageNumber0The page number.
IReadOnlyList<OcrWord>WordsemptyThe words recognised on the page.

OcrWord:

TypePropertyDefaultDescription
stringText""The recognised word.
doubleX0Left edge of the word's box.
doubleY0Top edge of the word's box.
doubleWidth0Width of the box.
doubleHeight0Height of the box.
doublePageWidth0Width of the recognised page image.
doublePageHeight0Height of the recognised page image.

Licensing and UI behavior

An active Temporary/Demo license grants Search during its active period. A missing license and legacy TRIAL file grant no Search capability. Without Search:

  • ReferenceCss and ReferenceScripts omit the search bundles.
  • The middleware denies search instead of returning licensed results.

Drive custom UI visibility from IDoconutLicenseService.IsCapabilityGranted(LicenseCapability.Search) and use CanSearch() for the separate format/session verdict.

Troubleshooting

SymptomCheck
Search bar is missingSearch capability and IncludeSearchCss/IncludeSearchScripts/IncludeSearchBar
CanSearch() is falseFormat viewer, selected DefaultRender path, and initialization response header
Search returns zero for a scanned documentInstall Doconut.NET8.Engines.Ocr; check that the license includes Search, that a PDF is opened with AllowSearch = true, and on Windows that the Visual C++ 2015‑2022 Redistributable (x64; for a 32-bit process, the x86 one) is installed. The startup log says which is missing
Search works but highlights are offsetRendering path, resolution, document transforms, and extracted word boxes

Was this page helpful?