This project demonstrates how to use WebAssembly compiled from Rust to parse PDF files in the browser, with processing offloaded to Web Workers for better performance.
The PDF Parser uses Rust compiled to WebAssembly to extract text and metadata from PDF files. The heavy processing is offloaded to Web Workers to prevent blocking the main UI thread, resulting in a responsive user experience even when processing large PDF files.
The project consists of:
- Rust backend: Core PDF parsing logic compiled to WebAssembly
- Web Workers: JavaScript workers that run the WebAssembly code off the main thread
- Web frontend: Simple HTML/CSS/JS interface for file selection and result display
- lopdf: Main PDF parsing library that handles document loading and content extraction
- wasm-bindgen: Facilitates communication between Rust and JavaScript
- serde/serde_derive: Handles serialization/deserialization of Rust structs to pass data to JavaScript
- console_error_panic_hook: Provides better error messages in the browser console
Processing PDFs can be CPU-intensive, which would normally freeze the browser UI. This project offloads the processing to Web Workers:
- The main thread (
main.js) handles the UI and sends the PDF data to a worker - The worker (
worker.js) initializes the WebAssembly module and processes the PDF - Results are sent back to the main thread for display
This approach keeps the UI responsive even when parsing large documents.
- Rust and Cargo installed
- wasm-pack installed (or it will be installed by the build script)
Run the build script:
./build-wasm.shThis script:
- Checks if wasm-pack is installed and installs it if needed
- Compiles the Rust code to WebAssembly with the
no-modulestarget for Web Worker compatibility - Outputs the compiled files to
rust-pdf-parser/pkg/
- Open
index.htmlin a web browser - Drag and drop a PDF file or click "Select PDF File"
- The PDF will be processed by the Rust WebAssembly module in a Web Worker
- Metadata and extracted text will be displayed on the page
index.html: Main web interfacemain.js: Frontend JavaScript that communicates with the Web Workerworker.js: Web Worker that loads and runs the WebAssembly modulerust-pdf-parser/: Rust project containing the PDF parsing codesrc/lib.rs: Core Rust implementation for PDF parsingpkg/: Output directory for compiled WebAssembly files
Using WebAssembly + Web Workers provides:
- Native-like speed: Rust compiled to WebAssembly runs significantly faster than equivalent JavaScript
- Non-blocking UI: Processing happens in a separate thread, keeping the UI responsive
- Memory efficiency: Rust's memory management is more efficient than JavaScript for large document processing
[MIT License]