-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwatermark_pdf.py
More file actions
945 lines (796 loc) · 28.4 KB
/
Copy pathwatermark_pdf.py
File metadata and controls
945 lines (796 loc) · 28.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
#!/usr/bin/env python3
# pyright: reportMissingImports=false
"""Add tiled, flowing, or single-position watermarks to a PDF.
Usage: python3.14 watermark_pdf.py INPUT OUTPUT --text TEXT --font FONT
--font-size POINTS [options]
Requires PyMuPDF and fonttools. Run with --help for layout options.
"""
from __future__ import annotations
import argparse
import math
import os
import sys
from collections.abc import Iterable
from dataclasses import dataclass
from pathlib import Path
from typing import Any, cast
import fitz # PyMuPDF
from fontTools.pens.basePen import BasePen
from fontTools.ttLib import TTFont, TTLibError
Point = tuple[float, float]
RGBA = tuple[int, int, int, int]
PathCommand = tuple[str, tuple]
def warn(msg: str) -> None:
print(f"[WARN] {msg}", file=sys.stderr)
def clamp01(x: float) -> float:
return max(0.0, min(1.0, x))
def rgba_to_pymupdf(color: RGBA) -> tuple[tuple[float, float, float], float]:
r, g, b, a = color
rgb = (clamp01(r / 255.0), clamp01(g / 255.0), clamp01(b / 255.0))
alpha = clamp01(a / 255.0)
return rgb, alpha
def parse_rgba(text: str) -> RGBA:
parts = [p.strip() for p in text.split(",")]
if len(parts) != 4:
raise ValueError("RGBA must have exactly 4 comma-separated integers")
vals = tuple(int(x) for x in parts)
if any(v < 0 or v > 255 for v in vals):
raise ValueError("RGBA components must be in range 0..255")
return vals # type: ignore[return-value]
def is_font_file(path: Path) -> bool:
return path.is_file() and path.suffix.lower() in {".ttf", ".otf", ".ttc", ".otc"}
def normalize_font_name(s: str) -> str:
return "".join(ch.lower() for ch in s if ch.isalnum())
def get_system_font_dirs() -> list[Path]:
home = Path.home()
dirs: list[Path] = []
if sys.platform.startswith("linux"):
dirs.extend(
[
Path("/usr/share/fonts"),
Path("/usr/local/share/fonts"),
home / ".fonts",
home / ".local/share/fonts",
]
)
elif sys.platform == "darwin":
dirs.extend(
[
Path("/System/Library/Fonts"),
Path("/Library/Fonts"),
home / "Library/Fonts",
]
)
elif os.name == "nt":
windir = os.environ.get("WINDIR", r"C:\Windows")
dirs.extend([Path(windir) / "Fonts"])
else:
dirs.extend(
[
Path("/usr/share/fonts"),
Path("/usr/local/share/fonts"),
home / ".fonts",
home / ".local/share/fonts",
]
)
return [d for d in dirs if d.exists()]
def iter_font_files() -> Iterable[Path]:
for root in get_system_font_dirs():
try:
for path in root.rglob("*"):
if is_font_file(path):
yield path
except OSError:
continue
def extract_font_names(font_path: Path) -> list[str]:
names: list[str] = []
try:
font = TTFont(str(font_path), lazy=True)
name_table = font["name"]
for rec in name_table.names:
try:
names.append(str(rec.toUnicode()))
except Exception:
continue
font.close()
except Exception:
pass
return names
def find_font(font: str) -> Path:
candidate = Path(font).expanduser()
if candidate.exists() and is_font_file(candidate):
return candidate.resolve()
target = normalize_font_name(font)
# First try a fast match against the file name.
filename_hits: list[Path] = []
for path in iter_font_files():
stem = normalize_font_name(path.stem)
full = normalize_font_name(path.name)
if target in (stem, full) or target in stem:
filename_hits.append(path)
if len(filename_hits) == 1:
return filename_hits[0].resolve()
# Then inspect internal font names.
for path in filename_hits + [p for p in iter_font_files() if p not in set(filename_hits)]:
for name in extract_font_names(path):
n = normalize_font_name(name)
if n == target or target in n:
return path.resolve()
raise FileNotFoundError(f"Font not found: {font}")
class OutlineRecordingPen(BasePen):
"""
Record glyph outlines as commands:
M (move)
L (line)
C (cubic bezier)
Z (close)
qCurveTo is converted to a cubic Bezier curve.
"""
def __init__(self, glyphSet: Any) -> None:
super().__init__(glyphSet)
self.commands: list[PathCommand] = []
self._current_contour_start: Point | None = None
self._current_point: Point | None = None
def _moveTo(self, pt: Point) -> None:
p = (float(pt[0]), float(pt[1]))
self.commands.append(("M", (p,)))
self._current_contour_start = p
self._current_point = p
def _lineTo(self, pt: Point) -> None:
p = (float(pt[0]), float(pt[1]))
self.commands.append(("L", (p,)))
self._current_point = p
def _curveToOne(self, pt1: Point, pt2: Point, pt3: Point) -> None:
c1 = (float(pt1[0]), float(pt1[1]))
c2 = (float(pt2[0]), float(pt2[1]))
p = (float(pt3[0]), float(pt3[1]))
self.commands.append(("C", (c1, c2, p)))
self._current_point = p
def _qCurveToOne(self, pt1: Point, pt2: Point) -> None:
"""
Quadratic bezier P0->P2 with control P1
converted to cubic:
C1 = P0 + 2/3*(P1-P0)
C2 = P2 + 2/3*(P1-P2)
"""
if self._current_point is None:
raise ValueError("Quadratic curve encountered without current point")
p0 = self._current_point
q1 = (float(pt1[0]), float(pt1[1]))
p2f = (float(pt2[0]), float(pt2[1]))
c1 = (
p0[0] + (2.0 / 3.0) * (q1[0] - p0[0]),
p0[1] + (2.0 / 3.0) * (q1[1] - p0[1]),
)
c2 = (
p2f[0] + (2.0 / 3.0) * (q1[0] - p2f[0]),
p2f[1] + (2.0 / 3.0) * (q1[1] - p2f[1]),
)
self.commands.append(("C", (c1, c2, p2f)))
self._current_point = p2f
def _closePath(self) -> None:
self.commands.append(("Z", ()))
self._current_point = self._current_contour_start
def _endPath(self) -> None:
self.commands.append(("Z", ()))
self._current_point = self._current_contour_start
@dataclass
class TextOutline:
commands: list[PathCommand]
bbox: tuple[float, float, float, float] # minx, miny, maxx, maxy
class FontOutlineBuilder:
def __init__(self, font_path: str | Path) -> None:
self.font_path = Path(font_path)
self.font = TTFont(str(self.font_path))
self.glyph_set = self.font.getGlyphSet()
self.best_cmap: dict[int, str] = self.font.getBestCmap() or {}
head_table = cast(Any, self.font["head"])
self.units_per_em = float(head_table.unitsPerEm)
self.hmtx = self.font["hmtx"]
self._glyph_cache: dict[str, list[PathCommand]] = {}
def close(self) -> None:
self.font.close()
def _glyph_commands(self, glyph_name: str) -> list[PathCommand]:
if glyph_name in self._glyph_cache:
return self._glyph_cache[glyph_name]
glyph = self.glyph_set[glyph_name]
pen = OutlineRecordingPen(self.glyph_set)
glyph.draw(pen)
self._glyph_cache[glyph_name] = pen.commands
return pen.commands
def _glyph_advance(self, glyph_name: str) -> float:
advance, _ = self.hmtx[glyph_name]
return float(advance)
def build_text_outline(self, text: str) -> TextOutline:
if not text:
raise ValueError("Watermark text is empty")
commands: list[PathCommand] = []
cursor_x = 0.0
minx = math.inf
miny = math.inf
maxx = -math.inf
maxy = -math.inf
def update_bbox_point(p: Point) -> None:
nonlocal minx, miny, maxx, maxy
minx = min(minx, p[0])
miny = min(miny, p[1])
maxx = max(maxx, p[0])
maxy = max(maxy, p[1])
for ch in text.replace("\n", " "):
code = ord(ch)
glyph_name = self.best_cmap.get(code)
if glyph_name is None:
# Fallback for whitespace or missing glyphs.
if ch == " ":
space_glyph = self.best_cmap.get(ord(" "))
if space_glyph is not None:
cursor_x += self._glyph_advance(space_glyph)
else:
cursor_x += self.units_per_em * 0.33
continue
raise ValueError(
f"Character {ch!r} (U+{code:04X}) is not available in font {self.font_path}"
)
glyph_cmds = self._glyph_commands(glyph_name)
advance = self._glyph_advance(glyph_name)
for cmd, data in glyph_cmds:
if cmd == "M":
p = (data[0][0] + cursor_x, data[0][1])
commands.append(("M", (p,)))
update_bbox_point(p)
elif cmd == "L":
p = (data[0][0] + cursor_x, data[0][1])
commands.append(("L", (p,)))
update_bbox_point(p)
elif cmd == "C":
c1 = (data[0][0] + cursor_x, data[0][1])
c2 = (data[1][0] + cursor_x, data[1][1])
p = (data[2][0] + cursor_x, data[2][1])
commands.append(("C", (c1, c2, p)))
update_bbox_point(c1)
update_bbox_point(c2)
update_bbox_point(p)
elif cmd == "Z":
commands.append(("Z", ()))
cursor_x += advance
if not commands:
raise ValueError("No drawable glyph outlines were produced")
if minx is math.inf:
# For example, a string containing only spaces.
minx, miny, maxx, maxy = 0.0, 0.0, cursor_x, self.units_per_em * 0.5
return TextOutline(commands=commands, bbox=(minx, miny, maxx, maxy))
def scale_outline(outline: TextOutline, scale: float) -> TextOutline:
cmds: list[PathCommand] = []
def sp(p: Point) -> Point:
return (p[0] * scale, p[1] * scale)
for cmd, data in outline.commands:
if cmd == "M":
cmds.append(("M", (sp(data[0]),)))
elif cmd == "L":
cmds.append(("L", (sp(data[0]),)))
elif cmd == "C":
cmds.append(("C", (sp(data[0]), sp(data[1]), sp(data[2]))))
else:
cmds.append((cmd, data))
x0, y0, x1, y1 = outline.bbox
return TextOutline(cmds, (x0 * scale, y0 * scale, x1 * scale, y1 * scale))
def transform_point(
p: Point,
rotation_deg: float,
tx: float,
ty: float,
y_flip: bool = True,
) -> Point:
"""
Convert font coordinates to PDF coordinates.
Font coords:
+Y points up
PDF coords:
+Y points down
Optionally flip Y, then rotate, then translate.
"""
x, y = p
if y_flip:
y = -y
angle = math.radians(rotation_deg)
ca = math.cos(angle)
sa = math.sin(angle)
xr = x * ca - y * sa
yr = x * sa + y * ca
return (xr + tx, yr + ty)
def transformed_bbox(
bbox: tuple[float, float, float, float],
rotation_deg: float,
tx: float,
ty: float,
) -> tuple[float, float, float, float]:
x0, y0, x1, y1 = bbox
corners = [
transform_point((x0, y0), rotation_deg, tx, ty),
transform_point((x1, y0), rotation_deg, tx, ty),
transform_point((x1, y1), rotation_deg, tx, ty),
transform_point((x0, y1), rotation_deg, tx, ty),
]
xs = [p[0] for p in corners]
ys = [p[1] for p in corners]
return min(xs), min(ys), max(xs), max(ys)
def draw_outline_on_page(
page: fitz.Page,
outline: TextOutline,
origin: Point,
rotation_deg: float,
color: RGBA,
overlay: bool,
) -> None:
rgb, alpha = rgba_to_pymupdf(color)
shape = page.new_shape()
current_start: Point | None = None
current_point: Point | None = None
ox, oy = origin
for cmd, data in outline.commands:
if cmd == "M":
p = transform_point(data[0], rotation_deg, ox, oy)
current_start = p
current_point = p
elif cmd == "L":
if current_point is None:
raise ValueError("Path line without current point")
p = transform_point(data[0], rotation_deg, ox, oy)
shape.draw_line(fitz.Point(*current_point), fitz.Point(*p))
current_point = p
elif cmd == "C":
if current_point is None:
raise ValueError("Path curve without current point")
c1 = transform_point(data[0], rotation_deg, ox, oy)
c2 = transform_point(data[1], rotation_deg, ox, oy)
p = transform_point(data[2], rotation_deg, ox, oy)
shape.draw_bezier(
fitz.Point(*current_point),
fitz.Point(*c1),
fitz.Point(*c2),
fitz.Point(*p),
)
current_point = p
elif cmd == "Z":
if current_point is not None and current_start is not None:
if (
abs(current_point[0] - current_start[0]) > 1e-9
or abs(current_point[1] - current_start[1]) > 1e-9
):
shape.draw_line(fitz.Point(*current_point), fitz.Point(*current_start))
current_point = current_start
shape.finish(
color=None,
fill=rgb,
fill_opacity=alpha,
even_odd=False,
closePath=False,
)
shape.commit(overlay=overlay)
def resolve_single_origin(
page_rect: fitz.Rect,
outline_bbox_scaled: tuple[float, float, float, float],
rotation_deg: float,
position: str | tuple[float, float],
margin: float = 24.0,
) -> Point:
x0, y0, x1, y1 = outline_bbox_scaled
# Bounding box after rotation around origin=(0, 0).
rx0, ry0, rx1, ry1 = transformed_bbox((x0, y0, x1, y1), rotation_deg, 0.0, 0.0)
rwidth = rx1 - rx0
rheight = ry1 - ry0
if isinstance(position, tuple):
return position
pos = position.lower()
if pos == "center":
tx = page_rect.x0 + (page_rect.width - rwidth) / 2.0 - rx0
ty = page_rect.y0 + (page_rect.height - rheight) / 2.0 - ry0
elif pos == "top-left":
tx = page_rect.x0 + margin - rx0
ty = page_rect.y0 + margin - ry0
elif pos == "top-right":
tx = page_rect.x1 - margin - rwidth - rx0
ty = page_rect.y0 + margin - ry0
elif pos == "bottom-left":
tx = page_rect.x0 + margin - rx0
ty = page_rect.y1 - margin - rheight - ry0
elif pos == "bottom-right":
tx = page_rect.x1 - margin - rwidth - rx0
ty = page_rect.y1 - margin - rheight - ry0
else:
raise ValueError(
"Unknown single position. Expected one of: "
"center, top-left, top-right, bottom-left, bottom-right, or (x, y)"
)
return tx, ty
def outline_flow_origins(
page_rect: fitz.Rect,
outline_bbox: tuple[float, float, float, float],
rotation_deg: float,
line_spacing: float = 1.2,
stagger: bool = True,
) -> Iterable[Point]:
x0, y0, x1, y1 = outline_bbox
# Account for rotation.
rx0, ry0, rx1, ry1 = transformed_bbox(
(x0, y0, x1, y1),
rotation_deg,
0.0,
0.0,
)
rwidth = rx1 - rx0
rheight = ry1 - ry0
step_x = rwidth
step_y = rheight * line_spacing
y = page_rect.y0 - rheight
row = 0
while y <= page_rect.y1 + rheight:
x_offset = step_x / 2.0 if (stagger and row % 2) else 0.0
x = page_rect.x0 - rwidth + x_offset
while x <= page_rect.x1 + rwidth:
yield (x - rx0, y - ry0)
x += step_x
y += step_y
row += 1
def outline_tile_origins(
page_rect: fitz.Rect,
outline_bbox_scaled: tuple[float, float, float, float],
rotation_deg: float,
spacing: tuple[float, float],
) -> Iterable[Point]:
sx, sy = spacing
if sx <= 0 or sy <= 0:
raise ValueError("Tile spacing must be positive")
x0, y0, x1, y1 = outline_bbox_scaled
rx0, ry0, rx1, ry1 = transformed_bbox((x0, y0, x1, y1), rotation_deg, 0.0, 0.0)
rwidth = rx1 - rx0
rheight = ry1 - ry0
step_x = rwidth + sx
step_y = rheight + sy
start_x = page_rect.x0 - rwidth - abs(rx0) - sx
start_y = page_rect.y0 - rheight - abs(ry0) - sy
end_x = page_rect.x1 + rwidth + sx
end_y = page_rect.y1 + rheight + sy
y = start_y
row = 0
while y <= end_y:
x = start_x + (step_x / 2.0 if row % 2 else 0.0)
while x <= end_x:
yield (x - rx0, y - ry0)
x += step_x
y += step_y
row += 1
def render_text_fallback(
page: fitz.Page,
text: str,
font_path: Path,
font_size: float,
color: RGBA,
layout: str,
position: str | tuple[float, float],
spacing: tuple[float, float],
rotation: float,
overlay: bool,
) -> None:
"""
Fallback: regular selectable text.
Arbitrary rotation uses a morph whose support depends on the PyMuPDF version.
If it fails, render unrotated text and write a warning to stderr.
"""
rgb, alpha = rgba_to_pymupdf(color)
page_rect = page.rect
# The width/height estimate is intentionally approximate for fallback rendering.
est_width = max(font_size * 0.6 * len(text), font_size)
est_height = font_size
def insert_one(pt: Point, use_rotation: bool) -> None:
kwargs = {
"point": fitz.Point(*pt),
"text": text,
"fontsize": font_size,
"fontfile": str(font_path),
"color": rgb,
"fill_opacity": alpha,
"overlay": overlay,
}
if use_rotation and abs(rotation) > 1e-9:
angle = math.radians(rotation)
# morph=(fixpoint, matrix)
m = fitz.Matrix(
math.cos(angle),
math.sin(angle),
-math.sin(angle),
math.cos(angle),
0,
0,
)
page.insert_text(morph=(fitz.Point(*pt), m), **kwargs)
else:
page.insert_text(**kwargs)
if layout == "single":
if isinstance(position, tuple):
pt = position
else:
pos = position.lower()
margin = 24.0
if pos == "center":
pt = (
page_rect.x0 + (page_rect.width - est_width) / 2.0,
page_rect.y0 + (page_rect.height + est_height) / 2.0,
)
elif pos == "top-left":
pt = (page_rect.x0 + margin, page_rect.y0 + margin + est_height)
elif pos == "top-right":
pt = (page_rect.x1 - margin - est_width, page_rect.y0 + margin + est_height)
elif pos == "bottom-left":
pt = (page_rect.x0 + margin, page_rect.y1 - margin)
elif pos == "bottom-right":
pt = (page_rect.x1 - margin - est_width, page_rect.y1 - margin)
else:
raise ValueError("Unknown single position")
try:
insert_one(pt, use_rotation=True)
except Exception as e:
warn(f"text fallback with rotation failed ({e}); inserting without rotation")
insert_one(pt, use_rotation=False)
elif layout == "tile":
sx, sy = spacing
if sx <= 0 or sy <= 0:
raise ValueError("Tile spacing must be positive")
step_x = est_width + sx
step_y = est_height + sy
y = page_rect.y0 - est_height
row = 0
while y <= page_rect.y1 + est_height:
x = page_rect.x0 - est_width + (step_x / 2.0 if row % 2 else 0.0)
while x <= page_rect.x1 + est_width:
try:
insert_one((x, y), use_rotation=True)
except Exception as e:
warn(f"text fallback with rotation failed ({e}); inserting without rotation")
insert_one((x, y), use_rotation=False)
x += step_x
y += step_y
row += 1
elif layout == "flow":
sx, sy = spacing
if sx <= 0 or sy <= 0:
raise ValueError("Tile spacing must be positive")
step_x = est_width
step_y = est_height * 1.2 # line spacing
y = page_rect.y0 - est_height
row = 0
while y <= page_rect.y1 + est_height:
x_offset = step_x / 2.0 if row % 2 else 0.0
x = page_rect.x0 - est_width + x_offset
while x <= page_rect.x1 + est_width:
try:
insert_one((x, y), use_rotation=True)
except Exception as e:
warn(f"text fallback with rotation failed ({e}); inserting without rotation")
insert_one((x, y), use_rotation=False)
x += step_x
y += step_y
row += 1
else:
raise ValueError("layout must be 'single' or 'tile' or 'flow'")
def add_watermark(
input_pdf: str | Path,
output_pdf: str | Path,
text: str,
font: str | Path,
font_size: float,
color: RGBA,
render_mode: str = "auto", # auto | outline | text
layout: str = "tile", # tile | single
position: str | tuple[float, float] = "center",
spacing: tuple[float, float] = (180.0, 120.0),
rotation: float = 45.0,
overlay: bool = True,
) -> None:
render_mode = render_mode.lower()
layout = layout.lower()
if render_mode not in {"auto", "outline", "text"}:
raise ValueError("render_mode must be one of: auto, outline, text")
if layout not in {"single", "tile", "flow"}:
raise ValueError("layout must be one of: single, tile, flow")
if font_size <= 0:
raise ValueError("font_size must be positive")
font_path = find_font(str(font))
doc = fitz.open(str(input_pdf))
try:
if render_mode == "text":
for page in doc:
render_text_fallback(
page=page,
text=text,
font_path=font_path,
font_size=font_size,
color=color,
layout=layout,
position=position,
spacing=spacing,
rotation=rotation,
overlay=overlay,
)
doc.save(str(output_pdf), garbage=4, deflate=True)
return
builder = FontOutlineBuilder(font_path)
try:
base_outline = builder.build_text_outline(text)
scaled_outline = scale_outline(base_outline, font_size / builder.units_per_em)
finally:
builder.close()
for page in doc:
if layout == "single":
origin = resolve_single_origin(
page_rect=page.rect,
outline_bbox_scaled=scaled_outline.bbox,
rotation_deg=rotation,
position=position,
)
draw_outline_on_page(
page=page,
outline=scaled_outline,
origin=origin,
rotation_deg=rotation,
color=color,
overlay=overlay,
)
elif layout == "flow":
for origin in outline_flow_origins(
page_rect=page.rect,
outline_bbox=scaled_outline.bbox,
rotation_deg=rotation,
line_spacing=1.2,
stagger=True,
):
draw_outline_on_page(
page=page,
outline=scaled_outline,
origin=origin,
rotation_deg=rotation,
color=color,
overlay=overlay,
)
else:
for origin in outline_tile_origins(
page_rect=page.rect,
outline_bbox_scaled=scaled_outline.bbox,
rotation_deg=rotation,
spacing=spacing,
):
draw_outline_on_page(
page=page,
outline=scaled_outline,
origin=origin,
rotation_deg=rotation,
color=color,
overlay=overlay,
)
doc.save(str(output_pdf), garbage=4, deflate=True)
except Exception as e:
if render_mode == "outline":
raise
warn(f"outline rendering failed: {e}")
warn("falling back to selectable text mode")
for page in doc:
render_text_fallback(
page=page,
text=text,
font_path=font_path,
font_size=font_size,
color=color,
layout=layout,
position=position,
spacing=spacing,
rotation=rotation,
overlay=overlay,
)
doc.save(str(output_pdf), garbage=4, deflate=True)
finally:
doc.close()
def parse_position(value: str) -> str | tuple[float, float]:
value = value.strip()
if "," in value:
parts = [x.strip() for x in value.split(",")]
if len(parts) != 2:
raise argparse.ArgumentTypeError("position must be named position or 'x,y'")
try:
return (float(parts[0]), float(parts[1]))
except ValueError as e:
raise argparse.ArgumentTypeError(str(e)) from e
return value
def parse_spacing(value: str) -> tuple[float, float]:
parts = [x.strip() for x in value.split(",")]
if len(parts) != 2:
raise argparse.ArgumentTypeError("spacing must be 'x,y'")
try:
sx = float(parts[0])
sy = float(parts[1])
except ValueError as e:
raise argparse.ArgumentTypeError(str(e)) from e
return sx, sy
def build_cli() -> argparse.ArgumentParser:
p = argparse.ArgumentParser(
description="Add watermark to PDF as outlines (non-selectable) or text fallback."
)
p.add_argument("input_pdf", help="Input PDF path")
p.add_argument("output_pdf", help="Output PDF path")
p.add_argument("--text", required=True, help="Watermark text")
p.add_argument(
"--font",
required=True,
help="Font name from system or path to font file",
)
p.add_argument("--font-size", type=float, required=True, help="Font size in points")
p.add_argument(
"--color",
type=parse_rgba,
default=(128, 128, 128, 64),
help="RGBA color, e.g. 128,128,128,64",
)
p.add_argument(
"--render-mode",
choices=["auto", "outline", "text"],
default="auto",
help="Rendering mode",
)
p.add_argument(
"--layout",
choices=["single", "tile", "flow"],
default="tile",
help="Watermark placement layout",
)
p.add_argument(
"--position",
type=parse_position,
default="center",
help="Named position for single layout or 'x,y'",
)
p.add_argument(
"--spacing",
type=parse_spacing,
default=(180.0, 120.0),
help="Tile spacing 'x,y'",
)
p.add_argument(
"--rotation",
type=float,
default=0.0,
help="Rotation angle in degrees",
)
p.add_argument(
"--layer",
choices=["overlay", "background"],
default="overlay",
help="Whether to draw watermark above or below page content",
)
return p
def main() -> int:
parser = build_cli()
args = parser.parse_args()
overlay = args.layer == "overlay"
try:
add_watermark(
input_pdf=args.input_pdf,
output_pdf=args.output_pdf,
text=args.text,
font=args.font,
font_size=args.font_size,
color=args.color,
render_mode=args.render_mode,
layout=args.layout,
position=args.position,
spacing=args.spacing,
rotation=args.rotation,
overlay=overlay,
)
return 0
except (FileNotFoundError, ValueError, TTLibError, fitz.FileDataError) as e:
print(f"[ERROR] {e}", file=sys.stderr)
return 2
except Exception as e:
print(f"[ERROR] Unexpected failure: {e}", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())