Add HTML template placeholder for diagram_png_base64 (#371)

This will enable users to replace the SVG diagram with an embedded PNG,
that is an improved work-around when the SVG output from Graphviz
is not looking good. Suggested as work-around for Graphviz bug in
https://github.com/wireviz/WireViz/issues/175#issuecomment-2132206026

Co-authored-by: kvid <kvid@users.noreply.github.com>
This commit is contained in:
Daniel Rojas 2025-03-01 18:31:07 +01:00
parent 287c47a65e
commit 6c30d0c40a

View File

@ -18,6 +18,20 @@ from wireviz.wv_utils import (
mime_subtype_replacements = {"jpg": "jpeg", "tif": "tiff"} mime_subtype_replacements = {"jpg": "jpeg", "tif": "tiff"}
# TODO: Share cache and code between data_URI_base64() and embed_svg_images()
def data_URI_base64(file: Union[str, Path], media: str = "image") -> str:
"""Return Base64-encoded data URI of input file."""
file = Path(file)
b64 = base64.b64encode(file.read_bytes()).decode("utf-8")
uri = f"data:{media}/{get_mime_subtype(file)};base64, {b64}"
# print(f"data_URI_base64('{file}', '{media}') -> {len(uri)}-character URI")
if len(uri) > 65535:
print(
"data_URI_base64(): Warning: Browsers might have different URI length limitations"
)
return uri
def embed_svg_images(svg_in: str, base_path: Union[str, Path] = Path.cwd()) -> str: def embed_svg_images(svg_in: str, base_path: Union[str, Path] = Path.cwd()) -> str:
images_b64 = {} # cache of base64-encoded images images_b64 = {} # cache of base64-encoded images
@ -126,7 +140,7 @@ def generate_html_output(
"<!-- %fontname% -->": options.fontname, "<!-- %fontname% -->": options.fontname,
"<!-- %bgcolor% -->": options.bgcolor.html, "<!-- %bgcolor% -->": options.bgcolor.html,
"<!-- %diagram% -->": svgdata, "<!-- %diagram% -->": svgdata,
# TODO: "<!-- %diagram_png_base64% -->": base64 of png file "<!-- %diagram_png_base64% -->": data_URI_base64(f"{filename}.png"),
"<!-- %filename% -->": str(filename), "<!-- %filename% -->": str(filename),
"<!-- %filename_stem% -->": Path(filename).stem, "<!-- %filename_stem% -->": Path(filename).stem,
"<!-- %bom% -->": bom_html, "<!-- %bom% -->": bom_html,