Tauri's official barcode-scanner plugin only runs on Android and iOS — it has no desktop implementation at all. If you are building a Tauri app for Windows, macOS, or Linux and need to read barcodes, the official plugin cannot help you. This tutorial builds the desktop scanner that fills that gap: a Tauri 2 app whose Rust backend decodes image files, PDFs, and a live webcam feed through FFI bindings to the Dynamsoft Barcode Reader SDK, while the UI is plain HTML/CSS/JS rendered in the system webview. The result decodes every barcode type the SDK supports, draws a quadrilateral over each one, and lists its format, text, and corner coordinates. Multi-page PDFs and TIFFs are previewed page by page, with on-screen arrows and left/right keys to switch pages.

The finished app decoding 32 ITF barcodes from a single photo:

Tauri desktop barcode scanner decoding 32 ITF barcodes with cyan bounding boxes and a results list

See it running — opening an image, decoding, and switching to the live camera:

What you'll build: A cross-platform Tauri 2 desktop barcode scanner with a Rust backend and a no-bundler web frontend. It opens images/PDFs through a native file dialog or a typed path, previews each document page with a cyan overlay on every decoded barcode, lists each barcode's format/text/coordinates, pages through multi-page PDFs and TIFFs, and streams a live webcam feed (Windows) — all powered by the same Dynamsoft Barcode Reader C++ core used by the Slint version of this sample.

The Desktop Gap in Tauri's Barcode Plugin

This is the central reason this sample exists. Tauri ships an official barcode-scanner plugin, and its name suggests it is the obvious choice for any Tauri barcode app. It is not — at least not on desktop.

The plugin's documentation describes it as a way to "allow your mobile application to use the camera to scan QR codes, EAN-13 and other kinds of barcodes." Three details in the official setup confirm the desktop gap:

  • The dependency is added only for mobile targets: cargo add tauri-plugin-barcode-scanner --target 'cfg(any(target_os = "android", target_os = "ios"))'.
  • The plugin is registered only on mobile: #[cfg(mobile)] app.handle().plugin(tauri_plugin_barcode_scanner::init());.
  • The capability that grants its permissions is scoped to mobile platforms: "platforms": ["iOS", "android"].

On Windows, macOS, and Linux there is simply no implementation to call. Beyond the platform gap, the plugin is also camera-only: it opens a native scan view (its windowed: true mode makes the webview transparent so the camera shows through) and returns what the camera sees. It does not decode a photo you already have on disk, does not read PDFs, and is not designed to return a batch of barcodes with precise corner coordinates from a still image.

This sample complements the official plugin rather than competing with it on mobile. It covers the desktop platforms the plugin leaves out, and adds the file/PDF decoding and multi-barcode coordinate output that a live mobile scan view does not provide:

Capability Official barcode-scanner plugin This Tauri + Rust sample
Windows / macOS / Linux Not supported Supported (decoding on all three)
Android / iOS Supported Not the target (use the official plugin)
Live camera scanning Yes (native mobile scan view) Yes on Windows (native Media Foundation)
Decode image files (JPEG/PNG/TIFF/BMP/GIF/WebP) No Yes
Decode PDF No Yes (every page previewed and navigable)
Multiple barcodes per image with corner coordinates Camera scan result Yes, four points per barcode
Frontend toolchain Plugin JS bindings Plain HTML/CSS/JS, no bundler

The practical takeaway: if your Tauri app targets desktop, or needs to read barcodes from files rather than only from a live mobile camera, you need a native decoding backend. The rest of this article builds one with Rust and the Dynamsoft Barcode Reader SDK, and shows how to wire it into a Tauri webview UI.

Prerequisites

  • Rust toolchain (MSVC toolchain on Windows) for the Tauri backend.
  • The WebView2 runtime on Windows (preinstalled on Windows 11); Tauri uses the system webview on macOS and Linux.
  • The Dynamsoft Barcode Reader SDK and the litecam camera library, both already vendored in the sample repository under dcv/ and litecam/dist/.
  • Get a 30-day free trial license for the Dynamsoft Barcode Reader SDK. The sample ships a shared demo key in examples/rust/src/scanner.rs; replace DEFAULT_LICENSE with your own for production.
  • Optional: Node.js only if you want the Tauri CLI (npm run dev / npm run build) for dev-server orchestration and installers. It is not needed to build or run the app.

