How to Scan, OCR, and Export Documents to Searchable PDF in JavaScript with Dynamic Web TWAIN

Organizations of all sizes face a common challenge: efficiently managing the vast documents that power their operations. Manual data entry is a persistent bottleneck—time-consuming, error-prone, and costly—that hurts productivity and increases expenses. Optical Character Recognition (OCR) technology solves this by converting scanned documents into fully searchable, editable text for modern digital workflows.

Dynamsoft’s Dynamic Web TWAIN has long been a leader in web-based document scanning. Since 19.5 its OCR Connector add-on is engine-aware: instead of shipping one fixed recognition engine, it drives whatever the local service can reach — the OCR built into Windows or macOS, or an ONNX Runtime engine you deploy yourself. The same release dropped the old OCRKit namespace, so Addon.OCRConnector is the only OCR API worth writing against today.

This tutorial walks through building a document management application on that API: scan or load pages, pick an engine, recognize text, fix page orientation, and export a searchable PDF.

What you’ll build: A browser-based JavaScript application that scans physical documents (or loads images), enumerates the OCR engines available on the machine, recognizes text with the chosen engine and language, and exports the result as a searchable or plain-text PDF.

Key Takeaways

  • Addon.OCRConnector.GetInstalledOCRInfo() returns { version, engines: [{ name, languages }] }, so the UI can offer exactly the engines and languages the machine actually has.
  • Since 19.5 the OCR Connector is part of the dynamsoft.webtwain.min.js bundle — there is no dynamsoft.webtwain.addon.ocrkit.js to copy into Resources/addon anymore.
  • Recognize(index, { engine: { name }, settings: { language } }) returns structured blocks, lines and words plus the imageID that ties the result to the page.
  • SaveToPath(indices, EnumDWT_OCRConnectorOutputFormat.PDF_WITH_EXTRA_TEXTLAYER, 'searchable-document.pdf') writes a searchable PDF in one call; PDF_PLAIN_TEXT writes text only.
  • OCR Connector runs on Windows 10+ and macOS 10.15+ only. Linux services reject the call, and orientation detection additionally needs the optional Onnx.Ocr engine.

Common Developer Questions

How do I add OCR to a document scanning web app using JavaScript?

Initialize Dynamic Web TWAIN, call Addon.OCRConnector.GetInstalledOCRInfo() once the object is ready, fill an engine picker from info.engines, and pass the selection to Addon.OCRConnector.Recognize(index, { engine: { name }, settings: { language } }). The engine is an object, not a string, and each engine publishes its own language codes.

How do I export a scanned document as a searchable PDF with a text layer in JavaScript?

Call Addon.OCRConnector.SaveToPath(indices, outputFormat, path) with PDF_WITH_EXTRA_TEXTLAYER to keep the page image and lay an invisible text layer over it, or PDF_PLAIN_TEXT for the recognized text alone. A bare filename such as searchable-document.pdf opens the system save dialog so the user chooses the folder.

How do I detect and correct image orientation before running OCR on scanned documents?

Addon.OCRConnector.DetectPageOrientation(index) returns the page angle. Rotate the buffer with DWTObject.Rotate(index, (360 - angle) % 360, true) when the angle is nonzero. Only the Onnx.Ocr engine implements detection, so pass no engine and let the service use it when installed.

Demo Video: Document OCR and PDF Saving

Prerequisites

  • Get a 30-day free trial license. The trial covers OCR Connector; Core Module 19.5 and later include it at no extra cost.
  • Dynamic Web TWAIN Service 19.5 installed on the machine that scans — Windows 10 or later, or macOS 10.15 or later. The downloads page ships Windows, macOS and Linux builds, but OCR Connector is not available on Linux.
  • A scanner and its driver, or a few images to load instead.

Step 1: Set Up Dynamic Web TWAIN 19.5 and OCR Connector

  1. Install Dynamic Web TWAIN Service 19.5. The service is the half that talks to scanners and to OCR engines.
  2. Load the JavaScript bundle. This sample pulls the SDK from jsDelivr, and the bundle already contains the OCR Connector:

     <script src="https://cdn.jsdelivr.net/npm/dwt@19.5.0/dist/dynamsoft.webtwain.min.js"></script>
    

    If you vendor the SDK instead of using the CDN, the equivalent file under Resources/addon/ is dynamsoft.webtwain.addon.ocrconnector.js. The 19.3-era dynamsoft.webtwain.addon.ocrkit.js no longer exists — 19.5 renamed the namespace and folded the add-on into the main package.

  3. Nothing else is required for the default path. Windows.Media.Ocr ships with Windows 10+ and Apple.Vision with macOS 10.15+, so GetInstalledOCRInfo() answers on a clean machine. A language only appears in the list after its OCR language pack is installed in the operating system.

  4. Optional, only for the Onnx.Ocr engine: download the OCR package ZIP, extract it, and run Install.cmd as administrator. The script copies the ONNX runtime and models into the ocr folder inside the service installation directory. This engine is what makes page-orientation detection available.

    Install the optional Onnx.Ocr pack

