How PDF Dark Mode Conversion Works: Streams, Images, and Print

By PDF Dark Team · · 6 min read

Most online dark-mode converters paint each PDF page onto an HTML canvas, invert the RGB pixels, and wrap the resulting JPEGs or PNGs into a new file, which bloats file size, blurs text when zoomed, and flips embedded photos into negatives. Hybrid PDF dark mode conversion edits the PDF's own drawing instructions wherever the page structure allows it, isolates embedded images geometrically, and falls back to raster rendering with an invisible searchable text layer only on pages that require pixel-level work. You can inspect the output directly on your own files in the PDF color inverter.

Three PDF dark mode conversion architectures

Client-side and online converters fall into three architectures. The trade-offs show up as soon as you zoom to 300%, inspect a color photograph, press Ctrl+F on a complex chart page, or print dark lecture slides.

Engineering behaviorCanvas rasterizers (2x PNG/JPEG tools)Naive 255 - RGB stream invertersPDF Dark hybrid pipeline
Standard digital text & file sizeDestroys vector glyphs; pages turn into blurry bitmaps at multi-megabyte sizesKeeps selectable vector text and compact file sizeKeeps selectable vector text, outlines, and links at near-original size
Vendor manuals with permissions-only lockRenders via canvas, losing vector text across the entire manualOften fails pdf-lib load on owner-locked files and drops to flat bitmapsUnlocks permissions-only owner passwords automatically so vector pages stay sharp
Colored headings & calloutsFlips RGB channels into harsh complementary colors unless filtered255 - channel turns dark blue headings bright orange and red notes cyanFlips lightness in HSL, preserving hue and saturation (dark blue becomes light blue)
Embedded photographs & white chartsFlips photos into X-ray negativesStraight 255 - channel flip turns photographs into color negatives and reverses chart colorsVector pages leave photo bytes untouched (optional subtle night veil); raster pages classify brightness/saturation and re-embed photos up to 2x render box
Gradients (sh), spot colors, or scansFlattens the entire PDF, destroying text search on every pageSingle-page raster fallback loses selectable text on fallback pagesPer-page health check isolates complex/scanned pages and replays standard Latin text in PDF rendering mode 3 (invisible searchable text)
Printing dark slides on white paperNot supported (dark PDFs dump black toner across the sheet)Not supported (warns against printing inverted files)Dedicated Dark → Light (Print) math snaps dark boards to #FFFFFF and darkens yellow/cyan strokes for legibility

1. Rewriting PDF color operators without shifting hue

A digital PDF page from Word, Google Docs, or LaTeX is a stream of postfix drawing operators: set grayscale fill or stroke (g / G), set RGB fill or stroke (rg / RG), set CMYK (k / K), or assign device, calibrated, or ICC color spaces (cs, CS, sc, SC, scn, SCN). Instead of rasterizing the page, the tokenizer walks that content stream, resolves each supported color operand, maps it into the target dark theme, and emits plain DeviceRGB (rg / RG) instructions in place. Text glyphs, vector line art, internal links, and document bookmarks remain intact. Before stream rewriting starts, pdf-lib also passes an empty user password (password: ""), unlocking the silent owner-password copy restrictions common on 500-page hardware manuals so their vector text is not downgraded to bitmaps.

How each color is mapped matters just as much as keeping it vector. A naive 255 - channel subtraction flips both brightness and hue, turning dark-blue headings bright orange. PDF Dark separates near-grayscale colors (mapped smoothly between pure white text and your chosen theme background via Rec.601 luminance) from chromatic colors: saturated headings and callouts convert to HSL, keep their original hue and saturation, and flip lightness onto a readable high-luminance band (0.92 - 0.42 * L).

Source PDF page with dark text, a dark-blue Chapter 3 subtitle, and a full-color sunset illustration
Source PDF
Naive 255 minus RGB channel inversion: the blue Chapter 3 subtitle turns orange and the sunset illustration flips into a blue negative
255 - RGB channel flip: blue subtitle turns orange, artwork becomes a negative
PDF Dark output: Midnight slate background, light-blue Chapter 3 subtitle preserving its hue, and sunset illustration kept in original colors
PDF Dark: hue-preserving vector recolor + untouched image XObject

2. Locating images from operators, not computer vision

Protecting photographs does not require machine-learning object detection or server uploads because a PDF already declares where every raster image lands. Before rendering a page, PDF Dark walks PDF.js's operator list with a simulated graphics-state stack that tracks 2D affine transforms (cm) and clipping rectangles (W / W*) across paintImageXObject, inline images, and repeated image tiles. Two deliberate exclusions keep text legible: 1-bit stencil masks (paintImageMaskXObject, which JBIG2 scanners use to stamp text glyphs in the active fill color) are skipped so scanned lettering flips to white, and any single image covering 85% or more of the page area marks the entire page as a scan rather than a figure to preserve.