Architecture: One Native Core, Two GUIs

The sample repository already contains a Rust CLI and a Slint desktop GUI that share a native decoding core. The Tauri app is a third frontend on that same core. Nothing about the decoding, licensing, or camera capture is rewritten — the Tauri crate literally compiles the same source files:

// src-tauri/src/main.rs #[path = "../../../src/scanner.rs"] mod scanner; #[cfg(windows)] #[path = "../../../src/camera.rs"] mod litecam; 

Only the presentation layer differs. The webview and the Rust backend talk over three channels, each suited to a different kind of traffic:

webview (ui/app.js) Rust (src-tauri/src) ─────────────────── ──────────────────── invoke("decode_path", { path }) ───────► #[tauri::command] fn decode_path ◄─────── DecodeReply (JSON) ────────┘ listen("camera-frame") ◄─────── app.emit("camera-frame", CameraFrame) <img src="media:…/preview.jpg"> ───────► register_uri_scheme_protocol("media") ◄─────── image/png bytes ──────────┘ 
  • Commands carry request/response calls: open a file, decode a path, switch pages, start/stop the camera.
  • Events carry push notifications: each camera frame and any camera error.
  • A custom URI scheme carries bulk pixels: the current page's JPEG and the live camera JPEG, served as ordinary HTTP responses instead of base64 JSON.

The project layout is small enough to read in one sitting:

tauri/ ├── ui/ # the frontend, loaded into the system webview │ ├── index.html # toolbar, preview pane, results list, status bar │ ├── style.css # the Slint look, in CSS │ └── app.js # invoke() calls, event listeners, canvas overlay └── src-tauri/ ├── Cargo.toml ├── build.rs # tauri_build + cc: links Dynamsoft/litecam, copies DLLs ├── tauri.conf.json # window, frontendDist, CSP, bundle icons ├── capabilities/ # what the webview is allowed to call ├── icons/ └── src/ ├── main.rs # Builder: state, plugin, protocol, invoke_handler ├── commands.rs # #[tauri::command] handlers + camera worker thread └── media.rs # custom media: URI scheme serving page/camera JPEG bytes 

Step 1: Scaffold the Tauri Project and Configure the Window

The crate depends on Tauri 2, the dialog plugin, serde for JSON, and the image crate for reading and re-encoding pictures. There is no frontend framework dependency:

# src-tauri/Cargo.toml [package] name = "barcode-reader-tauri" version = "0.1.0" edition = "2021" [build-dependencies] tauri-build = "2" cc = "1.0" walkdir = "2.5" [dependencies] tauri = { version = "2", features = [] } tauri-plugin-dialog = "2" serde = { version = "1", features = ["derive"] } serde_json = "1" image = { version = "0.24", default-features = false, features = [ "png", "jpeg", "tiff", "bmp", "gif", "webp", ] } 

tauri.conf.json points the webview at the static frontend, enables the global Tauri API, defines the window, and sets a Content Security Policy:

{ "$schema": "https://schema.tauri.app/config/2", "productName": "barcode-reader-tauri", "version": "0.1.0", "identifier": "com.dynamsoft.barcode-reader-tauri", "build": { "frontendDist": "../ui" }, "app": { "withGlobalTauri": true, "windows": [ { "label": "main", "title": "Dynamsoft Barcode Reader (Rust + Tauri)", "width": 1040, "height": 700, "minWidth": 760, "minHeight": 500, "center": true } ], "security": { "csp": "default-src 'self'; img-src 'self' data: blob: media: http://media.localhost; connect-src 'self' ipc: http://ipc.localhost; style-src 'self' 'unsafe-inline'; script-src 'self'" } }, "bundle": { "active": true, "targets": "all", "icon": ["icons/32x32.png", "icons/128x128.png", "icons/128x128@2x.png", "icons/icon.icns", "icons/icon.ico"] } } 

Two settings do the heavy lifting for the "no bundler" design:

  • "frontendDist": "../ui" tells Tauri to embed the static files in ui/ into the binary. There is no devUrl, so the same files are used in debug and release.
  • "withGlobalTauri": true injects Tauri's JavaScript API as window.__TAURI__, so app.js can call invoke and listen without importing npm packages.

