feat: enhance PNG rendering with size and padding options

main
Antonio De Lucreziis 5 months ago
parent 6f9df83e39
commit 2dddff8a71

@ -453,16 +453,17 @@ def _render_png_with_magick(
run_logger: RunLogger,
section_title: str,
png_name: str = "diagram.png",
size: str | None = None,
size: tuple[int, int] | None = None,
padding: int = 0,
) -> Optional[Path]:
png_path = run_dir / png_name
# Use first page only; remove alpha to avoid transparency surprises.
# Base command: use first page, 300 DPI, and flatten transparency
cmd = [
"magick",
"-density",
"300",
str(pdf_path) + "[0]",
f"{pdf_path}[0]",
"-background",
"white",
"-alpha",
@ -471,23 +472,33 @@ def _render_png_with_magick(
"off",
]
# If size is specified, add center-fit resizing (e.g., "1200x630")
if size:
width, height = size
# Calculate the target size for the content after subtracting margins
inner_width = width - (2 * padding)
inner_height = height - (2 * padding)
inner_size = f"{inner_width}x{inner_height}"
size_str = f"{width}x{height}"
cmd.extend(
[
"-resize",
size,
inner_size, # Resize to fit within margin bounds
"-gravity",
"center",
"center", # Center the image
"-extent",
size,
size_str, # Pad out to the full requested size
]
)
elif padding > 0:
# If no size is fixed but margin is requested, use -border
cmd.extend(["-bordercolor", "white", "-border", str(padding)])
cmd.append(str(png_path))
code, out = _run_cmd(cmd, cwd=run_dir, timeout_s=5, py_logger=run_logger.py)
run_logger.section(section_title, out)
if code == 0 and png_path.exists():
return png_path
return None
@ -599,7 +610,8 @@ def _compile_phase(
run_log,
section_title=f"{phase}.magick.preview",
png_name="preview.png",
size="1200x630",
size=(1200, 630),
padding=20,
)
if pdf_path
else None

Loading…
Cancel
Save