A 5,000 ms recognition timeout on an in-process Tesseract call does not mean the call comes back after five seconds. With a large multi-language model set, the calling thread can stay inside the native library well past that mark, because the progress monitor that enforces the deadline is polled while words are being recognized, and model loading and page layout analysis both happen before the first poll. That gap, a cancel callback whose C return type is a single byte, and an iterator that hands out memory you must never free are the real work of binding the Tesseract C API to Delphi. The rest is plumbing
Wiring the Tesseract DLL into a HotPDF text layer
HotPDF exposes the in-process path as HPDFCreateTesseractDLLOCREngine in the HPDFTesseractRecognition unit. The factory loads a Tesseract DLL that exports the C API, drives TessBaseAPIInit2, TessBaseAPIRecognize and the result iterator, and returns an IHPDFOCREngine. THotPDF.ApplyLoadedOCRTextLayer takes that engine and adds an invisible, searchable Unicode text layer to scanned pages, the same call every HotPDF OCR engine goes through
The factory validates eagerly. The DLL file and the tessdata directory must exist. The language identifier may contain only ASCII letters, digits, _ and +, and every model in a combination such as chi_sim+eng needs a matching .traineddata file. All 21 required exports have to resolve before you get an engine back. Configuration errors raise EArgumentException, with a missing export or model reported by name; a DLL that will not load raises EOSError carrying the Windows error code and a hint to check architecture and dependencies
uses
SysUtils, HPDFDoc, HPDFTesseractRecognition;
procedure MakeSearchable(const SourceFile, TargetFile: string);
var
Doc: THotPDF;
Engine: IHPDFOCREngine;
Options: THPDFOCRTextLayerOptions;
Info: THPDFOCRTextLayerInfo;
begin
// A Win64 application needs a 64-bit DLL; the file name depends on your build,
// and its dependency DLLs go in the same folder
Engine := HPDFCreateTesseractDLLOCREngine('C:\OCR\Win64\libtesseract.dll',
'C:\OCR\tessdata', 'chi_sim+eng'); // uses THPDFTesseractOptions.Default
Doc := THotPDF.Create(nil);
try
Doc.AutoLaunch := False;
if Doc.LoadFromFile(SourceFile) < 1 then
raise Exception.Create('Cannot load ' + SourceFile);
Options := THPDFOCRTextLayerOptions.Default; // 300 DPI, MinimumConfidence 0.5
// An empty page list means every page; pages that already carry text are skipped
if not Doc.ApplyLoadedOCRTextLayer([], Engine, Options, Info) then
raise Exception.Create(string(Info.Diagnostic));
Writeln(string(Info.EngineName), ': ', Info.AcceptedWordCount,
' words accepted, ', Info.DroppedWordCount, ' dropped');
Doc.SaveLoadedDocument(TargetFile);
finally
Doc.Free;
end;
end;
THPDFTesseractOptions.Default sets PageSegMode to tpsAuto, EngineMode to temDefault, TimeoutMilliseconds to 60,000 and MaxPixels to 16,777,216. That pixel budget bites sooner than people expect. A US Letter page at the default 300 DPI renders to 2,550 × 3,300 pixels, roughly 8.4 million, and fits. Suppose you raise the same page to 600 DPI: it becomes 5,100 × 6,600, about 33.7 million pixels, and the engine rejects it with Invalid Tesseract DLL OCR request or pixel budget before Tesseract ever sees the image. Either raise MaxPixels (the ceiling is 67,108,864) or stay at 300 DPI, which is plenty for body text; each side is also capped at 32,767 pixels
The DLL is loaded with LoadLibraryEx and the search flags for the DLL's own folder plus the default safe directories. The image libraries Tesseract depends on can therefore sit next to it, and you never have to touch PATH or rely on the current directory. HotPDF does not bundle or download an OCR runtime or any language model; you provision both
What the DLL path changes compared with tesseract.exe
The same recognizer is also reachable through the external tesseract.exe adapter that writes a BMP and parses TSV. Both adapters feed one text-layer pipeline, so coordinate mapping, confidence filtering and the all-or-nothing commit behave identically. What differs is how pixels go in, how words come out, and what happens when the recognizer misbehaves
| Aspect | tesseract.exe adapter | Tesseract DLL adapter |
|---|---|---|
| Factory | HPDFCreateTesseractOCREngine | HPDFCreateTesseractDLLOCREngine |
| Pixels in | BMP file in a private temporary directory | 8-bit grayscale buffer in memory |
| Words out | Word-level TSV, capped at 64 MiB | Result iterator, UTF-8 per word |
| Baselines | Not in the TSV; the pipeline estimates them | Passed through from TessPageIteratorBaseline |
| Page segmentation and engine mode | THPDFTesseractOptions overload, sent as --psm and --oem | THPDFTesseractOptions, sent to TessBaseAPISetPageSegMode and TessBaseAPIInit2 |
| Pixel budget | MaxPixels when options are passed | MaxPixels always, plus 32,767 pixels per side |
| Timeout | Hard: the child process is terminated | Cooperative: Tesseract has to notice |
| Crash and memory isolation | Separate process | None, it shares your address space |
One cost stays with the DLL. Each Recognize call creates its own API instance and runs TessBaseAPIInit2, so the language models are initialized for every page. The file cache takes the edge off the reload, yet with a big multi-language model set it remains the largest fixed cost per page, and it is charged against the recognition deadline. The in-process RapidOCR DLL engine makes the opposite choice and keeps its ONNX models resident for the engine's lifetime, while the boundary problems (C ABI, borrowed buffers, native work you cannot interrupt) belong to the same family
So which one belongs in production? For a desktop tool or a batch job working through a few hundred scans, the DLL is the better fit: no process launch per page, no temporary bitmap on disk, and real baselines for skewed lines. A long-running server that accepts PDFs from strangers should stay on tesseract.exe, because a native crash or runaway allocation there takes down one child process instead of your service
Why can't Delphi copy the Tesseract monitor struct?
Delphi cannot safely mirror Tesseract's progress monitor, because ETEXT_DESC carries internal fields that vary between Tesseract builds. A record translated by hand from one header puts the cancel callback and the deadline at whatever offsets that header used. Run it against a different build and Tesseract reads your callback pointer out of a field that now means something else, or never finds the deadline at all, and recognition simply runs to the end
The HotPDF adapter therefore treats the monitor as an opaque pointer and touches it only through exported functions: TessMonitorCreate, TessMonitorSetCancelThis, TessMonitorSetCancelFunc, TessMonitorSetDeadlineMSecs and TessMonitorDelete. The sketch below is your own binding code rather than HotPDF API; its declarations match the ones the adapter resolves with GetProcAddress
type
// C: typedef bool (*TessCancelFunc)(void *cancel_this, int words);
TTessCancelFunc = function(CancelThis: Pointer; Words: Integer): Boolean; cdecl;
TTessMonitorCreate = function: Pointer; cdecl; // ETEXT_DESC*, never dereferenced
TTessMonitorDelete = procedure(Monitor: Pointer); cdecl;
TTessMonitorSetCancelFunc = procedure(Monitor: Pointer; Func: TTessCancelFunc); cdecl;
TTessMonitorSetCancelThis = procedure(Monitor, CancelThis: Pointer); cdecl;
TTessMonitorSetDeadlineMSecs = procedure(Monitor: Pointer; MSecs: Integer); cdecl;
TTessBaseAPIRecognize = function(Handle, Monitor: Pointer): Integer; cdecl;
// Your own job state, not a HotPDF type
TOCRJob = record
CancelRequested: Boolean;
DeadlineTick: UInt64;
end;
POCRJob = ^TOCRJob;
function ShouldCancel(CancelThis: Pointer; Words: Integer): Boolean; cdecl;
begin
// Runs on Tesseract's stack: read a flag and the clock, never raise
Result := (CancelThis = nil) or POCRJob(CancelThis)^.CancelRequested or
(GetTickCount64 >= POCRJob(CancelThis)^.DeadlineTick);
end;
// Usage, with the function pointers resolved by GetProcAddress:
// Monitor := MonitorCreate();
// try
// MonitorSetCancelThis(Monitor, @Job);
// MonitorSetCancelFunc(Monitor, ShouldCancel);
// MonitorSetDeadlineMSecs(Monitor, RemainingMs);
// RC := BaseAPIRecognize(API, Monitor);
// finally
// MonitorDelete(Monitor);
// end;
The sketch types the callback as Boolean, one byte in both Delphi and Free Pascal, which matches the C bool in TessCancelFunc. The four-byte Windows BOOL and Delphi LongBool look interchangeable and are a different type: when one side writes a single byte and the other reads four, the upper three bytes are whatever the register held before, and a false can arrive as true. TessPageIteratorBoundingBox returns an int, declared as Integer on the Pascal side, so read the C type of each return value instead of assuming one rule for the whole API
The callback also never raises. A Delphi exception unwinding through Tesseract's C++ frames is undefined behavior. The HotPDF callback reads only the cancellation token and a monotonic GetTickCount64 value, and the adapter turns the outcome into a cancellation or timeout diagnostic after TessBaseAPIRecognize returns. It runs that check whether the native return code was 0 or not
Which native pointers does the Delphi side own?
The HotPDF Tesseract DLL adapter owns three native objects per request (the API instance, the monitor and the result iterator) and borrows everything else. Each Recognize call creates its own set and releases it in a finally block in a fixed order: TessResultIteratorDelete, then TessMonitorDelete, then TessBaseAPIDelete. Releasing the engine interface calls FreeLibrary on the DLL
TessResultIteratorGetPageIteratorreturns a view into the result iterator rather than a new object. The adapter uses it forTessPageIteratorBoundingBoxandTessPageIteratorBaselineand never frees it; deleting it as well would release the same memory twiceTessResultIteratorGetUTF8Textreturns a string allocated by the DLL's own runtime. The adapter decodes it and hands it back throughTessDeleteTextin afinallyblock, because PascalFreeMemwould release it on the wrong heap- Word text goes through strict UTF-8 decoding with a length check first. A word with control characters, malformed UTF-8, a box outside the image, an inverted rectangle or a confidence outside 0–100 fails the request; the adapter does not patch it up
- Text per request is capped at 1,048,576 UTF-16 code units, and the word count has to fit the budget that
ApplyLoadedOCRTextLayerhands down with each page
Confidence arrives as 0–100 and is scaled to 0–1, so THPDFOCRTextLayerOptions.MinimumConfidence means the same thing for every engine. When Tesseract reports a baseline, both endpoints are passed through, and for a predominantly vertical word the box width is used as the text height. Without a baseline the text-layer pipeline falls back to its geometric estimate, exactly as it does for TSV input
Range-checking enum options before they reach the DLL
The factory copies the raw bytes of PageSegMode and EngineMode into an Integer before range-checking them. A compiler is entitled to assume an enum variable always holds a declared value, so a test like Ord(X) > Ord(High(T)) written directly against the enum can be folded to a constant false. Those ordinals reach the DLL as plain integers: THPDFTesseractPageSegMode follows Tesseract's page segmentation numbering from 0 to 13 and THPDFTesseractEngineMode its engine mode numbering from 0 to 3. An options record cleared with FillChar, read from a stream, or filled from C++Builder through an integer cast can carry a byte like 200, and validating the copy turns that into an EArgumentException at factory time. The factory also rejects tpsOSDOnly and tpsAutoOnly, which return no words, and requires osd.traineddata for tpsAutoOSD and tpsSparseTextOSD
What does the recognition timeout actually guarantee?
The Tesseract DLL timeout is cooperative: HotPDF can stop its own work and ask Tesseract to stop, but it cannot force native code to return. The clock starts when Recognize begins, so grayscale conversion and model initialization draw on the same budget as recognition itself. The adapter checks elapsed time and the cancellation token every 64 rows during grayscale conversion, after initialization, and before each word while walking the results. Right before TessBaseAPIRecognize it passes the remaining milliseconds to TessMonitorSetDeadlineMSecs
The gap sits inside the native calls. Tesseract consults its monitor only during word recognition, so inside TessBaseAPIInit2 or page layout analysis a slow model load or a pathological layout can run past the deadline before the timeout gets reported. The pixel and output budgets do not cap the native library's own memory use either. When you need a worker you can kill outright, the process adapter is the tool for it
Page segmentation is where the DLL adapter pays off on awkward input. Forms, labels and scanned tables with scattered fields often recognize better with tpsSparseText than with automatic segmentation, which tries to assemble columns and paragraphs that are not there. The timeout below is short for a form page and still has to cover model initialization
procedure OCRFormPages(Doc: THotPDF; const Pages: array of Integer);
var
Engine: IHPDFOCREngine;
TessOptions: THPDFTesseractOptions;
LayerOptions: THPDFOCRTextLayerOptions;
Info: THPDFOCRTextLayerInfo;
begin
TessOptions := THPDFTesseractOptions.Default;
TessOptions.PageSegMode := tpsSparseText; // scattered fields, no column assembly
TessOptions.EngineMode := temLSTMOnly; // needs LSTM models in tessdata
TessOptions.TimeoutMilliseconds := 20000; // includes model initialization
Engine := HPDFCreateTesseractDLLOCREngine('C:\OCR\Win64\libtesseract.dll',
'C:\OCR\tessdata', 'eng+deu', TessOptions);
LayerOptions := THPDFOCRTextLayerOptions.Default;
LayerOptions.MinimumConfidence := 0.6;
if not Doc.ApplyLoadedOCRTextLayer(Pages, Engine, LayerOptions, Info) then
case Info.Status of
otlsCancelled:
Writeln('OCR cancelled, document unchanged');
otlsEngineError:
if Pos('timed out', string(Info.Diagnostic)) > 0 then
Writeln('Tesseract timed out, document unchanged')
else
Writeln('Tesseract failed: ', string(Info.Diagnostic));
else
Writeln(string(Info.Diagnostic));
end;
end;
A timeout surfaces as otlsEngineError with Tesseract DLL OCR timed out in the diagnostic. A token set through THPDFOCRTextLayerOptions.CancellationToken surfaces as otlsCancelled. In both cases ApplyLoadedOCRTextLayer recognizes every selected page before it starts the commit, so a failure on page 40 of 50 leaves the loaded document exactly as it was. tpsSingleLine, tpsSingleBlock and tpsSparseText change segmentation only; none of them straightens a skewed scan
Free Pascal and Lazarus: stale pixels and lost Chinese
Both Tesseract factories work in Windows Free Pascal and Lazarus Win32 and Win64 builds once the Lazarus package is rebuilt for the target architecture; the general port is covered in HotPDF on Free Pascal and Lazarus Win64. Input handling is where FPC behaves differently
An LCL TBitmap written through scanlines can update its raw image without refreshing the Windows bitmap handle, so GetDIBits on that handle returns the old pixels. The symptom is baffling: text drawn straight onto a bitmap is recognized, a page rendered through scanlines yields no words. Under FPC the DLL adapter reads a format-aware snapshot through CreateIntfImage, which respects the raw image's pixel format and row order. The Delphi build keeps the GetDIBits path on a private 24-bit copy, and neither build modifies the caller's bitmap
The tesseract.exe adapter meets a different problem. FPC's TStringList stores ANSI strings, so assigning decoded UTF-8 TSV text to Lines.Text drops every Chinese or supplementary-plane character the system ANSI code page cannot represent. The FPC path keeps the TSV as UTF-8 bytes, strips the BOM at byte level and decodes each word to UnicodeString on its own. The DLL adapter never meets the problem, since it decodes each word straight from the iterator
The Tesseract DLL adapter ships alongside the process adapters and the built-in OCR engine in HotPDF for Delphi, C++Builder and Free Pascal. Editions and downloads are listed on the HotPDF Delphi PDF component page