Platform note: OCR Connector is a Windows/macOS component. Called against a Linux service, every method rejects with a “not supported on this platform” error — scanning, preview and PDF export keep working there, but OCR has to move server-side.

Step 2: Understand the Project Structure

The application follows a simple, maintainable structure:

├── index.html          # Main HTML structure
├── css/
│   └── style.css       # Modern CSS with variables
├── js/
│   └── app.js          # Core application logic

There is no build step and no local copy of the SDK: index.html loads the CDN bundle, style.css and app.js directly. The heart of the application is js/app.js, which wraps the OCR Connector in three functions — enumerate, recognize, export.

Step 3: Integrate the Dynamic Web TWAIN OCR API

Let’s dive into the key parts of the code that demonstrate Dynamic Web TWAIN’s OCR capabilities.

Enumerate the OCR Engines

Wait for the object, then ask the service what it can drive. GetInstalledOCRInfo() is the only reliable way to know: engine availability depends on the operating system, installed language packs and whether the ONNX pack was deployed.

Dynamsoft.DWT.RegisterEvent("OnWebTwainReady", function () {
    DWTObject = Dynamsoft.DWT.GetWebTwain("dwtcontrolContainer");
    initOCR();
});

let ocrInfo = null;
let ocrReady = false;
let ocrError = "";

async function initOCR() {
    const engineSelect = document.getElementById("engine");
    const languageSelect = document.getElementById("language");
    try {
        ocrInfo = await DWTObject.Addon.OCRConnector.GetInstalledOCRInfo();
        if (!ocrInfo.engines || ocrInfo.engines.length === 0) {
            throw new Error("the local service reported no OCR engine");
        }
        engineSelect.innerHTML = "";
        ocrInfo.engines.forEach(function (engine) {
            engineSelect.add(new Option(engine.name, engine.name));
        });
        fillLanguages(engineSelect.value);
        ocrReady = true;
    } catch (error) {
        ocrError = "OCR is not available here: " + (error.message || error) +
            "\nOCR Connector runs on Windows and macOS only. Linux is not supported yet.";
        engineSelect.innerHTML = "";
        engineSelect.add(new Option("Not available", ""));
        languageSelect.innerHTML = "";
        languageSelect.add(new Option("Not available", ""));
        document.getElementById("result").innerText = ocrError;
    }
    refreshOCRControls(); // disable the OCR buttons when ocrReady is false
}

function fillLanguages(engineName) {
    const select = document.getElementById("language");
    select.innerHTML = "";
    const engine = ocrInfo.engines.find(function (item) { return item.name === engineName; });
    ((engine && engine.languages) || []).forEach(function (language) {
        select.add(new Option(language, language));
    });
}

The engines you will meet:

Engine Platform How it gets there
Windows.Media.Ocr Windows 10+ Built into the OS. One language pack per recognition language.
Apple.Vision macOS 10.15+ Built into the OS. Older releases expose fewer languages.
Onnx.Ocr Windows 10+ Optional OCR pack, installed with Install.cmd. Six languages, plus orientation detection.

Platform note: OCR Connector runs on Windows and macOS only. Linux is not supported yet — on Linux the call above rejects with a “not supported on this platform” error, so gate the OCR controls behind that check and keep scanning usable.

Recognize Text from a Scanned Image

The core OCR functionality lives in recognizeOnePage. Both the engine and the language come straight from the pickers:

async function recognizeOnePage(index) {
    const result = await DWTObject.Addon.OCRConnector.Recognize(index, {
        engine: { name: document.getElementById("engine").value },
        settings: { language: document.getElementById("language").value }
    });
    await saveOCRResult(result.imageID, result);
    printPrettyResult(result);
}

Key API details:

  • engine is an object. { name: "Windows.Media.Ocr" } works; a bare string is the mistake everyone makes first.
  • Language codes are BCP-47 tags, such as en-US or zh-Hans-CN — not the Tesseract-style eng / chi_sim codes from the retired OCR Basic/Pro add-ons. Read them from engines[].languages instead of hardcoding.
  • Structured results. OCRResult.blocks[].lines[].words[] each carry geometry and confidence, and result.imageID lets you cache the text against the page.
  • Region and speed options. rects limits recognition to one or more rectangles; recognitionLevel: "fast" trades accuracy for speed on macOS; settings.pageOrientation rotates the page before recognition but, like orientation detection, needs Onnx.Ocr.

