-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path12_image_replace.py
More file actions
80 lines (61 loc) · 2.53 KB
/
Copy path12_image_replace.py
File metadata and controls
80 lines (61 loc) · 2.53 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
"""
12 - Image find & replace.
- Scan a PDF for embedded images
- Get metadata: dimensions, color space, format, page locations
- Replace all images or specific ones by index/page
This is the killer feature for company rebrands: swap a logo across hundreds
of branded documents in one pass.
Run:
python examples/12_image_replace.py
Note: requires a PDF with embedded images and a replacement image file.
If samples/sample.pdf has no images the script reports that and exits.
"""
from pathlib import Path
from _common import (
header, info, success, warn, ensure_output_dir, get_sample_pdf,
SAMPLES_DIR, init_license,
)
import exis_pdfeditor
def main() -> None:
init_license()
header("Demo 12 - Image Replace")
sample = get_sample_pdf()
out = ensure_output_dir()
# Step 1: find all images in the sample
info("Scanning for embedded images...")
result = exis_pdfeditor.find_images(str(sample))
if result.totalImages == 0:
warn(f"{sample.name} has no embedded images. Drop a PDF with images into samples/ and re-run.")
return
success(f"Found {result.totalImages} images across {result.pagesSearched} pages")
for img in result.images[:5]:
print(
f" Image {img.index}: {img.pixelWidth}x{img.pixelHeight} "
f"{img.colorSpace} {img.format} (pages: {img.pageNumbers})"
)
if result.totalImages > 5:
print(f" ... and {result.totalImages - 5} more")
# Step 2: extract images to disk
info("Extracting images to output/12-extracted-images/...")
extracted_dir = out / "12-extracted-images"
extracted_dir.mkdir(exist_ok=True)
exis_pdfeditor.find_images(str(sample), output_dir=str(extracted_dir))
success(f"Extracted to: {extracted_dir}")
# Step 3: replace images
# Look for a replacement image in samples/
replacement = next((SAMPLES_DIR.glob("logo.png")), None) \
or next((SAMPLES_DIR.glob("*.png")), None) \
or next((SAMPLES_DIR.glob("*.jpg")), None)
if replacement is None:
warn("No replacement image found in samples/ - skipping replacement step.")
warn("Drop a logo.png (or any .png/.jpg) into samples/ to test image replacement.")
return
info(f"Replacing all images with: {replacement.name}")
replace_result = exis_pdfeditor.replace_image(
str(sample),
str(out / "12-replaced.pdf"),
str(replacement),
)
success(f"Replaced {replace_result.imagesReplaced} of {replace_result.imagesFound} images")
if __name__ == "__main__":
main()