Skip to content

Commit

Permalink
Add safe_pdf and save_svg helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
domdfcoding committed May 1, 2024
1 parent f3677cf commit 521a5fc
Showing 1 changed file with 42 additions and 3 deletions.
45 changes: 42 additions & 3 deletions gunshotmatch_reports/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,19 @@
#

# stdlib
from io import BytesIO
from io import BytesIO, StringIO
from typing import List, Tuple, TypeVar

# 3rd party
from matplotlib import pyplot as plt # type: ignore[import]
import matplotlib # type: ignore[import]
from domdf_python_tools.paths import PathPlus
from domdf_python_tools.typing import PathLike
from matplotlib import pyplot as plt
from matplotlib.figure import Figure # type: ignore[import]
from reportlab.graphics.shapes import Drawing # type: ignore[import]
from svglib.svglib import svg2rlg # type: ignore[import]

__all__ = ["extend_list", "figure_to_drawing", "scale"]
__all__ = ["extend_list", "figure_to_drawing", "scale", "save_pdf", "save_svg"]


def scale(drawing: Drawing, scale: float) -> Drawing:
Expand Down Expand Up @@ -89,3 +92,39 @@ def extend_list(l: List[_T], fillvalue: _T, length: int) -> List[_T]:
assert len(l) == length

return l


def save_pdf(fig: Figure, filename: PathLike) -> None:
"""
Save a PDF without a creation date.
:param fig:
:param filename:
.. versionadded:: 0.6.0
"""

fig.savefig(filename, format="pdf", metadata={"CreationDate": None})


def save_svg(fig: Figure, filename: PathLike) -> None:
"""
Save an SVG with fixed hashsalt and without a creation date.
:param fig:
:param filename:
.. versionadded:: 0.6.0
"""

filename_p = PathPlus(filename)

current_hashsalt = matplotlib.rcParams.get("svg.hashsalt")

try:
matplotlib.rcParams["svg.hashsalt"] = filename_p.name
s = StringIO()
fig.savefig(s, format="svg", metadata={"Date": None})
filename_p.write_clean(s.getvalue())
finally:
matplotlib.rcParams["svg.hashsalt"] = current_hashsalt

0 comments on commit 521a5fc

Please sign in to comment.