The CSP allows the media: scheme (and its Windows form http://media.localhost) for images, and ipc: (plus http://ipc.localhost) for Tauri's own command channel. Keep these in sync with the protocol you register in Step 5, or the webview will silently block the pixels.

Step 2: Build the Native Core with build.rs

build.rs has two jobs: generate the Tauri context, and compile/link the native Dynamsoft core. The Tauri part is a single call at the end; the rest is ordinary cc + linker configuration that mirrors the Slint example's build.

On Windows the SDK ships as static import libraries plus runtime DLLs. The script links the five Dynamsoft libraries statically, links litecam dynamically, and copies every DLL next to the executable:

// src-tauri/build.rs (Windows branch) "windows" => { let lib_dir = dcv.join("lib").join("win"); println!("cargo:rustc-link-search=native={}", lib_dir.display()); for lib in [ "DynamsoftCaptureVisionRouterx64", "DynamsoftBarcodeReaderx64", "DynamsoftCorex64", "DynamsoftLicensex64", "DynamsoftUtilityx64", ] { println!("cargo:rustc-link-lib=static={lib}"); } copy_extension(&lib_dir, &bin_dir, "dll"); let cam_dir = litecam.join("lib").join("windows").join("release"); println!("cargo:rustc-link-search=native={}", cam_dir.display()); println!("cargo:rustc-link-lib=dylib=litecam"); copy_file(&cam_dir.join("litecam.dll"), &bin_dir.join("litecam.dll")); copy_resources(&dcv, &bin_dir); } 

Linux and macOS link DynamsoftBarcodeReader as a dynamic library and set an rpath so the binary finds the .so/.dylib at runtime. copy_resources copies the SDK's Templates/ and Models/ folders beside the executable, because the SDK resolves them at runtime from the module directory.

The C ABI bridge is compiled with cc and shared with the Slint example — this is the "one native core" promise made concrete:

// src-tauri/build.rs let bridge = rust_example.join("lib").join("bridge.cpp"); let camera_bridge = rust_example.join("lib").join("camera_bridge.cpp"); let mut cpp = Build::new(); cpp.cpp(true) .include(dcv.join("include")) .file(&bridge); if target_os == "windows" { cpp.include(litecam.join("include")).file(&camera_bridge); } cpp.compile("bridge"); println!("cargo:rustc-link-lib=static=bridge"); println!("cargo:rustc-link-search=native={}", env::var("OUT_DIR").unwrap()); // ... rerun-if-changed for bridge, scanner.rs, camera.rs, ../ui ... tauri_build::build(); 

Two helpers are worth copying into your own Tauri + native projects:

// src-tauri/build.rs /// `target/debug` or `target/release`, where the executable and its DLLs live. /// OUT_DIR is `<target>/<profile>/build/<pkg>-<hash>/out`. fn profile_dir() -> PathBuf { let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap()); out_dir.ancestors().nth(3).expect("unexpected OUT_DIR layout").to_path_buf() } /// Canonicalize without the `\\?\` prefix, which MSVC's linker does not accept. fn absolute(path: PathBuf) -> PathBuf { let resolved = path.canonicalize().unwrap_or(path); let text = resolved.to_string_lossy(); PathBuf::from(text.strip_prefix(r"\\?\").unwrap_or(&text).to_string()) } 

profile_dir() is how the script knows where to drop the DLLs so they sit beside the final executable. absolute() strips the Windows \\?\ verbatim prefix that canonicalize() adds, because the MSVC linker rejects it. copy_file deliberately skips a destination that already exists — a running instance keeps its DLLs locked, and the files are identical anyway.

Step 3: Reuse the FFI Decoding Wrapper

The decoding core is a flat C API over the Dynamsoft Capture Vision Router. The C++ side (lib/bridge.cpp) wraps CCaptureVisionRouter and returns malloc'd structs; the Rust side (src/scanner.rs) declares them with #[repr(C)] and frees them after copying.

The C ABI is deliberately small:

// lib/bridge.h typedef struct { const char *barcode_type; const char *barcode_value; int x1, y1, x2, y2, x3, y3, x4, y4; } Barcode; typedef struct { Barcode *barcodes; int count; } BarcodeResults; typedef struct { int width; int height; unsigned char *rgb; // width * height * 3, RGB888 int rgb_length; Barcode *barcodes; // barcodes on this page; NULL when count is 0 int count; } PageResult; typedef struct { PageResult *pages; int count; } PageResults; BarcodeResults *decode_barcode_file(void *instance, const char *filename); PageResults *decode_barcode_file_pages(void *instance, const char *filename); BarcodeResults *decode_barcode_buffer(void *instance, const unsigned char *bytes, int width, int height, int stride); void free_barcode(BarcodeResults *results); void free_page_results(PageResults *results); int init_license(const char *license); void *CVR_CreateInstance(); void CVR_DestroyInstance(void *instance); 

The buffer entry point is the one that matters for coordinate alignment. It wraps the raw bytes in a CImageData tagged IPF_RGB_888 and captures with the read-barcodes preset:

// lib/bridge.cpp BarcodeResults *decode_barcode_buffer(void *instance, const unsigned char *bytes, int width, int height, int stride) { CCaptureVisionRouter *cvr = (CCaptureVisionRouter *)instance; CImageData image((unsigned long long)stride * height, bytes, width, height, stride, IPF_RGB_888); CCapturedResult *result = cvr->Capture(&image, CPresetTemplate::PT_READ_BARCODES); return extract_barcodes(result); } 

Two file entry points sit on the bridge. decode_barcode_file is the flat API used by the CLI and Slint UI: it calls CaptureMultiPages and concatenates every page's barcodes into one list. The Tauri GUI uses decode_barcode_file_pages because it also needs the pixels of each page for the preview.

The router does not keep page pixels around by default — GetOriginalImage returns NULL unless the original image was cached — and CaptureMultiPages only hands back decoded items. The SDK's CFileFetcher is the documented tool for this job: it partitions a multi-page PDF or TIFF into one CImageData per page. The bridge loops over those page bitmaps, copies each into RGB888, and decodes that exact bitmap with Capture():

// lib/bridge.cpp PageResults *decode_barcode_file_pages(void *instance, const char *filename) { CCaptureVisionRouter *cvr = (CCaptureVisionRouter *)instance; // CFileFetcher splits a multi-page PDF or TIFF into one CImageData per page. CFileFetcher fetcher; if (fetcher.SetFile(filename) != EC_OK) { return NULL; } std::vector<PageResult> pages; while (fetcher.HasNextImageToFetch()) { CImageData *image = fetcher.GetImage(); if (!image) { break; } PageResult page; page.rgb = image_to_rgb(image, &page.rgb_length); // stride-aware RGB888 copy page.width = page.rgb ? image->GetWidth() : 0; page.height = page.rgb ? image->GetHeight() : 0; page.barcodes = NULL; page.count = 0; // Decode the very bitmap the GUI will preview. CCapturedResult *result = cvr->Capture(image, CPresetTemplate::PT_READ_BARCODES); if (result) { if (result->GetErrorCode() == 0) { CDecodedBarcodesResult *barcodeResult = result->GetDecodedBarcodesResult(); std::vector<Barcode> items; append_barcode_items(barcodeResult, items); if (barcodeResult) { barcodeResult->Release(); } if (!items.empty()) { page.count = (int)items.size(); page.barcodes = (Barcode *)std::malloc(sizeof(Barcode) * items.size()); for (size_t i = 0; i < items.size(); i++) { page.barcodes[i] = items[i]; } } } result->Release(); } // Keep pages that have pixels even when they contain no barcode. if (page.rgb || page.count > 0) { pages.push_back(page); } else if (page.barcodes) { std::free(page.barcodes); } } if (pages.empty()) { return NULL; } PageResults *results = (PageResults *)std::malloc(sizeof(PageResults)); results->count = (int)pages.size(); results->pages = (PageResult *)std::malloc(sizeof(PageResult) * pages.size()); for (size_t i = 0; i < pages.size(); i++) { results->pages[i] = pages[i]; } return results; } Source:https://dev.to/yushulx/how-to-build-a-desktop-barcode-scanner-with-tauri-and-rust-5d4p

Related posts