feat: enhance PNG rendering with size and padding options

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

@ -453,16 +453,17 @@ def _render_png_with_magick(
run_logger: RunLogger, run_logger: RunLogger,
section_title: str, section_title: str,
png_name: str = "diagram.png", png_name: str = "diagram.png",
size: str | None = None, size: tuple[int, int] | None = None,
padding: int = 0,
) -> Optional[Path]: ) -> Optional[Path]:
png_path = run_dir / png_name 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 = [ cmd = [
"magick", "magick",
"-density", "-density",
"300", "300",
str(pdf_path) + "[0]", f"{pdf_path}[0]",
"-background", "-background",
"white", "white",
"-alpha", "-alpha",
@ -471,23 +472,33 @@ def _render_png_with_magick(
"off", "off",
] ]
# If size is specified, add center-fit resizing (e.g., "1200x630")
if size: 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( cmd.extend(
[ [
"-resize", "-resize",
size, inner_size, # Resize to fit within margin bounds
"-gravity", "-gravity",
"center", "center", # Center the image
"-extent", "-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)) cmd.append(str(png_path))
code, out = _run_cmd(cmd, cwd=run_dir, timeout_s=5, py_logger=run_logger.py) code, out = _run_cmd(cmd, cwd=run_dir, timeout_s=5, py_logger=run_logger.py)
run_logger.section(section_title, out) run_logger.section(section_title, out)
if code == 0 and png_path.exists(): if code == 0 and png_path.exists():
return png_path return png_path
return None return None
@ -599,7 +610,8 @@ def _compile_phase(
run_log, run_log,
section_title=f"{phase}.magick.preview", section_title=f"{phase}.magick.preview",
png_name="preview.png", png_name="preview.png",
size="1200x630", size=(1200, 630),
padding=20,
) )
if pdf_path if pdf_path
else None else None

Loading…
Cancel
Save