Most engines fill line.value with the joined text. Fall back to the words only when it is missing, otherwise a line with punctuation comes back differently from what you see on the page:

const text = line.value || line.words.map(function (word) { return word.value; }).join(" ");

Step 4: Implement the Full OCR-to-PDF Workflow

Let’s walk through a complete document processing workflow:

Step 4.1: Scanning or Loading Images

The application provides two ways to get images into the buffer: scanning documents from a connected scanner or loading images from your local machine.

// Scan from connected device
async function acquireImage() {
    if (DWTObject) {
        DWTObject.SelectSourceAsync()
            .then(function () {
                return DWTObject.AcquireImageAsync({
                    IfCloseSourceAfterAcquire: true,
                });
            })
            .catch(function (exp) {
                alert(exp.message);
            });
    }
}

// Load from local files
function loadImage() {
    DWTObject.IfShowFileDialog = true;
    DWTObject.LoadImageEx(
        "",
        Dynamsoft.DWT.EnumDWT_ImageType.IT_ALL,
        function () {
            console.log("Image loaded successfully");
        },
        function (errorCode, errorString) {
            console.error(errorString);
        }
    );
}

Scan at 200 DPI or more. Below roughly 150 DPI the system engines start dropping characters, which is the most common cause of “OCR is inaccurate” reports that have nothing to do with the engine.

Step 4.2: Correcting Image Orientation

OCR is sensitive to character orientation. DetectPageOrientation() returns the page angle; rotate the buffer before recognition:

async function correctOrientationForOne(index) {
    // Only Onnx.Ocr detects orientation: leave the engine unset and let the
    // service pick it when it is installed.
    const result = await DWTObject.Addon.OCRConnector.DetectPageOrientation(index, {});
    const angle = (360 - (result.angle || 0)) % 360;
    if (angle) {
        DWTObject.Rotate(index, angle, true);
    }
}

Two things to get right. Rotate() takes a clockwise angle, so a detected 90° counter-clockwise page is corrected with 270°. And passing an engine explicitly only works for Onnx.Ocr — send Windows.Media.Ocr and the service answers The engine not available for action 'onnx_detect_page_orientation'. Catch that and tell the user the pack is optional rather than leaving a dead button.

Step 4.3: Performing OCR Recognition

When you click “Recognize Text”, the application calls:

async function recognize() {
    if (document.getElementById("processingTarget").value === "all") {
        let count = DWTObject.HowManyImagesInBuffer;
        for (let i = 0; i < count; i++) {
            DWTObject.SelectImages([i]);
            await recognizeOnePage(i);
        }
    } else {
        await recognizeOnePage(DWTObject.CurrentImageIndexInBuffer);
    }
}

One page or the whole buffer, it is the same call. Results are written to IndexedDB keyed by imageID, so flipping pages brings the text back without a second recognition pass.

Step 4.4: Exporting to PDF

The application exports documents to PDF with or without a text layer:

async function saveAsPDF() {
    const indices = DWTObject.SelectAllImages();
    if (!indices || indices.length === 0) {
        alert("There is no page to export.");
        return;
    }
    const withTextLayer = document.getElementById("outputFormat").value === "extralayer";
    const format = withTextLayer
        ? Dynamsoft.DWT.EnumDWT_OCRConnectorOutputFormat.PDF_WITH_EXTRA_TEXTLAYER
        : Dynamsoft.DWT.EnumDWT_OCRConnectorOutputFormat.PDF_PLAIN_TEXT;
    try {
        // A filename without a directory opens the system save dialog.
        await DWTObject.Addon.OCRConnector.SaveToPath(
            indices,
            format,
            withTextLayer ? "searchable-document.pdf" : "document-text.pdf"
        );
    } catch (error) {
        alert("Could not save the PDF: " + (error.message || error));
    }
}

PDF_WITH_EXTRA_TEXTLAYER keeps the scanned page and lays an invisible text layer over it: the document looks identical, but Ctrl+F finds words and screen readers can announce them. PDF_PLAIN_TEXT writes the recognized text alone.

For archival output, set the PDF/A version first — the same call then produces a compliant file:

DWTObject.Addon.PDF.Write.Setup({ pdfaVersion: "pdf/a-3b" }); // "" turns PDF/A off

Files come out through the local service, so nothing is uploaded on the way. Note that a searchable PDF must be loaded back through the PDF Rasterizer to be displayed again — that is a rasterizer feature, not an OCR one.

