Skip to content
abhishek-rajPublic

About

Print to a host-based HP inkjet from Android — HPLIP's hpcups ported to the NDK, over TCP 9100 or USB.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

13 Commits

Folders and files

Repository files navigation

PrnPrint

Print from Android to a host-based HP inkjet that has no network print support of its own.

PrnPrint renders PDFs and images on the phone, converts them to the printer's native PCL3GUI2 data stream using a port of HPLIP's hpcups driver to the Android NDK, and sends the result over RAW/JetDirect (TCP 9100) or a USB cable.

Why this exists

The HP Ink Tank 310 — like most cheap inkjets — is a host-based printer. It has no PostScript or PCL interpreter inside it. The computer is expected to do all the rasterising and halftoning and send the printer a stream of ready-to-fire nozzle commands. On Linux that work is done by CUPS calling HPLIP's hpcups filter.

Android has no CUPS. So when such a printer is hung off a router's USB port and shared over JetDirect, Android's built-in printing cannot drive it: there is nothing on either end that can turn a document into something the printer understands.

PrnPrint puts the missing piece on the phone. The vendored hpcups sources are compiled unmodified and called in-process through JNI, so the phone produces the same bytes a Linux box would.

How it works

PDF or image
    |
    |  PdfRenderer / ImageDecoder          (Android platform)
    v
ARGB_8888 bitmap, rendered in 256-row strips
    |
    |  CupsRasterWriter                    (Kotlin, print-core)
    v
CUPS raster v3 stream  (4-byte sync word + 1796-byte page header + RGBW pixels)
    |
    |  hpcups via JNI                      (C++, native)
    v
PRN  (PJL preamble + PCL3GUI2 raster commands)
    |
    |  RawPrintClient (TCP 9100)  or  UsbPrintClient (USB printer class)
    v
Printer

A4 at 600 dpi is 4818 x 6877 pixels — 126.4 MiB per page as uncompressed RGBW. That never fits in an app heap, so pages are rendered and fed to the encoder in horizontal strips rather than as a whole bitmap.

The raster header is written by hand in Kotlin rather than by Ghostscript, and is verified byte-for-byte against a header captured from a real CUPS pipeline.

Status

Area State
PDF printing over TCP 9100 Working, validated on paper
Image printing Built, validated in the pipeline
System print service (print from any app) Built, not yet exercised on paper
USB printing Working, tested on hardware
Multi-page documents Per-page path built, only ever run with one page
Paper sizes A4 only

This is a working tool for one printer, not a general Android print stack. See Using a different printer.

