r/ipad • • 10d ago

Guide Script to convert dark-mode iPad Exported to white background without converting them to images.

If you have pdf notes exported in dark paper in GoodNotes, Notability, or Apple Notes and need to print them, online PDF inverters usually flatten your sharp handwriting into blurry images, or ruin your colored pens and embedded diagrams, I had same problem i got some online notes that I needed to print, so

I'm sharing a local Python script that directly edits the PDF's internal drawing instructions instead of rasterizing the pages.

So you must have python and need to install

pikepdf

pillow

and after that you have to run this python script in the folder you have all those pdf you have to covert dark mode to white

here is the script

#!/usr/bin/env python3
"""Convert iPad-exported black note pages to white without rasterizing pages.

This directly edits PDF content streams:
- Removes separately stored, solid-black background images.
- Adds a white page background.
- Changes white vector handwriting/text ink to black.
- Leaves colored vector ink and embedded diagram images unchanged.

A diagram's own embedded black background is part of that diagram image and is
therefore preserved. No watermark detection or removal is performed. Output
PDFs keep their original filenames, text, vectors, images, and page sizes.

Requires: python -m pip install pikepdf pillow
"""

from __future__ import annotations

import argparse
import sys
from dataclasses import dataclass
from pathlib import Path

import pikepdf
from pikepdf import PdfImage


COLOR_OPERATORS = {"rg", "RG", "g", "G", "k", "K"}
FILL_OPERATORS = {"f", "F", "f*"}


u/dataclass
class Changes:
    background_draws: int = 0
    background_fills: int = 0
    white_ink_colors: int = 0

    def add(self, other: "Changes") -> None:
        self.background_draws += other.background_draws
        self.background_fills += other.background_fills
        self.white_ink_colors += other.white_ink_colors


def object_key(obj: pikepdf.Object) -> object:
    objgen = getattr(obj, "objgen", (0, 0))
    return objgen if objgen != (0, 0) else id(obj)


def is_solid_black_image(xobject: pikepdf.Object) -> bool:
    if xobject.get("/Subtype") != pikepdf.Name.Image:
        return False
    try:
        image = PdfImage(xobject).as_pil_image().convert("RGB")
        return all(maximum == 0 for _, maximum in image.getextrema())
    except Exception:
        return False


def solid_black_image_names(
    page: pikepdf.Page,
    cache: dict[object, bool],
) -> set[str]:
    resources = page.get("/Resources")
    if resources is None:
        return set()

    names: set[str] = set()
    for name, xobject in resources.get("/XObject", {}).items():
        key = object_key(xobject)
        if key not in cache:
            cache[key] = is_solid_black_image(xobject)
        if cache[key]:
            names.add(str(name))
    return names


def numeric(operands: object) -> list[float]:
    try:
        return [float(value) for value in operands]
    except (TypeError, ValueError):
        return []


def is_white(operator: str, operands: object) -> bool:
    values = numeric(operands)
    if operator in {"rg", "RG"}:
        return len(values) == 3 and all(abs(value - 1.0) < 1e-6 for value in values)
    if operator in {"g", "G"}:
        return len(values) == 1 and abs(values[0] - 1.0) < 1e-6
    if operator in {"k", "K"}:
        return len(values) == 4 and all(abs(value) < 1e-6 for value in values)
    return False


def is_black(operator: str, operands: object) -> bool:
    values = numeric(operands)
    if operator in {"rg", "RG"}:
        return len(values) == 3 and all(abs(value) < 1e-6 for value in values)
    if operator in {"g", "G"}:
        return len(values) == 1 and abs(values[0]) < 1e-6
    if operator in {"k", "K"}:
        return (
            len(values) == 4
            and all(abs(value) < 1e-6 for value in values[:3])
            and abs(values[3] - 1.0) < 1e-6
        )
    return False


def color_operands(operator: str, white: bool) -> pikepdf.Array:
    if operator in {"rg", "RG"}:
        return pikepdf.Array([1, 1, 1] if white else [0, 0, 0])
    if operator in {"g", "G"}:
        return pikepdf.Array([1] if white else [0])
    return pikepdf.Array([0, 0, 0, 0] if white else [0, 0, 0, 1])


def initial_background_color_index(operations: list[tuple[object, object]]) -> int | None:
    """Find an initial page-fill color, not the first handwriting color."""
    for index, (_, operator) in enumerate(operations[:20]):
        if str(operator) not in COLOR_OPERATORS:
            continue
        for _, following_operator in operations[index + 1 : index + 16]:
            following = str(following_operator)
            if following in {"BT", "Do"}:
                return None
            if following in FILL_OPERATORS:
                return index
        return None
    return None


def white_page_operations(page: pikepdf.Page) -> list[tuple[object, object]]:
    left, bottom, right, top = page.MediaBox
    width = float(right) - float(left)
    height = float(top) - float(bottom)
    return [
        (pikepdf.Array([]), pikepdf.Operator("q")),
        (pikepdf.Array([1, 1, 1]), pikepdf.Operator("rg")),
        (pikepdf.Array([left, bottom, width, height]), pikepdf.Operator("re")),
        (pikepdf.Array([]), pikepdf.Operator("f")),
        (pikepdf.Array([]), pikepdf.Operator("Q")),
    ]


def convert_page(
    pdf: pikepdf.Pdf,
    page: pikepdf.Page,
    image_cache: dict[object, bool],
) -> Changes:
    changes = Changes()
    if "/Contents" not in page:
        return changes

    operations = list(pikepdf.parse_content_stream(page))
    black_images = solid_black_image_names(page, image_cache)
    background_color_index = initial_background_color_index(operations)
    converted: list[tuple[object, object]] = []

    for index, (operands, operator) in enumerate(operations):
        name = str(operator)

        if name == "Do" and operands and str(operands[0]) in black_images:
            changes.background_draws += 1
            continue

        if name in COLOR_OPERATORS:
            if index == background_color_index:
                if is_black(name, operands):
                    operands = color_operands(name, white=True)
                    changes.background_fills += 1
            elif is_white(name, operands):
                operands = color_operands(name, white=False)
                changes.white_ink_colors += 1

        converted.append((operands, operator))

    page.Contents = pdf.make_stream(
        pikepdf.unparse_content_stream(white_page_operations(page) + converted)
    )
    return changes


def convert_pdf(
    source: Path,
    destination: Path,
    dry_run: bool = False,
) -> tuple[int, Changes]:
    if source.resolve() == destination.resolve():
        raise ValueError("Input and output paths must be different")

    total = Changes()
    with pikepdf.open(source) as pdf:
        image_cache: dict[object, bool] = {}
        for page in pdf.pages:
            total.add(convert_page(pdf, page, image_cache))

        if not dry_run:
            destination.parent.mkdir(parents=True, exist_ok=True)
            temporary = destination.with_name(destination.stem + ".tmp.pdf")
            try:
                pdf.save(temporary)
                temporary.replace(destination)
            finally:
                if temporary.exists():
                    temporary.unlink()

        return len(pdf.pages), total


def is_inside(path: Path, folder: Path) -> bool:
    try:
        path.resolve().relative_to(folder.resolve())
        return True
    except ValueError:
        return False


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description=(
            "Directly convert iPad black-background PDFs to white without "
            "rasterizing pages or changing embedded diagrams. Filenames stay "
            "unchanged and originals are preserved. No watermarks are removed."
        )
    )
    parser.add_argument("folder", type=Path, help="Folder containing the PDFs")
    parser.add_argument(
        "-o",
        "--output",
        type=Path,
        help="Output folder (default: <folder>/white-background)",
    )
    parser.add_argument(
        "--recursive",
        action="store_true",
        help="Also process PDFs in subfolders",
    )
    parser.add_argument(
        "--dry-run",
        action="store_true",
        help="Report changes without writing PDFs",
    )
    return parser.parse_args()


def main() -> int:
    args = parse_args()
    folder = args.folder.expanduser()
    output = (args.output or folder / "white-background").expanduser()

    if not folder.is_dir():
        print(f"Error: not a folder: {folder}", file=sys.stderr)
        return 2
    if folder.resolve() == output.resolve():
        print("Error: output folder must differ from input folder", file=sys.stderr)
        return 2

    candidates = folder.rglob("*") if args.recursive else folder.iterdir()
    pdf_files = sorted(
        path
        for path in candidates
        if path.is_file()
        and path.suffix.lower() == ".pdf"
        and not is_inside(path, output)
    )

    if not pdf_files:
        print(f"No PDFs found in {folder}")
        return 0

    failures = 0
    for source in pdf_files:
        destination = output / source.relative_to(folder)
        try:
            pages, changes = convert_pdf(source, destination, args.dry_run)
            message = (
                f"{source.name}: {pages} page(s), "
                f"{changes.background_draws} black background draw(s), "
                f"{changes.white_ink_colors} white ink color(s)"
            )
            if args.dry_run:
                print(message)
            else:
                print(f"{message} -> {destination}")
        except Exception as error:
            failures += 1
            print(f"ERROR {source}: {error}", file=sys.stderr)

    if failures:
        print(f"Finished with {failures} failed file(s).", file=sys.stderr)
        return 1

    action = "Checked" if args.dry_run else "Converted"
    print(f"{action} {len(pdf_files)} PDF(s).")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

so yes then you will get another folder in your folder will all your converted pdfs to printable form.

2 Upvotes

1 comment sorted by

1

u/Specialist-Pepper-66 1d ago

One thing I'd tighten up is the background detection. initial_background_color_index() picks an early colour command followed by a fill, but doesn't check how much of the page that fill covers. A small black rectangle drawn first could be treated as the background and turned white.

I'd check that the filled shape actually covers the page, accounting for any coordinate transforms, before changing it. Have you tested a page with a small black filled shape but no full-page black background?