Next, a 32x32thumbnail sample measures each image's average brightness and saturation before choosing the page pipeline. Under Images: Auto, if a page contains a bright, low-saturation figure (luminance >= 190 and saturation < 0.12, such as a white-background chart or screenshot), that page routes to the raster pipeline so the figure's white background can invert alongside the page. Pages whose images only need preservation stay in vector mode: Image XObject bytes are never re-encoded, with at most a subtle black rectangle (<= 18% opacity) drawn over bright figures on unrotated pages. On pages that do enter the raster pipeline, axis-aligned, unmirrored, uncropped photographs are pulled from the PDF.js object pool and re-embedded over the dark base up to 2x the render box (~3x PDF user-space scale at standard 1.5x render, never upscaled past native pixels) as PNG (if transparent) or 0.92-quality JPEG.

3. Per-page health check and mode-3 invisible text

Not every PDF content stream is safe to rewrite blindly. Pages exported from Illustrator, InDesign, or CAD tools sometimes rely on smooth shading gradients (sh), named spot inks or lookup palettes (Separation, DeviceN, Indexed, Lab, Pattern), or raw inline image bytes (BI ... EI). Whenever the stream tokenizer encounters one of those constructs, a per-page health check aborts vector rewriting for that page alone and hands it to the raster pipeline (capped at 4,096 px per side and 8,388,608 total pixels so oversized architectural sheets never crash mobile browsers). In a 50-page report with one gradient cover page, the other 49 pages stay pure vector.

On any page that takes the raster path, including scanned PDFs that already carry OCR, PDF Dark reads every text run and placement matrix via PDF.js and writes those characters over the darkened bitmap in Helvetica (WinAnsi) using PDF text rendering mode 3(“neither fill nor stroke”). Visible dark pixels stay untouched, and selection, copy, and Ctrl+F keep working on upright horizontal Latin text (pages with a /Rotate flag skip the layer entirely; vertical ttb runs and text runs containing non-WinAnsi glyphs such as CJK, Cyrillic, or math symbols are skipped run by run rather than corrupting the file).

4. Reversing dark lecture slides for white-paper printing

Most PDF inverters warn users never to print an inverted PDF because a #121212 or #0f2042 slide background coats every sheet in toner, and a naive 255 - RGB reversal turns bright yellow chalk formulas almost invisible on white paper. Switching /invert-pdf-colors to Dark → Light (Print) runs a dedicated print-recovery transfer function (-light.pdf output):

Slide or page elementWhat plain 255 - RGB producesWhat PDF Dark Dark → Light (Print) does
Chalkboard, navy, or noisy JPEG-black backgrounds (effective level <= 55)Light gray or tinted background haze that wastes toner across the whole pageSnaps directly to pure #FFFFFF white (0% background ink)
Deep royal-blue or crimson pen strokes (low Rec.601 luminance, high single RGB channel)Risk getting misclassified as dark background and wiped outGates background snapping on max(luminance, 0.58 * maxChannel) so saturated blue and red strokes survive
Bright yellow, cyan, or green chalk highlightsFlips hue or stays too pale to read against white paperPreserves original hue in HSL and caps ink luminance (<= 110 / 255) so yellow and cyan notes print dark and legible
Already-white cover sheets & daylight screenshotsFlips white pages and pasted exam boxes into solid black blocksLeaves light pages (page mean >= 150, border median >= 180) and light embedded figures (brightness > 125) untouched

Frequently asked questions

Which PDF generators take the pure vector path vs the per-page raster fallback?

Prose documents exported from Word, Google Docs, LibreOffice, LaTeX (pdflatex / xelatex), and browser Save as PDF write standard grayscale, RGB, CMYK, or ICC operators and stay vector unless an individual page embeds a white-background raster figure slated for pixel inversion under Images: Auto. Print-production pages with vector gradients or spot inks fall back individually and leave ordinary text pages in the same file untouched.

If 100 pages share one Form XObject header or vector logo, does it get inverted twice?

No. Rewritten Form XObjects are tracked in a document-wide deduplication map by object reference during export, so a shared header or watermark stream is recolored once on its first appearance and reused across the remaining 99 pages.

How can I verify that conversion happens locally in my browser?

Load /invert-pdf-colors, open your browser's Network inspector (F12 -> Network), or disconnect Wi-Fi completely before dropping your PDF. Every step (PDF.js operator parsing, Web Worker pixel math, and pdf-lib serialization) executes inside local browser memory.

More from the PDF Dark blog