Modern printer companion apps have turned one of the simplest hardware tasks into an obstacle course. Even when a flatbed scanner is sitting two feet away on your own local network, suites like HP Smart routinely gate basic printing and scanning behind mandatory cloud accounts, background telemetry, heavy web wrappers, and vendor lock-in.
I wanted a fast, zero-account tool that treats local hardware like local hardware. So I built AlPrint: an offline-first, vendor-agnostic printing and scanning studio for Windows Desktop and Android Mobile that talks directly to printers and scanners over standard OS and LAN protocols (WIA 2.0, Windows Print Spooler, driverless eSCL / AirScan, IPP / Mopria, mDNS / NSD, and UDP SNMPv1).
Alongside core scan-and-print workflows, AlPrint includes the power-user tools OEM apps omit or paywall: guided manual 2-pass duplexing with automatic odd-sheet blank-page padding, 2-step ID card front+back stitching, multi-item receipt splitting, book-spread splitting, non-destructive editing, offline OCR searchable PDFs, and 1-tap shortcuts.
1. Dual-Platform System Architecture
AlPrint is structured as a dual-platform monorepo pairing a Tauri v2 (Rust + React/TypeScript) desktop studio at the root with a Native Kotlin + Jetpack Compose Android app inside mobile/.
Desktop & Mobile Data Flow
- Desktop (
Tauri v2): React views invoke typed Rust commands over Tauri IPC. Every scan is stored non-destructively as paired*_orig.pngand*_edit.pngfiles so rotation, crop, tone adjustments, and markup can always be recomputed from the untouched original. Multi-page PDF previews are rasterized offline withpdfjs-dist, and searchable PDFs embed invisible OCR word bounding boxes viapdf-libusingWindows.Media.Ocr. - Mobile (
Kotlin + Compose):MainActivity.kthandles both direct launches and Android Share Sheet intents (ACTION_SEND,ACTION_SEND_MULTIPLE,ACTION_VIEW). Captures from ML Kit Document Scanner, Wi-Fi eSCL flatbeds, or local files live inside a process-scopedAlPrintSessionStore, run heavy image and PDF passes onDispatchers.Default/Dispatchers.IO, and spool natively through Android'sPrintManager(PrintDocumentAdapter).
2. Driverless Wi-Fi Flatbed Scanning (eSCL / AirScan)
On Android, you don't get a system-wide flatbed scanner daemon like Windows WIA. Instead of bundling proprietary OEM SDKs, I built a zero-dependency eSCL (AirScan) client in Kotlin (NetworkPrinterService.kt) on top of HttpURLConnection and XmlPullParser:
- Discovers
_uscan._tcp.and_ipp._tcp.services on the LAN via Android'sNsdManager. - Queries
/eSCL/ScannerCapabilitiesto read supported DPIs, color modes, and platen dimensions. - Polls
/eSCL/ScannerStatusand sendsDELETEto clear any leftover stuck jobs on the printer's embedded web server. - Posts a
ScanSettingsXML payload usingThreeHundredthsOfInchesscan regions (A4,Letter,4×6",5×7",ID Card, orFull Glass) to/eSCL/ScanJobsand streams raw JPEG or PDF bytes back from/NextDocument.
3. Pure-Rust UDP SNMPv1 Telemetry
Both apps check live ink and supply status directly on the local network without touching any vendor cloud. Rather than pulling in C SNMP libraries or external tools on Windows, src-tauri/src/devices.rs hand-encodes ASN.1/BER TLV packets (0x30, 0xA0, 0x06, 0x02) over a raw std::net::UdpSocket to port 161, querying prtMarkerSuppliesTable (1.3.6.1.2.1.43.11.1.1.{6,8,9}.1.<idx>).
On continuous ink-tank printers like the HP Smart Tank 580, firmware often reports cryptic placeholder strings such as "tri-color ink cartridge HP unknown" with MaxCapacity = 0, so the Rust telemetry layer also normalizes those descriptions into readable ink tank labels:
fn query_printer_mib_supplies(ip: &str) -> Vec<SupplyLevel> {
let target = format!("{ip}:161");
let socket = match UdpSocket::bind("0.0.0.0:0") {
Ok(s) => s,
Err(_) => return Vec::new(),
};
let _ = socket.set_read_timeout(Some(Duration::from_millis(750)));
let _ = socket.set_write_timeout(Some(Duration::from_millis(750)));
let mut supplies = Vec::new();
for idx in 1u32..=6 {
let desc_oid = [1, 3, 6, 1, 2, 1, 43, 11, 1, 1, 6, 1, idx];
let max_oid = [1, 3, 6, 1, 2, 1, 43, 11, 1, 1, 8, 1, idx];
let lvl_oid = [1, 3, 6, 1, 2, 1, 43, 11, 1, 1, 9, 1, idx];
let desc_raw = match snmp_get(&socket, &target, &desc_oid, 100 + idx * 3) {
Some(SnmpVal::Str(s)) if !s.trim().is_empty() => s.trim().to_string(),
_ => break,
};
let max_cap = match snmp_get(&socket, &target, &max_oid, 101 + idx * 3) {
Some(SnmpVal::Int(v)) => v,
_ => -1,
};
let raw_lvl = match snmp_get(&socket, &target, &lvl_oid, 102 + idx * 3) {
Some(SnmpVal::Int(v)) => v,
_ => -1,
};
let level_percent = if max_cap > 0 && raw_lvl >= 0 {
Some(((raw_lvl as f64 / max_cap as f64) * 100.0).round().clamp(0.0, 100.0) as i32)
} else {
None
};
// Clean up HP Smart Tank firmware strings like "tri-color ink cartridge HP unknown"
let desc = clean_supply_description(&desc_raw, max_cap);
let color = infer_supply_color(&desc_raw);
supplies.push(SupplyLevel {
name: desc,
color,
level_percent,
raw_level: raw_lvl,
max_capacity: max_cap,
});
}
supplies
}
fn clean_supply_description(raw: &str, max_cap: i32) -> String {
let low = raw.to_ascii_lowercase();
if low.contains("unknown") && max_cap <= 0 {
if low.contains("tri-color") || low.contains("color") {
return "Tri-Color Ink Tank (C/M/Y)".to_string();
} else if low.contains("black") {
return "Black Ink Tank (K)".to_string();
}
}
raw.replace("HP unknown", "")
.replace("unknown", "")
.trim()
.to_string()
}4. Power-User Workflows & Non-Destructive Editing
Guided Manual 2-Pass Duplex With Odd-Sheet Padding
Entry-level ink-tank printers don't have automatic duplexers. When printing multi-page documents two-sided, both Desktop and Mobile first compose N-up sheets (1 / 2 / 4 pages per sheet), split them into Pass 1 (odd front sheets) and Pass 2 (even back sheets), and automatically append a blank white sheet to Pass 2 whenever the total sheet count is odd:
/**
* Splits composed sheets into Pass 1 (odd sheets: 1, 3, 5...) and Pass 2 (even sheets: 2, 4, 6...).
* When total sheets is odd (e.g. 1 or 3), automatically appends a blank white sheet to Pass 2
* so the user never has to figure out which sheet stays unprinted when flipping the stack!
*/
fun splitManualDuplexPasses(sheets: List<Bitmap>): Pair<List<Bitmap>, List<Bitmap>> {
val pass1Odd = mutableListOf<Bitmap>()
val pass2Even = mutableListOf<Bitmap>()
sheets.forEachIndexed { idx, sheet ->
if (idx % 2 == 0) {
pass1Odd.add(sheet)
} else {
pass2Even.add(sheet)
}
}
if (sheets.size % 2 == 1 && sheets.isNotEmpty()) {
val sample = sheets.first()
val blankBack = Bitmap.createBitmap(sample.width, sample.height, Bitmap.Config.ARGB_8888)
Canvas(blankBack).drawColor(Color.WHITE)
pass2Even.add(blankBack)
}
return Pair(pass1Odd, pass2Even)
}That single detail means you never have to pull the last sheet off the tray before flipping the stack—you just flip the entire Pass 1 output and hit Print on Pass 2.
Rotation-First Pipeline & Adaptive Crop Editor
Both backends (image_ops.rs in Rust and ImageProcessor.kt in Kotlin) execute edits strictly in Rotation → Crop → Filter/Tone → Markup order so cropping a rotated page operates in the exact coordinate frame shown on screen. On Android, PageEditorDialog.kt adapts dynamically between a vertical stack in Portrait and a side-by-side workspace in Landscape (weight(1f) full-height canvas beside a 280dp inspector sidebar) with screen-pixel hit-testing across corners, midpoints, and edges.
5. Engineering Failures, Roadblocks & Pivots
HP eSCL .local mDNS Location Header & Embedded Server Deadlock
- What failed: On the very first Android test against the HP Smart Tank 580, the scanner physically swept the glass, then the app froze indefinitely on
"Scanning from Flatbed (192.168.0.58)...". Worse, every follow-up request—evencurl http://192.168.0.58/eSCL/ScannerStatusand Windows WIA—timed out with:
curl: (28) Operation timed out after 10008 milliseconds with 0 bytes received
- Root cause: HP's eSCL firmware returns a
Locationheader pointing to its.localmDNS hostname (e.g.,http://HP91C060.local/eSCL/ScanJobs/<id>). Windows resolves.localtransparently, whereas Android'sHttpURLConnectionthrowsUnknownHostException. Leaving the initialPOSTconnection open withKeep-Alivesimultaneously starved the printer's small lwIP HTTP worker pool until the hardware was power-cycled. Sending<pwg:Version>2.6</pwg:Version>also caused the firmware to reject scan jobs outright. - The fix: Restored
<pwg:Version>2.0</pwg:Version>, forcedConnection: closeon the job creation connection, cleared stale jobs automatically viaDELETE, and addedresolveEsclJobUrl()to rewrite.localhosts back to the verified IPv4 address while preserving explicit ports:
fun resolveEsclJobUrl(baseEsclUrl: String, locationHeader: String): String {
val cleanBase = normalizeEsclBase(baseEsclUrl).trimEnd('/')
val baseParsed = runCatching { URL(cleanBase) }.getOrNull()
val targetHost = baseParsed?.host ?: baseEsclUrl.trim()
.removePrefix("http://")
.removePrefix("https://")
.substringBefore("/")
.substringBefore(":")
val baseScheme = baseParsed?.protocol ?: "http"
val hostRoot = cleanBase.substringBefore("/eSCL").trimEnd('/')
val trimmedLoc = locationHeader.trim().trimEnd('/')
if (trimmedLoc.startsWith("http://", ignoreCase = true) ||
trimmedLoc.startsWith("https://", ignoreCase = true)
) {
val locParsed = runCatching { URL(trimmedLoc) }.getOrNull()
if (locParsed != null) {
val scheme = locParsed.protocol.ifBlank { baseScheme }
val portPart = if (locParsed.port > 0 && locParsed.port != 80 && locParsed.port != 443) {
":${locParsed.port}"
} else if (baseParsed != null && baseParsed.port > 0 && baseParsed.port != 80 && baseParsed.port != 443) {
":${baseParsed.port}"
} else {
""
}
val rawPath = locParsed.path.trimEnd('/')
val finalPath = if (rawPath.contains("/eSCL/", ignoreCase = true) ||
rawPath.startsWith("/eSCL", ignoreCase = true)
) {
rawPath
} else {
"/eSCL/${rawPath.trimStart('/')}"
}
return "$scheme://$targetHost$portPart$finalPath"
}
}
// Relative Location header
val esclIdx = trimmedLoc.indexOf("/eSCL/", ignoreCase = true)
if (esclIdx >= 0) {
return "$hostRoot${trimmedLoc.substring(esclIdx)}"
}
return when {
trimmedLoc.startsWith("/") -> "$hostRoot$trimmedLoc"
else -> "$cleanBase/${trimmedLoc.trimStart('/')}"
}
}Even after resolving the job URL, embedded printer HTTP servers sometimes hold the /NextDocument socket open after transmitting the final byte. To avoid hanging for a 45-second socket read timeout, readEsclDocumentStream() inspects incoming chunks for the JPEG End-Of-Image marker (0xFF 0xD9) and verifies the image header/dimensions so the UI finishes the instant the scan bytes arrive:
private fun readEsclDocumentStream(
conn: HttpURLConnection,
onBytesProgress: (Int) -> Unit
): ByteArray {
val out = java.io.ByteArrayOutputStream(256 * 1024)
val contentLen = conn.contentLength
try {
conn.inputStream.use { input ->
val buf = ByteArray(16 * 1024)
var lastProgressReport = 0
while (true) {
val n = try {
input.read(buf)
} catch (timeoutEx: java.net.SocketTimeoutException) {
// If the socket timed out AFTER we already received a valid image payload, return what we have!
if (out.size() > 4096) break else throw timeoutEx
}
if (n < 0) break
if (n > 0) {
out.write(buf, 0, n)
val currentSize = out.size()
if (currentSize - lastProgressReport >= 64 * 1024) {
lastProgressReport = currentSize
onBytesProgress(currentSize)
}
if (contentLen > 0 && currentSize >= contentLen) {
break
}
// Check for JPEG End-Of-Image marker (0xFF, 0xD9) at the end of a chunk when no more bytes are queued
if (contentLen <= 0 && currentSize > 4096 && n >= 2) {
val b1 = buf[n - 2]
val b2 = buf[n - 1]
if (b1 == 0xFF.toByte() && b2 == 0xD9.toByte()) {
val snapshot = out.toByteArray()
if (snapshot.size >= 4 &&
snapshot[0] == 0xFF.toByte() &&
snapshot[1] == 0xD8.toByte()
) {
// Verify it decodes cleanly as a complete JPEG
val opts = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeByteArray(snapshot, 0, snapshot.size, opts)
if (opts.outWidth > 0 && opts.outHeight > 0) {
return snapshot
}
}
}
}
}
}
}
} catch (_: Exception) {
if (out.size() <= 4096) throw IllegalStateException("Interrupted while streaming image from scanner")
}
return out.toByteArray()
}Jetpack Compose pointerInput Stale Closure on Crop Dragging
Dragging any handle or gridline on the mobile crop box initially jittered by 1 pixel and snapped straight back. Because pointerInput(activeTab, cropEnabled) captured cropRect by value at initial composition, every onDrag callback added a 1-frame delta onto the stale initial rectangle instead of accumulating. Wrapping live state with rememberUpdatedState(cropRect) and switching to pixel-space hitTestCropHandlePx() (36dp corner radius, 28dp edge-line tolerance) made dragging immediate and exact.
Desktop Rotate Button "Wiggle" & Backwards Spin
Clicking Rotate on Desktop caused the image to spin +90°, snap to the newly rotated PNG, and visibly unwind -90° while the toolbar jittered horizontally. transition-transform duration-150 was still active when optimisticRotateDeg reset from 90deg back to 0deg after the Rust backend returned, and the button text toggled between "Rotate" and "Rotating...". Resetting transform: rotate(0deg) with transition: none inside the <img> onLoad callback—the exact frame the rotated PNG decodes—fixing the button width, and tracking monotonic visualRotateDeg in PageEditorModal.tsx (so 270° → 360° rotates forward instead of unwinding -270°) eliminated the glitch.
Android Rotation State Loss & Toolchain Gotchas
- Rotation & Layout: Rotating the phone initially destroyed
MainActivityand wiped active scans, while Landscape stacked controls into a~60dpcanvas strip and squeezed unscrollable chip rows into tiny vertical slivers. Addingandroid:configChanges+singleTopinAndroidManifest.xml, hoisting workspace state intoAlPrintSessionStore, and building a dedicated Landscape side-by-side layout inPageEditorDialog.ktresolved all three. - Android SDK 37 & Missing
NA_5X7:androidx.lifecycle:lifecycle-runtime-compose-android:2.11.0-rc01failed compilation untilcompileSdkwas bumped from36to37, and Android'sPrintAttributes.MediaSizelacked a built-inNA_5X7constant—requiring an explicit mil-basedPrintAttributes.MediaSize("NA_5X7", "5x7 in", 5000, 7000). - License Pivot: Rebuilt the repository cleanly from MIT → Apache 2.0 → GNU GPLv3 so derivative builds must remain open source.
6. Hardware Validation & Release Footprints
Every release build was validated end-to-end against physical hardware rather than mocks:
- HP Smart Tank 580-590 series (
HP91C060, Wi-Fi IPv4192.168.0.58across TCP ports80 / 443 / 631 / 3910 / 3911 / 8080 / 9100+ UDP161, and USBUSB001). - Physical Android smartphone (Wi-Fi 6 LAN eSCL scanning, ML Kit camera scanning, Android
PrintManagerspooling, portrait/landscape orientation switching). - Windows x64 PC (WIA 2.0 / WSD flatbed scanning, Windows Print Spooler, offline
Windows.Media.Ocr).
v0.1.0 Release Artifacts
| Target Artifact | Platform | Binary Size | Exact Bytes |
|---|---|---|---|
AlPrint_0.1.0_x64-setup.exe | Windows NSIS Installer | 5.79 MiB | 6,071,384 |
AlPrint_0.1.0_x64_en-US.msi | Windows MSI Installer | 8.20 MiB | 8,593,408 |
AlPrint-0.1.0-portable-x64.exe | Windows Portable EXE | 23.27 MiB | 24,398,848 |
AlPrint-Android-0.1.0.apk | Android APK (bundled ML Kit OCR) | 60.70 MiB | 63,645,481 |
Automated checks pass across the stack: TypeScript strict checking (tsc --noEmit), Vite production bundling (1,786 modules built in 5.2s), Rust release builds + cargo test, and Android JUnit suites (ImageProcessorTest.kt covering Otsu thresholding, edge detection, page-range parsing, paper aspect ratios, eSCL .local URL rewriting, and scan region math).
7. Open Source Release
AlPrint is released as free software under the GNU General Public License v3.0 (GPL-3.0):
- Source Code: github.com/TheChos3nOne/AlPrint
- Downloads (
v0.1.0): Windows installers (.exe/.msi), portable build, and Android.apkare published on GitHub Releases.