Requirements

  • Android Studio with NDK 27.2.12479018 and CMake 3.22.1 — or, to build on the phone itself, Termux (see Building on the phone (Termux))
  • JDK 11 or newer (Android Studio's bundled JBR works)
  • A device or emulator on API 29+
  • WSL or a Linux box, only if you want to regenerate test fixtures or run the host-side validation tools

Toolchain versions are pinned in android/gradle/libs.versions.toml: AGP 9.3.1, Gradle 9.5.0, Kotlin 2.2.10. Builds target arm64-v8a, armeabi-v7a, x86 and x86_64.

Building

hpcups vendors two JPEG internals that need libjpeg-turbo's private headers, and libjpeg-turbo's build system refuses to be consumed via add_subdirectory or FetchContent. So it is built once per ABI and staged as a static library before the first Gradle build:

.\tools\build-libjpeg-android.ps1      # Windows
bash tools/build-libjpeg-android.sh    # Linux, macOS, Termux (optionally: arm64-v8a ...)

Either script fetches libjpeg-turbo 3.0.4 and installs to android/native/src/main/cpp/prebuilt/<abi>/. CMake fails with an explicit message if this step is skipped. The bash script uses the SDK's CMake if present, otherwise the one on PATH, and reads the SDK location from ANDROID_HOME.

Then:

cd android
$env:JAVA_HOME = "C:\Program Files\Android\Android Studio\jbr"
.\gradlew.bat :app:installDebug

Building on the phone (Termux)

The app also builds, installs and debugs on an arm64 phone with no PC, using Termux. Set up the SDK, Gradle and adb-to-self with termux-android-dev. The NDK needs extra steps, because Google ships it for x86-64 hosts only:

  1. Install NDK 27.2.12479018 into $ANDROID_HOME/ndk/ and replace the binaries in toolchains/llvm/prebuilt/linux-x86_64/bin with an aarch64 build of the same toolchain (for example from android-ndk-custom).
  2. CMake reports Termux as an Android host, which the NDK toolchain files reject. In build/cmake/android.toolchain.cmake and android-legacy.toolchain.cmake, treat CMAKE_HOST_SYSTEM_NAME STREQUAL Android like Linux.
  3. pkg install cmake ninja, then symlink cmake, ctest, cpack and ninja into $ANDROID_HOME/cmake/3.22.1/bin/. CMake 4.x works in place of 3.22.1.
  4. Create android/local.properties with sdk.dir=$ANDROID_HOME.

Phones have little memory to spare, and Android kills Termux if a build takes too much. Build one ABI with a single worker:

bash tools/build-libjpeg-android.sh arm64-v8a
cd android
termux-wake-lock
./gradlew :app:installDebug --max-workers=1 \
  -Pandroid.injected.build.abi=arm64-v8a \
  -Pkotlin.compiler.execution.strategy=in-process \
  -Dorg.gradle.jvmargs=-Xmx1536m

With android.injected.build.abi set, the APK is written to app/build/intermediates/apk/debug/ instead of app/build/outputs/apk/debug/.

Using it

There are three ways in:

The app. Pick a PDF or image, set the printer address, press Print.

The share sheet. Any app holding a PDF or image can share it to PrnPrint.

The system print dialog. Enable PrnPrint in Android's print settings (the path varies by vendor — search Settings for "Printing"), and it appears as a printer in any app's print dialog. Android renders every document to PDF before handing it to a print service, so this covers Chrome, Gmail, the gallery, Office and anything else with a print button, with no per-format code.

Settings

Most of these knobs exist because of the print server, not the printer.

  • Print over USB cable — bypasses the network path entirely. Requires an OTG adapter. Permission must be granted in the app before the system print service can use it, because a print service runs headless and has nowhere to prompt from.
  • Detail — renders at 1/N and upscales without smoothing before rasterising. This is the effective lever on output size: PRN size is driven by source detail, not page size. Measured on identical 132 MB rasters, a coarse image produced a 62 KB PRN and a fine one 1.4 MB — a 23x difference. Raise this when a page is too heavy to get through.
  • Send speed — throttles the TCP write. Useful for print servers that accept data faster than the printer drains it.
  • Spool pages on this phone — sends one connection per page instead of one for the whole document, bounding how much the print server has to buffer.

Notes on cheap print servers

A router's USB print server is usually a small daemon with a fixed buffer and a watchdog. Two distinct failure modes turned up while building this, and the mitigations for them are why the code looks the way it does:

  • Spool overrun. The server accepts data far faster than the printer consumes it. Past a few megabytes on one connection it stops responding. Mitigation: one connection per page, drained to EOF before the next.
  • Cold-start stall. A printer waking from idle accepts nothing for several seconds. The server blocks on its USB write and its watchdog takes the whole router down. Mitigation: RawPrintClient.warmUp() sends a PJL-comment-only job that marks no paper, then waits, so the wake happens on a job that costs nothing.

tools/Test-RawPort.ps1 probes a print server in a couple of seconds without using ink, and tells a wedged server apart from a client bug. It is worth running before blaming the app.

If your print server is healthy, none of this will matter to you. Printing over USB sidesteps the print server altogether, and is the more reliable path if you have an OTG adapter to hand.

Repository layout

android/
  app/            Compose UI, foreground print job service, system print service
  print-core/     Rendering and transport. The interesting module.
  native/         hpcups + CUPS shim + JNI bridge
tools/            Host-side build, capture and validation scripts

print-core

File Role
CupsRaster.kt PageGeometry and the hand-built 1796-byte CUPS raster header
PdfRasterizer.kt Renders PDF pages in strips; implements the detail reduction
ImageToPdf.kt Wraps an image in a one-page PDF so images reuse the PDF path
PrintPipeline.kt Orchestrates render → raster → hpcups → transmit
PrintTransport.kt The interface both transports implement
RawPrintClient.kt TCP 9100, with throttling, retry, warm-up and a stall watchdog
UsbPrintClient.kt USB printer class, bulk-OUT endpoint

native

src/main/cpp/hpcups/ holds the vendored HPLIP sources, compiled unmodified. Keeping them byte-identical to upstream is deliberate: it is what allows the output to be diffed against the distribution's own hpcups binary as a correctness oracle.

src/main/cpp/shim/ is a clean-room reimplementation of just enough of the CUPS raster and PPD APIs for hpcups to link — a PPD attribute reader and a raster v3 reader/writer. Linking real libcups would drag in dbus, krb5, gnutls, systemd and avahi, none of which exist on Android. The shim rejects raster versions 1 and 2 outright rather than half-implement their compression, so a wrong assumption fails loudly instead of quietly printing garbage.

src/main/cpp/jni/ calls HPCupsFilter::StartPrintJob() in-process with file descriptors 0 and 1 temporarily redirected, rather than forking a filter binary. hpcups is not reentrant, so calls are serialised on a mutex.

Testing

cd android
.\gradlew.bat :native:connectedDebugAndroidTest :print-core:connectedDebugAndroidTest
Test What it proves
HpcupsBridgeTest The on-device encoder is byte-identical to the Linux hpcups binary. Feeds a captured 132 MB raster through JNI and compares the SHA-256 of the output, ignoring only the PJL preamble's hostname and timestamp.
CupsRasterWriterTest The hand-written raster header matches one captured from a real CUPS pipeline, byte for byte.
PrintPipelineTest A synthetic PDF makes it end to end and produces a structurally valid PRN.
RealPrinterTest Prints a page on actual hardware. Skips itself unless given -Pandroid.testInstrumentationRunnerArguments.printerHost=<ip>.

The first two are the load-bearing ones. Everything below the JNI boundary is verified against the reference implementation rather than against expectations.

Note that the instrumentation harness frequently exits non-zero for reasons unrelated to the tests. Read the XML reports under <module>/build/outputs/androidTest-results/ rather than trusting the exit code.

Using a different printer

Less work than it looks, because nothing below the JNI boundary is model-specific. The PPD parser is a generic keyword scanner, and the encoder is chosen at runtime from the PPD's *hpPrinterLanguage value. Twelve encoder families are compiled in — pcl3, pcl3gui, pcl3gui2, ljmono, ljcolor, ljfastraster, ljjetready, ljzjstream, ljzxstream, lidil, hbpl1, quickconnect — which is essentially all of hpcups.

What is hard-coded is on the Kotlin side:

  1. PrintPipeline.PPD_ASSET names a single bundled PPD.
  2. PageGeometry.A4_600 is the only geometry that exists.

For a new paper size or printer you need a PageGeometry. Most of it can be read straight out of the PPD: mediaId is cupsInteger0 on the *PageSize line, mediaSubtype is cupsInteger6 on the *MediaType line, and page dimensions and margins are stated directly. Only widthPx/heightPx need capturing, because they are Ghostscript's own rounding result and differ slightly from the PPD's stated imageable area. Run gstoraster on a host with the target PPD and read them off with tools/dump-raster-header.sh.

One hard limit: HPLIP ships a closed-source libImageProcessor blob, built only for x86 Linux, which this project compiles out. Printers whose HPLIP model entry has plugin=1 cannot be supported at all — there is no ARM build of that blob and no source to port. Check plugin= in HPLIP's models.dat before assuming a model will work.

Limitations

  • A4 only. Other sizes need a captured and validated PageGeometry.
  • 600 dpi. The PPD's floor is 600x600; there is no draft mode to fall back to.
  • Multi-page is unexercised. The per-page loop has only ever run once.
  • Colour reduction does not help. Forcing ColorModel=KGray was measured to change PRN size by 10 bytes out of 433 KB. There is no driver-level lever for heavy pages; reduce detail instead.
  • Unsigned debug builds only. No release signing config is present.

Licensing

PrnPrint is released under GPL-2.0-or-later — see LICENSE.

That is not a free choice. The vendored HPLIP code is a mix of licences, and two of the files compiled into libprnprint.so are GPL-2+, so the linked work as a whole must be too. Every other component is GPL-compatible, so this is a clean outcome rather than a conflict.

The authoritative per-file breakdown is Debian/Ubuntu's copyright audit of the exact release this code came from, HPLIP 3.23.12, readable at /usr/share/doc/hplip/copyright on any machine with HPLIP installed:

Component Upstream path Licence
native/.../hpcups/* (111 files) prnt/hpcups/* BSD-3-Clause, © 1996–2015 HP Co.
native/.../hpcups/jccolor.c prnt/hpcups/jccolor.c Independent JPEG Group
native/.../hpcups/jdatadbf.c prnt/hpcups/jdatadbf.c GPL-2+ — explicit stanza in the audit
native/.../common/utils.c common/utils.c GPL-2+ — falls under the Files: * catch-all
native/.../hpmud/hpmud.h io/hpmud/* MIT (Expat)
print-core/.../inktank310.ppd ppd/* GPL-2+ (Files: *)
native/.../shim/*, jni/*, all Kotlin — Original to this project
libjpeg-turbo — BSD-3-Clause; fetched at build time, not redistributed

Full attributions and licence texts are in THIRD-PARTY-NOTICES.md.

Files original to this project carry SPDX-License-Identifier: GPL-2.0-or-later. The vendored HPLIP sources are left byte-identical to upstream, headers included — that is what keeps tools/compare-hpcups.py meaningful as a correctness oracle.

Could this be permissively licensed?

Not as it stands, and not by a fork alone. Two separate things would each have to change.

1. The vendored GPL-2+ files would have to go. Both are removable in principle:

  • hpcups/jdatadbf.c provides jpeg_buffer_dest, used only by ModeJpeg.cpp. This printer encodes with Mode9/Mode10 via Pcl3Gui2 and never touches the JPEG path, so dropping both files from CMakeLists.txt costs nothing here — though it would remove JPEG-mode support for other HP models.
  • common/utils.c is harder: eight hpcups sources include common/utils.h. Its functions are plugin loading (already compiled out via DISABLE_IMAGEPROCESSOR), /etc/hp config parsing (meaningless on Android), createTempFile and getHPLogLevel. A clean-room reimplementation behind the existing header is realistic — the same approach already taken for the CUPS shim — but it is real work and needs care to stay genuinely independent.

The bundled PPD is GPL-2+ as well, so a permissive build would also have to ship without it and have users supply their own.

2. The copyright holder would have to relicense this project's own code. The Kotlin sources, the CUPS shim and the JNI bridge are all marked GPL-2.0-or-later. Removing HP's GPL files does not change that; only the copyright holder can. If you want permissively licensed derivatives, open an issue rather than assuming a fork is enough.

For context: with both GPL-2+ files gone, everything remaining would be BSD-3-Clause, MIT and IJG — so the option is real, just not unilateral.

Acknowledgements

About

Print to a host-based HP inkjet from Android — HPLIP's hpcups ported to the NDK, over TCP 9100 or USB.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages