pdfpainter 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pdfpainter/__init__.py ADDED
@@ -0,0 +1,25 @@
1
+ """pdfpainter: paint PDF pages to images with Pillow alone, no native PDF engine needed.
2
+
3
+ Built on pdfsieve (which reads pages with pure-Python pdfminer.six), so it runs anywhere Pillow
4
+ and NumPy run, including PCs where policies block native PDF DLLs.
5
+
6
+ >>> import pdfpainter
7
+ >>> img = pdfpainter.render_pdf("statement.pdf", page=0, dpi=150)
8
+ >>> img.save("statement-1.png")
9
+
10
+ The picture is simplified: shapes (with holes), lines, embedded images, and real text set in a
11
+ similar system font. Word and line positions match the PDF exactly, which is what OCR and
12
+ "draw a box over the page" interfaces need.
13
+ """
14
+
15
+ from .fonts import FAMILIES, ITALICS, add_font_dir, family_for, find_font, font_dirs, font_for
16
+ from .images import decode_image
17
+ from .painter import MAX_PIXELS, page_size_px, render, render_pdf, to_ppm
18
+
19
+ __version__ = "0.1.0"
20
+
21
+ __all__ = [
22
+ "render", "render_pdf", "page_size_px", "decode_image", "to_ppm",
23
+ "add_font_dir", "font_dirs", "find_font", "font_for", "family_for", "FAMILIES", "ITALICS", "MAX_PIXELS",
24
+ "__version__",
25
+ ]
pdfpainter/__main__.py ADDED
@@ -0,0 +1,99 @@
1
+ """Command line: ``pdfpainter file.pdf -o page.png`` (or ``python -m pdfpainter ...``)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import os
7
+ import sys
8
+ from typing import List, Optional
9
+
10
+ import pdfsieve
11
+
12
+ from . import __version__, render
13
+
14
+
15
+ def parse_pages(spec: Optional[str], count: int) -> List[int]:
16
+ """'1,3-5' -> [0, 2, 3, 4] (1-based in, 0-based out). None means every page."""
17
+ if not spec:
18
+ return list(range(count))
19
+ out: List[int] = []
20
+ for part in spec.split(","):
21
+ part = part.strip()
22
+ if not part:
23
+ continue
24
+ if "-" in part:
25
+ a, b = part.split("-", 1)
26
+ lo = int(a) if a.strip() else 1
27
+ hi = int(b) if b.strip() else count
28
+ else:
29
+ lo = hi = int(part)
30
+ for n in range(lo, hi + 1):
31
+ if not 1 <= n <= count:
32
+ raise ValueError(f"page {n} out of range (the PDF has {count} pages)")
33
+ if n - 1 not in out:
34
+ out.append(n - 1)
35
+ return out
36
+
37
+
38
+ def out_name(pattern: str, page: int, many: bool) -> str:
39
+ """'{page}' in the name becomes the 1-based page number; with several pages and no
40
+ '{page}', '-N' goes before the extension."""
41
+ if "{page}" in pattern:
42
+ return pattern.replace("{page}", str(page + 1))
43
+ if many:
44
+ root, ext = os.path.splitext(pattern)
45
+ return f"{root}-{page + 1}{ext}"
46
+ return pattern
47
+
48
+
49
+ def main(argv: Optional[List[str]] = None) -> int:
50
+ ap = argparse.ArgumentParser(
51
+ prog="pdfpainter",
52
+ description="Paint PDF pages to image files with Pillow alone (simplified rendering, "
53
+ "exact positions).")
54
+ ap.add_argument("pdf", help="the PDF file")
55
+ ap.add_argument("-o", "--output", default=None,
56
+ help="image file to write; the extension picks the format (.png, .jpg, .tif...). "
57
+ "'{page}' is replaced by the page number. Default: <pdf name>-{page}.png")
58
+ ap.add_argument("-p", "--pages", help="pages, 1-based, e.g. 1,3-5 (default: all)")
59
+ ap.add_argument("-d", "--dpi", type=float, default=150.0, help="resolution (default: 150)")
60
+ ap.add_argument("--no-text", action="store_true", help="leave real text out (shapes and images only)")
61
+ ap.add_argument("--password", default="", help="password for an encrypted PDF")
62
+ ap.add_argument("-V", "--version", action="version", version=f"pdfpainter {__version__}")
63
+ args = ap.parse_args(argv)
64
+
65
+ if args.dpi <= 0:
66
+ print("pdfpainter: --dpi must be positive", file=sys.stderr)
67
+ return 2
68
+ try:
69
+ doc = pdfsieve.open(args.pdf, password=args.password)
70
+ except (OSError, pdfsieve.PdfSieveError) as exc:
71
+ print(f"pdfpainter: {exc}", file=sys.stderr)
72
+ return 2
73
+ with doc:
74
+ try:
75
+ pages = parse_pages(args.pages, doc.page_count)
76
+ except ValueError as exc:
77
+ print(f"pdfpainter: {exc}", file=sys.stderr)
78
+ return 2
79
+ pattern = args.output or os.path.splitext(os.path.basename(args.pdf))[0] + "-{page}.png"
80
+ for i in pages:
81
+ info: dict = {}
82
+ img = render(doc.page(i), dpi=args.dpi, info=info, text=not args.no_text)
83
+ name = out_name(pattern, i, len(pages) > 1)
84
+ try:
85
+ img.save(name)
86
+ except (OSError, ValueError) as exc:
87
+ print(f"pdfpainter: could not write {name}: {exc}", file=sys.stderr)
88
+ return 2
89
+ notes = []
90
+ if info.get("undecoded"):
91
+ notes.append(f"{info['undecoded']} image(s) in an unsupported format shown as grey boxes")
92
+ if info.get("skipped_fills"):
93
+ notes.append(f"{info['skipped_fills']} pattern/shading fill(s) left out")
94
+ print(f"{name} ({img.width} x {img.height})" + (f" note: {'; '.join(notes)}" if notes else ""))
95
+ return 0
96
+
97
+
98
+ if __name__ == "__main__":
99
+ sys.exit(main())
pdfpainter/fonts.py ADDED
@@ -0,0 +1,150 @@
1
+ """Finding a system font similar to the PDF's font.
2
+
3
+ pdfpainter never uses the fonts embedded in the PDF. It sets real text in a font from this
4
+ computer that matches the family (sans, serif, mono), weight, slant, and script (Latin, Indic,
5
+ CJK).
6
+ Extra font folders can be added with :func:`add_font_dir` or the ``PDFPAINTER_FONT_DIRS``
7
+ environment variable (folders separated by ``os.pathsep``).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import sys
14
+ from typing import Dict, List, Optional, Tuple
15
+
16
+ from PIL import ImageFont
17
+
18
+ ENV_FONT_DIRS = "PDFPAINTER_FONT_DIRS"
19
+
20
+ # family -> (regular candidates, bold candidates), first found wins
21
+ FAMILIES: Dict[str, Tuple[List[str], List[str]]] = {
22
+ "sans": (["arial.ttf", "Arial.ttf", "LiberationSans-Regular.ttf", "segoeui.ttf", "DejaVuSans.ttf",
23
+ "FreeSans.ttf"],
24
+ ["arialbd.ttf", "Arial Bold.ttf", "LiberationSans-Bold.ttf", "segoeuib.ttf", "DejaVuSans-Bold.ttf",
25
+ "FreeSansBold.ttf"]),
26
+ "serif": (["times.ttf", "Times New Roman.ttf", "LiberationSerif-Regular.ttf", "DejaVuSerif.ttf",
27
+ "FreeSerif.ttf"],
28
+ ["timesbd.ttf", "Times New Roman Bold.ttf", "LiberationSerif-Bold.ttf", "DejaVuSerif-Bold.ttf",
29
+ "FreeSerifBold.ttf"]),
30
+ "mono": (["cour.ttf", "Courier New.ttf", "LiberationMono-Regular.ttf", "DejaVuSansMono.ttf",
31
+ "FreeMono.ttf"],
32
+ ["courbd.ttf", "Courier New Bold.ttf", "LiberationMono-Bold.ttf", "DejaVuSansMono-Bold.ttf",
33
+ "FreeMonoBold.ttf"]),
34
+ # scripts the Latin fonts above don't cover
35
+ "indic": (["Nirmala.ttf", "Nirmala.ttc", "mangal.ttf", "NotoSansDevanagari-Regular.ttf", "Kohinoor.ttc"],
36
+ ["NirmalaB.ttf", "Nirmala.ttc", "NotoSansDevanagari-Bold.ttf"]),
37
+ "cjk": (["YuGothR.ttc", "msgothic.ttc", "msyh.ttc", "malgun.ttf", "NotoSansCJK-Regular.ttc",
38
+ "NotoSansCJKjp-Regular.otf", "PingFang.ttc"],
39
+ ["YuGothB.ttc", "msyhbd.ttc", "malgunbd.ttf", "NotoSansCJK-Bold.ttc"]),
40
+ }
41
+
42
+ # family -> (italic candidates, bold italic candidates); scripts without italics fall back upright
43
+ ITALICS: Dict[str, Tuple[List[str], List[str]]] = {
44
+ "sans": (["ariali.ttf", "Arial Italic.ttf", "LiberationSans-Italic.ttf", "segoeuii.ttf",
45
+ "DejaVuSans-Oblique.ttf", "FreeSansOblique.ttf"],
46
+ ["arialbi.ttf", "Arial Bold Italic.ttf", "LiberationSans-BoldItalic.ttf", "segoeuiz.ttf",
47
+ "DejaVuSans-BoldOblique.ttf", "FreeSansBoldOblique.ttf"]),
48
+ "serif": (["timesi.ttf", "Times New Roman Italic.ttf", "LiberationSerif-Italic.ttf", "DejaVuSerif-Italic.ttf",
49
+ "FreeSerifItalic.ttf"],
50
+ ["timesbi.ttf", "Times New Roman Bold Italic.ttf", "LiberationSerif-BoldItalic.ttf",
51
+ "DejaVuSerif-BoldItalic.ttf", "FreeSerifBoldItalic.ttf"]),
52
+ "mono": (["couri.ttf", "Courier New Italic.ttf", "LiberationMono-Italic.ttf", "DejaVuSansMono-Oblique.ttf",
53
+ "FreeMonoOblique.ttf"],
54
+ ["courbi.ttf", "Courier New Bold Italic.ttf", "LiberationMono-BoldItalic.ttf",
55
+ "DejaVuSansMono-BoldOblique.ttf", "FreeMonoBoldOblique.ttf"]),
56
+ }
57
+
58
+ _extra_dirs: List[str] = []
59
+ _paths: Dict[Tuple[str, bool, bool], Optional[str]] = {}
60
+ _fonts: Dict[Tuple[str, bool, bool, int], object] = {}
61
+
62
+
63
+ def add_font_dir(path: str) -> None:
64
+ """Search this folder for fonts before the system folders."""
65
+ if path not in _extra_dirs:
66
+ _extra_dirs.insert(0, path)
67
+ _paths.clear()
68
+ _fonts.clear()
69
+
70
+
71
+ def font_dirs() -> List[str]:
72
+ """Folders searched for fonts, in order."""
73
+ env = [d for d in os.environ.get(ENV_FONT_DIRS, "").split(os.pathsep) if d]
74
+ if os.name == "nt":
75
+ system = [os.path.join(os.environ.get("WINDIR", r"C:\Windows"), "Fonts"),
76
+ os.path.join(os.environ.get("LOCALAPPDATA", ""), "Microsoft", "Windows", "Fonts")]
77
+ elif sys.platform == "darwin":
78
+ system = ["/System/Library/Fonts/Supplemental", "/System/Library/Fonts", "/Library/Fonts",
79
+ os.path.expanduser("~/Library/Fonts")]
80
+ else:
81
+ system = ["/usr/share/fonts/truetype/liberation", "/usr/share/fonts/truetype/dejavu",
82
+ "/usr/share/fonts/truetype/freefont", "/usr/share/fonts/truetype/noto",
83
+ "/usr/share/fonts/opentype/noto", "/usr/share/fonts/liberation",
84
+ "/usr/share/fonts/dejavu", "/usr/share/fonts", os.path.expanduser("~/.local/share/fonts")]
85
+ return _extra_dirs + env + system
86
+
87
+
88
+ def find_font(family: str, bold: bool, italic: bool = False) -> Optional[str]:
89
+ """Path of the first installed font for a family and style, or None. A bold or italic
90
+ request falls back to the plainer styles of the same family."""
91
+ key = (family, bold, italic)
92
+ if key not in _paths:
93
+ found = None
94
+ regular, bolds = FAMILIES[family]
95
+ italics, bold_italics = ITALICS.get(family, ([], []))
96
+ if italic:
97
+ names = (bold_italics + italics + bolds + regular) if bold else (italics + regular)
98
+ else:
99
+ names = (bolds + regular) if bold else regular
100
+ dirs = font_dirs()
101
+ for name in names:
102
+ for d in dirs:
103
+ p = os.path.join(d, name)
104
+ if os.path.isfile(p):
105
+ found = p
106
+ break
107
+ if found:
108
+ break
109
+ _paths[key] = found
110
+ return _paths[key]
111
+
112
+
113
+ def family_for(fontname: str, ch: str) -> str:
114
+ """Which family to draw a character in: by its script first, then by the PDF font's name."""
115
+ o = ord(ch[0]) if ch else 0
116
+ if 0x0900 <= o <= 0x0DFF:
117
+ return "indic"
118
+ if o >= 0x2E80 and not 0xFB00 <= o <= 0xFB4F:
119
+ return "cjk"
120
+ n = fontname.lower()
121
+ if any(k in n for k in ("courier", "mono", "consol")):
122
+ return "mono"
123
+ if any(k in n for k in ("times", "serif", "roman", "georgia", "cambria", "garamond", "minion")) \
124
+ and "sans" not in n:
125
+ return "serif"
126
+ return "sans"
127
+
128
+
129
+ def font_for(fontname: str, ch: str, px: int):
130
+ """A Pillow font, ``px`` pixels high, to draw ``ch`` in place of the PDF font ``fontname``."""
131
+ name = fontname.lower()
132
+ bold = any(k in name for k in ("bold", "black", "heavy", "semibold"))
133
+ italic = any(k in name for k in ("italic", "oblique", "slant"))
134
+ fam = family_for(fontname, ch)
135
+ key = (fam, bold, italic, px)
136
+ if key not in _fonts:
137
+ path = find_font(fam, bold, italic) or find_font("sans", bold, italic) or find_font("sans", False)
138
+ font = None
139
+ if path:
140
+ try:
141
+ font = ImageFont.truetype(path, px)
142
+ except Exception:
143
+ font = None
144
+ if font is None:
145
+ try:
146
+ font = ImageFont.load_default(size=px) # Pillow >= 10.1: scalable built-in font
147
+ except TypeError: # older Pillow: fixed tiny bitmap font
148
+ font = ImageFont.load_default()
149
+ _fonts[key] = font
150
+ return _fonts[key]
pdfpainter/images.py ADDED
@@ -0,0 +1,128 @@
1
+ """Decoding images embedded in a PDF into Pillow images, without a PDF engine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ from typing import Optional, Tuple
7
+
8
+ from PIL import Image, ImageOps
9
+
10
+
11
+ def _name(obj) -> str:
12
+ n = getattr(obj, "name", obj)
13
+ if isinstance(n, bytes):
14
+ n = n.decode("latin-1")
15
+ return str(n)
16
+
17
+
18
+ def decode_image(stream) -> Tuple[Optional[Image.Image], bool]:
19
+ """An embedded image (a pdfminer ``PDFStream``) as ``(picture, is_stencil)``.
20
+
21
+ Supported: JPEG (DCT), JPEG 2000 (JPX, if your Pillow reads it), and raw/Flate/LZW/RunLength samples in gray, RGB, CMYK,
22
+ ICC-based, calibrated and indexed colour spaces at 1, 2, 4, 8 or 16 bits per component, plus
23
+ 1-bit stencil masks. Returns ``(None, False)`` for anything else (JBIG2, DeviceN and other
24
+ unusual colour spaces).
25
+
26
+ For a stencil the picture is the raw 1-bit mask; the caller paints the fill colour where the
27
+ sample is 0 (or 1 when the image's /Decode array is inverted).
28
+ """
29
+ from pdfminer.pdftypes import PDFStream, resolve1
30
+
31
+ def get(*keys, default=None):
32
+ for k in keys:
33
+ if k in stream:
34
+ return resolve1(stream[k])
35
+ return default
36
+
37
+ try:
38
+ filters = [_name(f) for f, _ in stream.get_filters()]
39
+ last = filters[-1] if filters else ""
40
+ if last == "JBIG2Decode":
41
+ return None, False
42
+ data = stream.get_data()
43
+ w, h = int(get("Width", "W")), int(get("Height", "H"))
44
+ stencil = bool(get("ImageMask", "IM", default=False))
45
+ decode = get("Decode", "D")
46
+ inverted = bool(decode) and float(decode[0]) > float(decode[1])
47
+ if last in ("DCTDecode", "DCT", "JPXDecode"):
48
+ img = Image.open(io.BytesIO(data))
49
+ img.load()
50
+ if img.mode == "CMYK":
51
+ # Adobe JPEGs store CMYK inverted; Pillow already handles the common case
52
+ img = img.convert("RGB")
53
+ return img.convert("RGB" if img.mode != "L" else "L"), False
54
+ bpc = int(get("BitsPerComponent", "BPC", default=1 if stencil else 8))
55
+ cs = get("ColorSpace", "CS")
56
+ palette = None
57
+ if isinstance(cs, list):
58
+ kind = _name(cs[0])
59
+ if kind in ("Indexed", "I"):
60
+ base = resolve1(cs[1])
61
+ base_n = {"DeviceGray": 1, "G": 1, "DeviceCMYK": 4, "CMYK": 4}.get(
62
+ _name(base[0] if isinstance(base, list) else base), 3)
63
+ if isinstance(base, list) and _name(base[0]) == "ICCBased":
64
+ base_n = int(resolve1(base[1]).get("N", 3))
65
+ look = resolve1(cs[3])
66
+ look = look.get_data() if isinstance(look, PDFStream) else bytes(look)
67
+ palette = (base_n, look)
68
+ ncomp = 1
69
+ elif kind == "ICCBased":
70
+ ncomp = int(resolve1(cs[1]).get("N", 3))
71
+ elif kind in ("CalGray", "Separation"):
72
+ ncomp = 1
73
+ elif kind in ("CalRGB", "Lab"):
74
+ ncomp = 3
75
+ else:
76
+ return None, False
77
+ else:
78
+ ncomp = {"DeviceGray": 1, "G": 1, "DeviceRGB": 3, "RGB": 3, "DeviceCMYK": 4, "CMYK": 4}.get(
79
+ _name(cs) if cs is not None else "DeviceGray", 1)
80
+ if stencil:
81
+ ncomp, bpc = 1, 1
82
+
83
+ if bpc == 1 and ncomp == 1 and palette is None:
84
+ img = Image.frombytes("1", (w, h), data[: ((w + 7) // 8) * h])
85
+ if stencil:
86
+ return img, True
87
+ img = img.convert("L")
88
+ else:
89
+ import numpy as np
90
+
91
+ row = (w * ncomp * bpc + 7) // 8
92
+ arr = np.frombuffer(data[: row * h], dtype=np.uint8).reshape(h, row)
93
+ if bpc == 8:
94
+ px = arr[:, : w * ncomp]
95
+ elif bpc == 16:
96
+ px = arr[:, : w * ncomp * 2: 2]
97
+ elif bpc in (1, 2, 4):
98
+ bits = np.unpackbits(arr, axis=1)[:, : w * ncomp * bpc].reshape(h, w * ncomp, bpc)
99
+ px = bits.dot(1 << np.arange(bpc - 1, -1, -1)).astype(np.uint8)
100
+ if palette is None:
101
+ px = (px.astype(np.uint16) * 255 // ((1 << bpc) - 1)).astype(np.uint8)
102
+ else:
103
+ return None, False
104
+ px = np.ascontiguousarray(px)
105
+ if palette is not None:
106
+ base_n, look = palette
107
+ table = np.frombuffer(look, dtype=np.uint8)
108
+ table = table[: (len(table) // base_n) * base_n].reshape(-1, base_n)
109
+ if base_n == 1:
110
+ table = np.repeat(table, 3, axis=1)
111
+ elif base_n == 4:
112
+ k = table[:, 3:4].astype(np.int32)
113
+ table = (255 - np.minimum(255, table[:, :3].astype(np.int32) + k)).astype(np.uint8)
114
+ idx = np.minimum(px, len(table) - 1)
115
+ img = Image.fromarray(np.ascontiguousarray(table[idx]))
116
+ elif ncomp == 1:
117
+ img = Image.fromarray(px.reshape(h, w))
118
+ elif ncomp == 3:
119
+ img = Image.fromarray(px.reshape(h, w, 3))
120
+ elif ncomp == 4:
121
+ img = Image.frombytes("CMYK", (w, h), px.tobytes()).convert("RGB")
122
+ else:
123
+ return None, False
124
+ if inverted and not stencil:
125
+ img = ImageOps.invert(img.convert("L") if img.mode == "1" else img)
126
+ return img, False
127
+ except Exception:
128
+ return None, False
pdfpainter/painter.py ADDED
@@ -0,0 +1,251 @@
1
+ """Painting a pdfsieve page with Pillow."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from typing import Optional, Tuple
7
+
8
+ from PIL import Image, ImageChops, ImageDraw, ImageOps
9
+
10
+ from pdfsieve import Page, Picture, Shape
11
+
12
+ from .fonts import font_for
13
+ from .images import decode_image
14
+
15
+ MAX_PIXELS = 60_000_000
16
+ """Pages with vector content are painted at twice the size and shrunk for smooth edges, unless
17
+ the doubled canvas would exceed this many pixels."""
18
+
19
+ R = Image.Resampling
20
+ T = Image.Transpose
21
+
22
+
23
+ # ---------------------------------------------------------------- shapes
24
+
25
+ def _flatten(pts, s: float) -> list:
26
+ """A subpath as a polygon in pixels; curves become short straight pieces."""
27
+ out = [(pts[0][1] * s, pts[0][2] * s)]
28
+ for p in pts[1:]:
29
+ if p[0] == "l":
30
+ out.append((p[1] * s, p[2] * s))
31
+ else:
32
+ x0, y0 = out[-1]
33
+ x1, y1, x2, y2, x3, y3 = (v * s for v in p[1:])
34
+ span = abs(x1 - x0) + abs(y1 - y0) + abs(x2 - x1) + abs(y2 - y1) + abs(x3 - x2) + abs(y3 - y2)
35
+ n = min(max(int(span / 3) + 1, 3), 32)
36
+ for k in range(1, n + 1):
37
+ t = k / n
38
+ u = 1 - t
39
+ a, b, c, d = u * u * u, 3 * u * u * t, 3 * u * t * t, t * t * t
40
+ out.append((a * x0 + b * x1 + c * x2 + d * x3, a * y0 + b * y1 + c * y2 + d * y3))
41
+ return out
42
+
43
+
44
+ def _area(poly) -> float:
45
+ a = 0.0
46
+ for (x0, y0), (x1, y1) in zip(poly, poly[1:] + poly[:1]):
47
+ a += x0 * y1 - x1 * y0
48
+ return a / 2
49
+
50
+
51
+ def _fill(canvas: Image.Image, draw: ImageDraw.ImageDraw, polys, color, evenodd: bool) -> None:
52
+ polys = [p for p in polys if len(p) >= 3]
53
+ if not polys:
54
+ return
55
+ if len(polys) == 1:
56
+ draw.polygon(polys[0], fill=color)
57
+ return
58
+ import numpy as np
59
+
60
+ W, H = canvas.size
61
+ x0 = max(int(math.floor(min(x for p in polys for x, _ in p))), 0)
62
+ y0 = max(int(math.floor(min(y for p in polys for _, y in p))), 0)
63
+ x1 = min(int(math.ceil(max(x for p in polys for x, _ in p))) + 1, W)
64
+ y1 = min(int(math.ceil(max(y for p in polys for _, y in p))) + 1, H)
65
+ if x1 <= x0 or y1 <= y0:
66
+ return
67
+ mask = np.zeros((y1 - y0, x1 - x0), dtype=bool)
68
+ areas = [_area(p) for p in polys]
69
+ order = sorted(range(len(polys)), key=lambda i: -abs(areas[i]))
70
+ outer_sign = areas[order[0]] >= 0
71
+ for i in order:
72
+ p = polys[i]
73
+ px0 = min(max(int(math.floor(min(x for x, _ in p))), x0), x1 - 1)
74
+ py0 = min(max(int(math.floor(min(y for _, y in p))), y0), y1 - 1)
75
+ px1 = max(min(int(math.ceil(max(x for x, _ in p))) + 1, x1), px0 + 1)
76
+ py1 = max(min(int(math.ceil(max(y for _, y in p))) + 1, y1), py0 + 1)
77
+ small = Image.new("1", (px1 - px0, py1 - py0), 0)
78
+ ImageDraw.Draw(small).polygon([(x - px0, y - py0) for x, y in p], fill=1)
79
+ sub = np.asarray(small, dtype=bool)
80
+ view = mask[py0 - y0:py1 - y0, px0 - x0:px1 - x0]
81
+ if evenodd:
82
+ view ^= sub
83
+ else:
84
+ # Non-zero rule, approximated: biggest outlines first; an outline wound the other
85
+ # way that lies inside ink is a hole (the inside of "o"), anything else is ink.
86
+ inside = sub.any() and view[sub].mean() > 0.5
87
+ if inside and (areas[i] >= 0) != outer_sign:
88
+ view &= ~sub
89
+ else:
90
+ view |= sub
91
+ canvas.paste(color, (x0, y0), Image.fromarray(mask.astype("uint8") * 255))
92
+
93
+
94
+ # ---------------------------------------------------------------- images
95
+
96
+ def _place(canvas: Image.Image, draw, pic: Picture, s: float) -> bool:
97
+ """Paint one embedded image where its matrix puts it. False if it couldn't be decoded."""
98
+ a, b, c, d, e, f = pic.matrix
99
+ corners = [(e, f), (e + a, f + b), (e + c, f + d), (e + a + c, f + b + d)]
100
+ bx0 = int(math.floor(min(x for x, _ in corners) * s))
101
+ by0 = int(math.floor(min(y for _, y in corners) * s))
102
+ bx1 = int(math.ceil(max(x for x, _ in corners) * s))
103
+ by1 = int(math.ceil(max(y for _, y in corners) * s))
104
+ bw, bh = bx1 - bx0, by1 - by0
105
+ if bw < 1 or bh < 1 or bw * bh > 4 * canvas.size[0] * canvas.size[1]:
106
+ return True
107
+ img, stencil = decode_image(pic.stream)
108
+ if img is None:
109
+ draw.rectangle((bx0, by0, bx1, by1), fill=(236, 236, 236), outline=(170, 170, 170))
110
+ return False
111
+ if stencil:
112
+ from pdfminer.pdftypes import resolve1
113
+
114
+ dec = resolve1(pic.stream.get("Decode") or pic.stream.get("D"))
115
+ paint_ones = bool(dec) and float(dec[0]) > float(dec[1])
116
+ ink = img.convert("L")
117
+ mask_src = ink if paint_ones else ImageOps.invert(ink)
118
+ img = None
119
+ else:
120
+ mask_src = None
121
+ src = img if img is not None else mask_src
122
+ w, h = src.size
123
+ if abs(b) < 1e-6 and abs(c) < 1e-6: # upright: the usual case
124
+ if a < 0:
125
+ src = src.transpose(T.FLIP_LEFT_RIGHT)
126
+ if d > 0: # image's top row lands at the bottom
127
+ src = src.transpose(T.FLIP_TOP_BOTTOM)
128
+ small = bw < w or bh < h
129
+ src = src.resize((bw, bh), R.LANCZOS if small else R.BICUBIC)
130
+ valid = None
131
+ else: # rotated or skewed
132
+ # image pixel (i, j) -> canvas: u = i / w, v = 1 - j / h
133
+ m00, m01, m02 = s * a / w, -s * c / h, s * (c + e) - bx0
134
+ m10, m11, m12 = s * b / w, -s * d / h, s * (d + f) - by0
135
+ det = m00 * m11 - m01 * m10
136
+ if abs(det) < 1e-12:
137
+ return True
138
+ i00, i01, i10, i11 = m11 / det, -m01 / det, -m10 / det, m00 / det
139
+ coeffs = (i00, i01, -(i00 * m02 + i01 * m12), i10, i11, -(i10 * m02 + i11 * m12))
140
+ valid = Image.new("L", (w, h), 255).transform((bw, bh), Image.Transform.AFFINE, coeffs, R.NEAREST)
141
+ src = src.transform((bw, bh), Image.Transform.AFFINE, coeffs, R.BICUBIC)
142
+ if mask_src is not None: # stencil: paint the fill colour through the mask
143
+ if valid is not None:
144
+ src = ImageChops.multiply(src, valid)
145
+ canvas.paste(pic.color or (0, 0, 0), (bx0, by0), src)
146
+ else:
147
+ canvas.paste(src.convert("RGB"), (bx0, by0), valid)
148
+ return True
149
+
150
+
151
+ # ---------------------------------------------------------------- page
152
+
153
+ def page_size_px(page: Page, zoom: float) -> Tuple[int, int]:
154
+ """The size in pixels :func:`render` produces: the same rounding PDFium uses, so the two are
155
+ interchangeable."""
156
+ return (max(math.ceil(page.width * zoom - 1e-6), 1), max(math.ceil(page.height * zoom - 1e-6), 1))
157
+
158
+
159
+ def render(page: Page, zoom: float = 1.0, info: Optional[dict] = None, *, dpi: Optional[float] = None,
160
+ background: Tuple[int, int, int] = (255, 255, 255), text: bool = True,
161
+ antialias: bool = True) -> Image.Image:
162
+ """Paint a page as an RGB Pillow image.
163
+
164
+ zoom: pixels per point (1.0 = 72 dpi). ``dpi`` sets the same thing in dots per inch.
165
+ info: a dict that receives ``undecoded`` (images that could not be shown) and
166
+ ``skipped_fills`` (shapes filled with a pattern or shading, left out).
167
+ background: page colour.
168
+ text: False leaves real text out (shapes and images only), e.g. to see what a page
169
+ looks like to OCR once its text layer is ignored.
170
+ antialias: paint vector pages at twice the size and shrink, for smooth edges.
171
+ """
172
+ if dpi is not None:
173
+ zoom = dpi / 72.0
174
+ if zoom <= 0:
175
+ raise ValueError("zoom must be positive")
176
+ W, H = page_size_px(page, zoom)
177
+ has_vector = bool(page.glyphs) or any(isinstance(i, Shape) for i in page.items)
178
+ ss = 2 if antialias and has_vector and W * H * 4 <= MAX_PIXELS else 1
179
+ s = zoom * ss
180
+ canvas = Image.new("RGB", (W * ss, H * ss), background)
181
+ draw = ImageDraw.Draw(canvas)
182
+ undecoded = skipped = 0
183
+ for it in page.items:
184
+ if isinstance(it, Picture):
185
+ if not _place(canvas, draw, it, s):
186
+ undecoded += 1
187
+ continue
188
+ polys = [(_flatten(pts, s), closed) for pts, closed in it.subpaths]
189
+ if it.fill is not None:
190
+ _fill(canvas, draw, [p for p, _ in polys], it.fill, it.evenodd)
191
+ elif it.stroke is None:
192
+ skipped += 1
193
+ if it.stroke is not None:
194
+ width = max(int(round(it.width * s)), ss)
195
+ for p, closed in polys:
196
+ if closed:
197
+ p = p + p[:1]
198
+ if len(p) >= 2:
199
+ draw.line(p, fill=it.stroke, width=width, joint="curve" if width > 2 else None)
200
+ if text:
201
+ for g in page.glyphs:
202
+ if not g.visible or not g.text.strip() or g.text == "�":
203
+ continue
204
+ px = max(int(round(g.size * s)), 4)
205
+ font = font_for(g.font, g.text, px)
206
+ if not g.upright:
207
+ _sideways(canvas, g, font, px, s)
208
+ continue
209
+ try:
210
+ draw.text((g.x0 * s, g.base * s), g.text, font=font, fill=g.color or (0, 0, 0), anchor="ls")
211
+ except Exception: # bitmap fallback font has no anchors
212
+ draw.text((g.x0 * s, g.y0 * s), g.text, font=font, fill=g.color or (0, 0, 0))
213
+ if info is not None:
214
+ info["undecoded"] = undecoded
215
+ info["skipped_fills"] = skipped
216
+ return canvas.resize((W, H), R.LANCZOS) if ss > 1 else canvas
217
+
218
+
219
+ def _sideways(canvas: Image.Image, g, font, px: int, s: float) -> None:
220
+ """A character that is turned on the page: set it upright on a scrap, turn the scrap, and
221
+ stamp it so its baseline corner sits where the PDF put it."""
222
+ try:
223
+ pad = px
224
+ scrap = Image.new("L", (px * 2 + 2 * pad, px * 2 + 2 * pad), 0)
225
+ ImageDraw.Draw(scrap).text((scrap.width // 2, scrap.height // 2), g.text, font=font, fill=255,
226
+ anchor="ls")
227
+ scrap = scrap.rotate(g.turn) # turns about the centre, where the baseline starts
228
+ # the baseline start in the box: the corner the writing leaves from
229
+ ox, oy = {90: (g.x1, g.y1), 180: (g.x1, g.y0), 270: (g.x0, g.y0)}.get(g.turn, (g.x0, g.y1))
230
+ d = 0.22 * g.size # the box includes the descender; lift the baseline off the box edge
231
+ ox, oy = {90: (ox - d, oy), 180: (ox, oy + d), 270: (ox + d, oy)}.get(g.turn, (ox, oy - d))
232
+ canvas.paste(g.color or (0, 0, 0),
233
+ (int(round(ox * s - scrap.width / 2)), int(round(oy * s - scrap.height / 2))), scrap)
234
+ except Exception:
235
+ pass
236
+
237
+
238
+ def render_pdf(source, page: int = 0, zoom: float = 1.0, *, dpi: Optional[float] = None, password: str = "",
239
+ info: Optional[dict] = None, **kwargs) -> Image.Image:
240
+ """Open a PDF (path, bytes or binary file) and paint one page (0-based). Other keyword
241
+ arguments go to :func:`render`."""
242
+ import pdfsieve
243
+
244
+ with pdfsieve.open(source, password=password) as doc:
245
+ return render(doc.page(page), zoom, info, dpi=dpi, **kwargs)
246
+
247
+
248
+ def to_ppm(img: Image.Image) -> bytes:
249
+ """PPM bytes, which Tk's ``PhotoImage`` reads without any extra library."""
250
+ img = img.convert("RGB")
251
+ return b"P6 %d %d 255\n" % img.size + img.tobytes()
pdfpainter/py.typed ADDED
File without changes
@@ -0,0 +1,312 @@
1
+ Metadata-Version: 2.4
2
+ Name: pdfpainter
3
+ Version: 0.1.0
4
+ Summary: Paint PDF pages to images with Pillow alone: no native PDF engine, permissive licence, exact text positions. For OCR and page previews where PDF DLLs can't run.
5
+ Author: Vaibhav Rawat (AdRaw App Studio)
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/Vibhu1712/pdfpainter
8
+ Project-URL: Issues, https://github.com/Vibhu1712/pdfpainter/issues
9
+ Project-URL: Changelog, https://github.com/Vibhu1712/pdfpainter/blob/main/CHANGELOG.md
10
+ Keywords: pdf,render,rasterize,pdf to image,pillow,ocr,pure python
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Topic :: Multimedia :: Graphics :: Graphics Conversion
17
+ Classifier: Topic :: Office/Business
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.9
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ License-File: NOTICE
23
+ License-File: THIRD_PARTY_NOTICES.md
24
+ Requires-Dist: pdfsieve>=0.1.0
25
+ Requires-Dist: pdfminer.six>=20240706
26
+ Requires-Dist: Pillow>=9.1
27
+ Requires-Dist: numpy>=1.21
28
+ Provides-Extra: test
29
+ Requires-Dist: pytest>=7; extra == "test"
30
+ Requires-Dist: reportlab>=4; python_version >= "3.10" and extra == "test"
31
+ Requires-Dist: reportlab<=4.5.0,>=4; python_version < "3.10" and extra == "test"
32
+ Dynamic: license-file
33
+
34
+ # pdfpainter
35
+
36
+ **Paint PDF pages to images with Pillow alone: no native PDF engine, Apache-2.0 licensed, text in exactly the right place.**
37
+
38
+ ```python
39
+ import pdfpainter
40
+
41
+ img = pdfpainter.render_pdf("payslip.pdf", page=0, dpi=150) # a Pillow image
42
+ img.save("payslip-1.png")
43
+ ```
44
+
45
+ ![The same payslip painted by PDFium and by pdfpainter](docs/comparison.png)
46
+
47
+ ## Why pdfpainter
48
+
49
+ Most ways to turn a PDF page into an image load a native engine: MuPDF, PDFium, Poppler or Ghostscript. That fails where policies block unsigned DLLs (Windows Application Control on government and bank PCs, locked-down servers), and some of those engines are AGPL or GPL.
50
+
51
+ pdfpainter paints pages with **Pillow and NumPy only**, from what [pdfsieve](https://github.com/Vibhu1712/pdfsieve) reads with pure-Python pdfminer.six. It is built for two jobs:
52
+
53
+ 1. **OCR** of pages with no usable text layer: scans, and text drawn as outlines (for example PDFs from "Microsoft Print to PDF"). Letter outlines are filled with their holes, so OCR reads them.
54
+ 2. **Showing a page on screen** so users can see it, click on it, or drag boxes over it. Words land in exactly the positions the PDF gives them.
55
+
56
+ It is **not** a full PDF renderer; see [what is drawn](#what-is-drawn-and-what-isnt). For pixel-perfect output, use PDFium (pypdfium2) when it's available and fall back to pdfpainter when it isn't. The two produce images of the same size, so they're interchangeable.
57
+
58
+ ## Contents
59
+
60
+ - [Install](#install)
61
+ - [Quick start](#quick-start)
62
+ - [Command line](#command-line)
63
+ - [API reference](#api-reference)
64
+ - [Recipes](#recipes)
65
+ - [What is drawn, and what isn't](#what-is-drawn-and-what-isnt)
66
+ - [Fonts](#fonts)
67
+ - [Speed](#speed)
68
+ - [Development](#development)
69
+ - [Licence](#licence)
70
+
71
+ ## Install
72
+
73
+ ```bash
74
+ pip install pdfpainter
75
+ ```
76
+
77
+ Python 3.9 or newer. Installs pdfsieve, pdfminer.six, Pillow and NumPy, all with permissive licences and wheels for every common platform.
78
+
79
+ ## Quick start
80
+
81
+ ```python
82
+ import pdfpainter
83
+ import pdfsieve
84
+
85
+ # one call: open, paint, close
86
+ img = pdfpainter.render_pdf("statement.pdf", page=0, dpi=200)
87
+
88
+ # or paint pages you already opened with pdfsieve
89
+ with pdfsieve.open("statement.pdf") as doc:
90
+ for page in doc:
91
+ img = pdfpainter.render(page, zoom=2.0) # 2 pixels per point = 144 dpi
92
+ img.save(f"statement-{page.index + 1}.png")
93
+
94
+ # find out what couldn't be drawn
95
+ info = {}
96
+ img = pdfpainter.render_pdf("scan.pdf", dpi=300, info=info)
97
+ print(info) # {'undecoded': 0, 'skipped_fills': 0}
98
+ ```
99
+
100
+ **Zoom and dpi.** `zoom` is pixels per PDF point; `dpi = zoom × 72`. A word box from pdfsieve maps onto the image by multiplying each coordinate by `zoom`.
101
+
102
+ ## Command line
103
+
104
+ ```bash
105
+ pdfpainter payslip.pdf # every page to payslip-1.png, payslip-2.png, ...
106
+ pdfpainter payslip.pdf -o page.png -p 1 # one page
107
+ pdfpainter payslip.pdf -o "out/p{page}.jpg" # {page} is the page number; extension picks the format
108
+ pdfpainter payslip.pdf --dpi 300 # default 150
109
+ pdfpainter payslip.pdf --no-text # shapes and images only
110
+ pdfpainter locked.pdf --password secret
111
+ ```
112
+
113
+ Each file written is listed with its size, plus a note if something on the page couldn't be shown:
114
+
115
+ ```
116
+ k-1.png (417 x 417) note: 1 image(s) in an unsupported format shown as grey boxes
117
+ ```
118
+
119
+ ## API reference
120
+
121
+ ### `render(page, zoom=1.0, info=None, *, dpi=None, background=(255, 255, 255), text=True, antialias=True)`
122
+
123
+ Paint a `pdfsieve.Page` and return an RGB `PIL.Image.Image`.
124
+
125
+ | Argument | Meaning |
126
+ |---|---|
127
+ | `page` | A page from `pdfsieve.open(...).page(i)`. |
128
+ | `zoom` | Pixels per point. `1.0` is 72 dpi. |
129
+ | `dpi` | Alternative to `zoom`: dots per inch. |
130
+ | `info` | A dict to receive `undecoded` (images in an unsupported format, drawn as grey boxes) and `skipped_fills` (shapes filled with a pattern or shading, left out). |
131
+ | `background` | Page colour. |
132
+ | `text` | `False` leaves the text layer out, to see what a page looks like without it. |
133
+ | `antialias` | Paint vector content at twice the size, then shrink, for smooth edges. Turn off for speed. |
134
+
135
+ The image size is `ceil(width × zoom) × ceil(height × zoom)`, the same rounding PDFium uses
136
+ (see `page_size_px(page, zoom)`).
137
+
138
+ ### `render_pdf(source, page=0, zoom=1.0, *, dpi=None, password="", info=None, **kwargs)`
139
+
140
+ Open a PDF (path, bytes or binary file object), paint one page (0-based), and close it. Other
141
+ keyword arguments go to `render`.
142
+
143
+ ### `decode_image(stream) -> (image or None, is_stencil)`
144
+
145
+ Decode one embedded image (a pdfminer stream, e.g. `page.pictures[0].stream`) into a Pillow image,
146
+ for extracting a scan's image without rendering the whole page. Returns `(None, False)` for
147
+ unsupported formats.
148
+
149
+ ### Fonts
150
+
151
+ | | |
152
+ |---|---|
153
+ | `add_font_dir(path)` | Search a folder for fonts before the system folders. |
154
+ | `font_dirs()` | The folders searched, in order. |
155
+ | `find_font(family, bold, italic=False)` | Path of the font used for `"sans"`, `"serif"`, `"mono"`, `"indic"` or `"cjk"`. |
156
+ | `font_for(pdf_font_name, char, px)` | The Pillow font used to draw a character. |
157
+ | `FAMILIES`, `ITALICS` | The candidate font file names per family; edit to prefer other fonts. |
158
+
159
+ The `PDFPAINTER_FONT_DIRS` environment variable adds folders too (separated by `;` on Windows and
160
+ `:` elsewhere).
161
+
162
+ ### Other
163
+
164
+ | | |
165
+ |---|---|
166
+ | `page_size_px(page, zoom)` | Size in pixels `render` will produce. |
167
+ | `to_ppm(img)` | PPM bytes that Tkinter's `PhotoImage(data=...)` shows with no extra libraries. |
168
+ | `MAX_PIXELS` | Above this canvas size, `antialias` is skipped to save memory. |
169
+
170
+ ## Recipes
171
+
172
+ Runnable versions live in [`examples/`](examples). Make the sample PDF with
173
+ `python examples/make_sample_pdf.py` (needs `pip install reportlab`).
174
+
175
+ ### OCR a page that has no text layer
176
+
177
+ ```python
178
+ import numpy as np
179
+ import pdfpainter, pdfsieve
180
+ from rapidocr import RapidOCR # pip install rapidocr onnxruntime
181
+
182
+ zoom = 300 / 72
183
+ with pdfsieve.open("printed-to-pdf.pdf") as doc:
184
+ img = pdfpainter.render(doc.page(0), zoom)
185
+
186
+ result = RapidOCR()(np.asarray(img))
187
+ for quad, text in zip(result.boxes, result.txts):
188
+ xs, ys = [p[0] for p in quad], [p[1] for p in quad]
189
+ print(min(xs) / zoom, min(ys) / zoom, text) # back in PDF points, like pdfsieve's words
190
+ ```
191
+
192
+ [`examples/ocr_page.py`](examples/ocr_page.py) does the same with RapidOCR or, if that isn't
193
+ installed, Tesseract.
194
+
195
+ ### Draw word boxes over the page
196
+
197
+ ```python
198
+ from PIL import ImageDraw
199
+
200
+ zoom = 2.0
201
+ with pdfsieve.open("sample.pdf") as doc:
202
+ page = doc.page(0)
203
+ img = pdfpainter.render(page, zoom)
204
+ draw = ImageDraw.Draw(img)
205
+ for w in page.words():
206
+ draw.rectangle([v * zoom for v in w[:4]], outline="red", width=2)
207
+ img.save("boxes.png")
208
+ ```
209
+
210
+ ### PDFium when allowed, pdfpainter when not
211
+
212
+ ```python
213
+ def page_image(path, index, zoom):
214
+ try:
215
+ import pypdfium2 as pdfium
216
+ pdf = pdfium.PdfDocument(path)
217
+ try:
218
+ return pdf[index].render(scale=zoom).to_pil().convert("RGB")
219
+ finally:
220
+ pdf.close()
221
+ except Exception: # not installed, or its DLL is blocked
222
+ return pdfpainter.render_pdf(path, index, zoom)
223
+ ```
224
+
225
+ ### Show a page in Tkinter with no extra libraries
226
+
227
+ ```python
228
+ import tkinter as tk
229
+
230
+ root = tk.Tk()
231
+ photo = tk.PhotoImage(data=pdfpainter.to_ppm(pdfpainter.render_pdf("sample.pdf", dpi=96)))
232
+ tk.Label(root, image=photo).pack()
233
+ root.mainloop()
234
+ ```
235
+
236
+ ### Pull the scanned image out of a page
237
+
238
+ ```python
239
+ with pdfsieve.open("scan.pdf") as doc:
240
+ pic = doc.page(0).pictures[0]
241
+ img, is_stencil = pdfpainter.decode_image(pic.stream)
242
+ if img is not None:
243
+ img.save("scan.png") # at the scan's own resolution
244
+ ```
245
+
246
+ ## What is drawn, and what isn't
247
+
248
+ **Drawn**
249
+
250
+ - Filled and stroked paths, with curves, line widths and colours (gray, RGB, CMYK, spot tints).
251
+ - Holes in shapes under both fill rules, so letters drawn as outlines (`o`, `e`, `8`) keep their
252
+ counters and OCR reads them.
253
+ - Embedded images, upright or rotated: JPEG, JPEG 2000 (if your Pillow reads it), and raw, Flate,
254
+ LZW or RunLength data in gray, RGB, CMYK, ICC, calibrated and indexed colour spaces at
255
+ 1–16 bits; 1-bit stencil masks in the current fill colour.
256
+ - Real text in a similar system font (sans, serif or mono, bold and italic, Indic and CJK
257
+ scripts), on its exact baseline, including sideways and upside-down text. Invisible text, such
258
+ as a scan's OCR layer, is not drawn.
259
+
260
+ **Not drawn**
261
+
262
+ - Clipping paths: content outside a clip still shows.
263
+ - Transparency and blend modes: everything is opaque.
264
+ - Pattern and shading fills (gradients): left out and counted in `info["skipped_fills"]`.
265
+ - Dashed lines are drawn solid; line caps and joins are approximated.
266
+ - The PDF's own embedded fonts: text is set in a system font, so letter shapes and widths differ
267
+ slightly, though each character starts where the PDF puts it.
268
+ - JBIG2 images (common in scanned archives) and unusual colour spaces (DeviceN, Lab images): drawn
269
+ as grey boxes and counted in `info["undecoded"]`.
270
+ - Annotations and form-field appearances.
271
+
272
+ ## Fonts
273
+
274
+ Text is set in fonts already on the computer:
275
+
276
+ | Family | Windows | macOS | Linux |
277
+ |---|---|---|---|
278
+ | sans | Arial, Segoe UI | Arial | Liberation Sans, DejaVu Sans, FreeSans |
279
+ | serif | Times New Roman | Times New Roman | Liberation Serif, DejaVu Serif, FreeSerif |
280
+ | mono | Courier New | Courier New | Liberation Mono, DejaVu Sans Mono, FreeMono |
281
+ | indic | Nirmala UI, Mangal | Kohinoor | Noto Sans Devanagari |
282
+ | cjk | Yu Gothic, MS Gothic, Microsoft YaHei, Malgun Gothic | PingFang | Noto Sans CJK |
283
+
284
+ The family is chosen from the PDF's font name (`Times`, `Courier`, `Bold`, `Italic`, ...) and the
285
+ character's script. With no matching font installed, Pillow's built-in font is used. On a minimal
286
+ Linux server, `apt install fonts-liberation` gives good results.
287
+
288
+ ## Speed
289
+
290
+ In testing, painting at 150 dpi took about **100–200 ms per page**, on top of pdfsieve's reading
291
+ time; text-heavy pages take longest. Turning off `antialias` cut that to **20–130 ms**, at the
292
+ cost of rougher edges. For OCR, antialiasing usually helps accuracy, so keep it on there.
293
+
294
+ ## Development
295
+
296
+ ```bash
297
+ git clone https://github.com/Vibhu1712/pdfpainter
298
+ cd pdfpainter
299
+ pip install -e ".[test]"
300
+ pytest
301
+ ```
302
+
303
+ The tests build their sample PDFs at run time (with reportlab, plus a few hand-written PDFs for
304
+ image formats), and compare page sizes against PDFium when pypdfium2 is installed.
305
+
306
+ ## Licence
307
+
308
+ Apache License 2.0; see [LICENSE](LICENSE). Copyright 2026 Vaibhav Rawat (AdRaw App Studio).
309
+ Dependencies and their licences are listed in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
310
+
311
+ pdfpainter began as the fallback page painter inside **docextract by AdRaw App Studio**, an
312
+ offline PDF-to-Excel extraction tool, and is published so others can use it too.
@@ -0,0 +1,14 @@
1
+ pdfpainter/__init__.py,sha256=jvHdey6Adz6n0dG0S3-3AFEQAQ1yeWBMNjXrA_jKpTg,1059
2
+ pdfpainter/__main__.py,sha256=Epg3MbfrZvD3cgGCR3nhD3EF7zbN3et9EZ69SeVq_iY,3943
3
+ pdfpainter/fonts.py,sha256=a36Ef3xsiliekMtBIqMQCIW350rFhxKY0qYBGQPlCx0,6972
4
+ pdfpainter/images.py,sha256=RYQAkYAgnm-7bQn0FaddZgSP2qz03V31869Dyrnut_s,5456
5
+ pdfpainter/painter.py,sha256=na2-yjaBNXg5S5-Efu_zyrUVCLPtWupXQwWhTeym_cA,11066
6
+ pdfpainter/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ pdfpainter-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
8
+ pdfpainter-0.1.0.dist-info/licenses/NOTICE,sha256=SS0HjcOaaG9uEXCAR8-p1UyKiRo7jAmpHMz8rays24Q,252
9
+ pdfpainter-0.1.0.dist-info/licenses/THIRD_PARTY_NOTICES.md,sha256=XJ3HKdRw_XotpECb_f8QP0hvsv7ifxtAh3BJWlNz4wI,2025
10
+ pdfpainter-0.1.0.dist-info/METADATA,sha256=4IEMCej38rtcVuuWQUP39ehbM8Ny7Gnr8Q-t3MFasQE,12603
11
+ pdfpainter-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
12
+ pdfpainter-0.1.0.dist-info/entry_points.txt,sha256=m0XlZ7DP9rCYvoxg2MJ4QLJ67BAzmDjz1wihNJccLLM,56
13
+ pdfpainter-0.1.0.dist-info/top_level.txt,sha256=anPvpmaj4S0cDRbT1EXSc9UiOApOukhht437LbrtmBw,11
14
+ pdfpainter-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ pdfpainter = pdfpainter.__main__:main
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,7 @@
1
+ pdfpainter
2
+ Copyright 2026 Vaibhav Rawat (AdRaw App Studio)
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
5
+ It paints PDF pages to images with Pillow alone.
6
+
7
+ Originally developed as part of docextract by AdRaw App Studio.
@@ -0,0 +1,53 @@
1
+ # Third-party notices
2
+
3
+ pdfpainter does not copy code from these projects; it depends on them at run time.
4
+ They are installed separately by pip, under their own licences, listed here for convenience.
5
+
6
+ ## pdfsieve
7
+
8
+ Apache License 2.0. Copyright 2026 Vaibhav Rawat (AdRaw App Studio).
9
+ https://github.com/YOUR-GITHUB-USER/pdfsieve
10
+
11
+ ## pdfminer.six
12
+
13
+ MIT License. https://github.com/pdfminer/pdfminer.six
14
+
15
+ ```
16
+ Copyright (c) 2004-2016 Yusuke Shinyama <yusuke at shinyama dot jp>
17
+
18
+ Permission is hereby granted, free of charge, to any person
19
+ obtaining a copy of this software and associated documentation
20
+ files (the "Software"), to deal in the Software without
21
+ restriction, including without limitation the rights to use,
22
+ copy, modify, merge, publish, distribute, sublicense, and/or
23
+ sell copies of the Software, and to permit persons to whom the
24
+ Software is furnished to do so, subject to the following
25
+ conditions:
26
+
27
+ The above copyright notice and this permission notice shall be
28
+ included in all copies or substantial portions of the Software.
29
+
30
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
31
+ KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
32
+ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
33
+ PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
34
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
35
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
36
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
37
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
38
+ ```
39
+
40
+ ## Pillow
41
+
42
+ MIT-CMU License (HPND). Copyright 1997-2011 Secret Labs AB, 1995-2011 Fredrik Lundh and
43
+ contributors, 2010 Jeffrey 'Alex' Clark and contributors. https://github.com/python-pillow/Pillow
44
+
45
+ ## NumPy
46
+
47
+ BSD 3-Clause License. Copyright 2005 NumPy Developers. https://github.com/numpy/numpy
48
+
49
+ ## Test-only dependencies
50
+
51
+ pytest (MIT) and reportlab (BSD) are used to run the test suite and are not needed to use
52
+ pdfpainter. pypdfium2 (Apache-2.0 / BSD-3-Clause) is used, when installed, to compare
53
+ page sizes in the tests.
@@ -0,0 +1 @@
1
+ pdfpainter