-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathconvert_svg.py
More file actions
59 lines (45 loc) · 1.9 KB
/
Copy pathconvert_svg.py
File metadata and controls
59 lines (45 loc) · 1.9 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
#!/usr/bin/env python3
"""Convert SVG diagrams to high-resolution PNG for LaTeX/ePub compatibility.
Uses rsvg-convert (from librsvg) — install with: brew install librsvg
SVG files in images/ are converted to PNG at 2x resolution (suitable for
both print PDF and retina HTML). The PNGs are saved alongside the SVGs.
"""
import os
import subprocess
import sys
from pathlib import Path
def convert_svg_to_png(svg_path: Path, png_path: Path, dpi: int = 192):
"""Convert SVG to PNG using rsvg-convert at the specified DPI.
Default 192 DPI = 2x scale (CSS reference is 96 DPI).
For print, 288 DPI = 3x is also reasonable.
"""
cmd = ['rsvg-convert', '-d', str(dpi), '-p', str(dpi),
'-o', str(png_path), str(svg_path)]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
print(f" ERROR: {result.stderr.strip()}", file=sys.stderr)
sys.exit(1)
size = png_path.stat().st_size
print(f" {svg_path.name} -> {png_path.name} ({size:,} bytes, {dpi} DPI)")
def main():
images_dir = Path(__file__).parent / "images"
svgs = sorted(images_dir.glob("*.svg"))
if not svgs:
print("No SVG files found in images/")
return
# Check rsvg-convert is available
if subprocess.run(['which', 'rsvg-convert'], capture_output=True).returncode != 0:
print("ERROR: rsvg-convert not found. Install with: brew install librsvg",
file=sys.stderr)
sys.exit(1)
print(f"Converting {len(svgs)} SVG(s) to PNG...")
for svg_path in svgs:
png_path = svg_path.with_suffix('.png')
# Skip if PNG is newer than SVG
if png_path.exists() and png_path.stat().st_mtime > svg_path.stat().st_mtime:
print(f" {svg_path.name} -> (up to date, skipping)")
continue
convert_svg_to_png(svg_path, png_path)
print("Done.")
if __name__ == "__main__":
main()