diff --git a/gunshotmatch_reports/utils.py b/gunshotmatch_reports/utils.py index 9e03621..413595c 100644 --- a/gunshotmatch_reports/utils.py +++ b/gunshotmatch_reports/utils.py @@ -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: @@ -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