Step 5: Manage Images and OCR Results

The application provides intuitive tools for image management:

  • Remove Selected Image: Deletes the current image and its OCR results
  • Remove All Images: Clears all images and OCR data
async function removeSelectedImage() {
    let currentImageId = DWTObject.IndexToImageID(DWTObject.CurrentImageIndexInBuffer);
    DWTObject.RemoveImage(DWTObject.CurrentImageIndexInBuffer);
    await deleteOCRResult(currentImageId); // Remove from IndexedDB
    // Update UI...
}

IndexToImageID() is the bridge: the buffer index shifts when pages are deleted, but the image ID stored with the OCR result does not, so the text follows the right page.

Run the Application Locally

  1. Set the license key in the inline configuration block of index.html:

    Dynamsoft.DWT.ProductKey = "LICENSE-KEY";
    
  2. Start a web server in the project directory:

     # Using Python 3
     python -m http.server 8000
        
     # Using Node.js with http-server
     npx http-server -p 8000
    
  3. Open your web browser and navigate to http://localhost:8000. The engine and language pickers fill in as soon as the viewer is ready.

    Dynamic Web TWAIN document OCR

Key Benefits of Dynamic Web TWAIN’s OCR API for Document Workflows

Now that you’ve seen the API in action, let’s explore how it benefits document management industries:

1. Enhanced Efficiency

  • Automates data extraction from scanned documents
  • Reduces manual data entry by up to 90%
  • Accelerates document processing workflows

2. Improved Accuracy

  • Engine-aware recognition: use the OS engine that ships with the machine, or deploy a specialized ONNX model
  • Structured output with block/line/word geometry for reliable data extraction
  • Per-engine language lists instead of a hardcoded set

3. Accessibility & Searchability

  • Makes scanned documents text-searchable
  • Enables screen readers for visually impaired users
  • Facilitates text-based document analysis

4. Cost Savings

  • OCR Connector is included with Core Module 19.5+ and with trial licenses
  • No separate OCR server to license or operate
  • Reduces storage costs by enabling text compression

5. Compliance & Security

  • Recognition runs on the user’s machine; images and results are not uploaded
  • Engine choice stays under your control, so data never leaves the deployment
  • Supports regulatory requirements for document management

6. Flexible Integration

  • One Promise-based API for every engine
  • Works with existing scanning hardware, TWAIN, WIA and ICA
  • Supports PDF with a text layer, plain-text PDF and raw OCR data

Real-World Use Cases for Document Scanning and OCR

Dynamic Web TWAIN’s OCR API is transforming workflows across industries:

  • Healthcare: Automating patient record digitization and data extraction
  • Finance: Processing invoices, receipts, and financial documents
  • Legal: Digitizing contracts and case files for text search
  • Education: Converting physical documents into accessible digital formats
  • Government: Streamlining form processing and citizen services

Common Issues & Edge Cases

  • Addon.OCRConnector is undefined: the page is running a pre-19.5 JavaScript bundle, or it still loads the removed dynamsoft.webtwain.addon.ocrkit.js next to a 19.5 service. Check GetInstalledOCRInfo().version — it must report 19.5.x — and load dwt@19.5.0 (or later) only.
  • Engine list is empty, or the language you need is missing: Windows.Media.Ocr only lists languages whose OCR pack is installed. Add the language in Windows Settings → Time & language → Language & region, and include the optical character recognition feature. On older macOS releases Apple.Vision simply exposes fewer languages.
  • The engine not available for action 'onnx_detect_page_orientation': orientation detection is served by Onnx.Ocr only. Install the OCR pack, or hide the “Correct Orientation” action when no ONNX engine is reported.
  • engine passed as a string: Recognize(index, { engine: "Windows.Media.Ocr" }) raises nothing and the service falls back to its default engine, so the picker looks broken. Always pass { name }. A name the machine does not have fails loudly instead: Engine 'NoSuch.Engine' not found.
  • Garbled or missing text in OCR output: OCR accuracy degrades sharply below 150 DPI. Ensure the scanner resolution is set to at least 200 DPI in AcquireImageAsync settings. For loaded images, check the source file resolution before calling Recognize().
  • Scanning fails silently in Firefox or Safari: Dynamic Web TWAIN requires its local service daemon to be installed on the user’s machine. If the installation prompt is blocked by the browser’s popup policy, scanning will fail without a visible error. Advise users to allow popups for the domain, or display a custom installation guidance message by handling the OnWebTwainNotFound event.

Source Code

Get the complete sample project source code on GitHub