-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwatermark_tool.py
More file actions
371 lines (300 loc) · 11.6 KB
/
watermark_tool.py
File metadata and controls
371 lines (300 loc) · 11.6 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
#!/usr/bin/env python3
"""Add text watermarks to PDF files and images on Windows.
Examples:
python watermark_tool.py input.pdf output.pdf --text "CONFIDENTIAL" --position tile
python watermark_tool.py photo.jpg photo_marked.jpg --text "SAMPLE" --opacity 0.2
"""
from __future__ import annotations
import argparse
import io
from pathlib import Path
from typing import Iterable, List, Tuple
PDF_EXTENSIONS = {".pdf"}
IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".bmp", ".tif", ".tiff", ".webp"}
def parse_color(value: str) -> Tuple[int, int, int]:
text = value.strip().lstrip("#")
if len(text) != 6:
raise argparse.ArgumentTypeError("--color must be a hex value like #FF0000")
try:
red = int(text[0:2], 16)
green = int(text[2:4], 16)
blue = int(text[4:6], 16)
except ValueError as exc:
raise argparse.ArgumentTypeError("--color must be a valid hex value like #FF0000") from exc
return red, green, blue
def parse_opacity(value: str) -> float:
try:
opacity = float(value)
except ValueError as exc:
raise argparse.ArgumentTypeError("--opacity must be a number between 0 and 1") from exc
if not (0.0 <= opacity <= 1.0):
raise argparse.ArgumentTypeError("--opacity must be between 0 and 1")
return opacity
def detect_mode(input_path: Path, requested_mode: str) -> str:
if requested_mode != "auto":
return requested_mode
suffix = input_path.suffix.lower()
if suffix in PDF_EXTENSIONS:
return "pdf"
if suffix in IMAGE_EXTENSIONS:
return "image"
raise ValueError(
"Could not detect file type from extension. Use --mode pdf or --mode image explicitly."
)
def get_image_font(font_size: int, font_path: str | None):
from PIL import ImageFont
candidates: List[str] = []
if font_path:
candidates.append(font_path)
candidates.extend(
[
r"C:\\Windows\\Fonts\\arial.ttf",
r"C:\\Windows\\Fonts\\segoeui.ttf",
r"C:\\Windows\\Fonts\\meiryo.ttc",
]
)
for candidate in candidates:
path = Path(candidate)
if path.exists():
try:
return ImageFont.truetype(str(path), font_size)
except OSError:
continue
return ImageFont.load_default()
def image_text_size(text: str, font) -> Tuple[int, int]:
from PIL import Image, ImageDraw
dummy = Image.new("RGBA", (1, 1), (0, 0, 0, 0))
drawer = ImageDraw.Draw(dummy)
left, top, right, bottom = drawer.textbbox((0, 0), text, font=font)
return max(1, right - left), max(1, bottom - top)
def draw_rotated_text(layer, text: str, center: Tuple[float, float], font, fill, angle: float) -> None:
from PIL import Image, ImageDraw
text_width, text_height = image_text_size(text, font)
patch = Image.new("RGBA", (text_width + 20, text_height + 20), (0, 0, 0, 0))
drawer = ImageDraw.Draw(patch)
drawer.text((10, 10), text, font=font, fill=fill)
rotated = patch.rotate(angle, expand=True)
x = int(center[0] - rotated.width / 2)
y = int(center[1] - rotated.height / 2)
layer.paste(rotated, (x, y), rotated)
def single_position_centers(
width: int,
height: int,
position: str,
margin: int,
) -> List[Tuple[float, float]]:
if position == "center":
return [(width / 2, height / 2)]
if position == "top-left":
return [(margin, margin)]
if position == "top-right":
return [(width - margin, margin)]
if position == "bottom-left":
return [(margin, height - margin)]
if position == "bottom-right":
return [(width - margin, height - margin)]
raise ValueError(f"Unsupported position: {position}")
def tile_centers(width: int, height: int, step_x: int, step_y: int) -> Iterable[Tuple[float, float]]:
y = -step_y
while y <= height + step_y:
x = -step_x
while x <= width + step_x:
yield (x, y)
x += step_x
y += step_y
def add_watermark_to_image(
input_path: Path,
output_path: Path,
text: str,
font_size: int,
opacity: float,
color: Tuple[int, int, int],
angle: float,
position: str,
margin: int,
font_path: str | None,
) -> None:
try:
from PIL import Image
except ModuleNotFoundError as exc:
raise RuntimeError("Pillow is required for image watermarking. Install with pip install -r requirements.txt") from exc
base = Image.open(input_path).convert("RGBA")
overlay = Image.new("RGBA", base.size, (0, 0, 0, 0))
font = get_image_font(font_size, font_path)
alpha = int(opacity * 255)
fill = (color[0], color[1], color[2], alpha)
text_width, text_height = image_text_size(text, font)
if position == "tile":
step_x = max(int(text_width * 2.4), 180)
step_y = max(int(text_height * 2.8), 140)
for center in tile_centers(base.width, base.height, step_x, step_y):
draw_rotated_text(overlay, text, center, font, fill, angle)
else:
centers = single_position_centers(base.width, base.height, position, margin)
for center in centers:
draw_rotated_text(overlay, text, center, font, fill, angle)
merged = Image.alpha_composite(base, overlay)
output_path.parent.mkdir(parents=True, exist_ok=True)
if output_path.suffix.lower() in {".jpg", ".jpeg", ".bmp"}:
merged.convert("RGB").save(output_path)
else:
merged.save(output_path)
def draw_pdf_single_watermark(
canvas_obj,
page_width: float,
page_height: float,
text: str,
font_size: int,
angle: float,
position: str,
margin: int,
) -> None:
from reportlab.pdfbase import pdfmetrics
text_width = pdfmetrics.stringWidth(text, "Helvetica", font_size)
if position == "center":
center_x, center_y = page_width / 2, page_height / 2
elif position == "top-left":
center_x, center_y = margin, page_height - margin
elif position == "top-right":
center_x, center_y = page_width - margin, page_height - margin
elif position == "bottom-left":
center_x, center_y = margin, margin
elif position == "bottom-right":
center_x, center_y = page_width - margin, margin
else:
raise ValueError(f"Unsupported position: {position}")
canvas_obj.saveState()
canvas_obj.translate(center_x, center_y)
canvas_obj.rotate(angle)
canvas_obj.drawString(-text_width / 2, -font_size / 2, text)
canvas_obj.restoreState()
def draw_pdf_tiled_watermark(
canvas_obj,
page_width: float,
page_height: float,
text: str,
font_size: int,
angle: float,
margin: int,
) -> None:
from reportlab.pdfbase import pdfmetrics
text_width = pdfmetrics.stringWidth(text, "Helvetica", font_size)
step_x = max(text_width * 2.0, 180)
step_y = max(font_size * 3.0, 120)
canvas_obj.saveState()
canvas_obj.translate(page_width / 2, page_height / 2)
canvas_obj.rotate(angle)
y = -page_height
while y <= page_height:
x = -page_width
while x <= page_width:
canvas_obj.drawString(x, y, text)
x += step_x
y += step_y
canvas_obj.restoreState()
def add_watermark_to_pdf(
input_path: Path,
output_path: Path,
text: str,
font_size: int,
opacity: float,
color: Tuple[int, int, int],
angle: float,
position: str,
margin: int,
) -> None:
try:
from pypdf import PdfReader, PdfWriter
except ModuleNotFoundError as exc:
raise RuntimeError("pypdf is required for PDF watermarking. Install with pip install -r requirements.txt") from exc
try:
from reportlab.lib.colors import Color
from reportlab.pdfgen import canvas
except ModuleNotFoundError as exc:
raise RuntimeError("reportlab is required for PDF watermarking. Install with pip install -r requirements.txt") from exc
reader = PdfReader(str(input_path))
writer = PdfWriter()
for page in reader.pages:
width = float(page.mediabox.width)
height = float(page.mediabox.height)
packet = io.BytesIO()
c = canvas.Canvas(packet, pagesize=(width, height))
c.setFont("Helvetica", font_size)
fill_color = Color(color[0] / 255.0, color[1] / 255.0, color[2] / 255.0, alpha=opacity)
c.setFillColor(fill_color)
if hasattr(c, "setFillAlpha"):
c.setFillAlpha(opacity)
if position == "tile":
draw_pdf_tiled_watermark(c, width, height, text, font_size, angle, margin)
else:
draw_pdf_single_watermark(c, width, height, text, font_size, angle, position, margin)
c.save()
packet.seek(0)
watermark_page = PdfReader(packet).pages[0]
page.merge_page(watermark_page)
writer.add_page(page)
output_path.parent.mkdir(parents=True, exist_ok=True)
with output_path.open("wb") as output_file:
writer.write(output_file)
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Add text watermarks to PDF files or images.")
parser.add_argument("input", type=Path, help="Input file path (.pdf, .jpg, .png, etc.)")
parser.add_argument("output", type=Path, help="Output file path")
parser.add_argument("--text", required=True, help="Watermark text")
parser.add_argument("--mode", choices=["auto", "pdf", "image"], default="auto", help="How to process input")
parser.add_argument("--font-size", type=int, default=48, help="Font size (default: 48)")
parser.add_argument("--opacity", type=parse_opacity, default=0.2, help="Opacity from 0 to 1 (default: 0.2)")
parser.add_argument("--color", type=parse_color, default=(220, 0, 0), help="Hex color (default: #DC0000)")
parser.add_argument("--angle", type=float, default=35.0, help="Rotation angle in degrees (default: 35)")
parser.add_argument(
"--position",
choices=["center", "tile", "top-left", "top-right", "bottom-left", "bottom-right"],
default="tile",
help="Watermark position (default: tile)",
)
parser.add_argument("--margin", type=int, default=36, help="Margin for corner positions (default: 36)")
parser.add_argument("--font-path", default=None, help="Optional TTF/TTC font path for image watermarking")
return parser
def main() -> int:
parser = build_parser()
args = parser.parse_args()
if not args.input.exists() or not args.input.is_file():
parser.error(f"Input file not found: {args.input}")
if args.font_size <= 0:
parser.error("--font-size must be > 0")
try:
mode = detect_mode(args.input, args.mode)
except ValueError as exc:
parser.error(str(exc))
try:
if mode == "pdf":
add_watermark_to_pdf(
input_path=args.input,
output_path=args.output,
text=args.text,
font_size=args.font_size,
opacity=args.opacity,
color=args.color,
angle=args.angle,
position=args.position,
margin=args.margin,
)
else:
add_watermark_to_image(
input_path=args.input,
output_path=args.output,
text=args.text,
font_size=args.font_size,
opacity=args.opacity,
color=args.color,
angle=args.angle,
position=args.position,
margin=args.margin,
font_path=args.font_path,
)
except Exception as exc:
parser.error(str(exc))
print(f"Saved: {args.output}")
return 0
if __name__ == "__main__":
raise SystemExit(main())