import atexit import codecs import functools import logging import math import os import pathlib import re import shutil import subprocess import sys import tempfile import weakref import matplotlib as mpl from matplotlib import _png, cbook, font_manager as fm, __version__, rcParams from matplotlib.backend_bases import ( _Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase, RendererBase) from matplotlib.backends.backend_mixed import MixedModeRenderer from matplotlib.path import Path from matplotlib.figure import Figure from matplotlib._pylab_helpers import Gcf _log = logging.getLogger(__name__) ############################################################################### @cbook.deprecated("3.0") def get_texcommand(): """Get chosen TeX system from rc.""" texsystem_options = ["xelatex", "lualatex", "pdflatex"] texsystem = rcParams["pgf.texsystem"] return texsystem if texsystem in texsystem_options else "xelatex" def get_fontspec(): """Build fontspec preamble from rc.""" latex_fontspec = [] texcommand = rcParams["pgf.texsystem"] if texcommand != "pdflatex": latex_fontspec.append("\\usepackage{fontspec}") if texcommand != "pdflatex" and rcParams["pgf.rcfonts"]: families = ["serif", "sans\\-serif", "monospace"] commands = ["setmainfont", "setsansfont", "setmonofont"] for family, command in zip(families, commands): # 1) Forward slashes also work on Windows, so don't mess with # backslashes. 2) The dirname needs to include a separator. path = pathlib.Path(fm.findfont(family)) latex_fontspec.append(r"\%s{%s}[Path=%s]" % ( command, path.name, path.parent.as_posix() + "/")) return "\n".join(latex_fontspec) def get_preamble(): """Get LaTeX preamble from rc.""" return rcParams["pgf.preamble"] ############################################################################### # This almost made me cry!!! # In the end, it's better to use only one unit for all coordinates, since the # arithmetic in latex seems to produce inaccurate conversions. latex_pt_to_in = 1. / 72.27 latex_in_to_pt = 1. / latex_pt_to_in mpl_pt_to_in = 1. / 72. mpl_in_to_pt = 1. / mpl_pt_to_in ############################################################################### # helper functions NO_ESCAPE = r"(? 3 else 1.0 if has_fill: writeln(self.fh, r"\definecolor{currentfill}{rgb}{%f,%f,%f}" % tuple(rgbFace[:3])) writeln(self.fh, r"\pgfsetfillcolor{currentfill}") if has_fill and fillopacity != 1.0: writeln(self.fh, r"\pgfsetfillopacity{%f}" % fillopacity) # linewidth and color lw = gc.get_linewidth() * mpl_pt_to_in * latex_in_to_pt stroke_rgba = gc.get_rgb() writeln(self.fh, r"\pgfsetlinewidth{%fpt}" % lw) writeln(self.fh, r"\definecolor{currentstroke}{rgb}{%f,%f,%f}" % stroke_rgba[:3]) writeln(self.fh, r"\pgfsetstrokecolor{currentstroke}") if strokeopacity != 1.0: writeln(self.fh, r"\pgfsetstrokeopacity{%f}" % strokeopacity) # line style dash_offset, dash_list = gc.get_dashes() if dash_list is None: writeln(self.fh, r"\pgfsetdash{}{0pt}") else: writeln(self.fh, r"\pgfsetdash{%s}{%fpt}" % ("".join(r"{%fpt}" % dash for dash in dash_list), dash_offset)) def _print_pgf_path(self, gc, path, transform, rgbFace=None): f = 1. / self.dpi # check for clip box / ignore clip for filled paths bbox = gc.get_clip_rectangle() if gc else None if bbox and (rgbFace is None): p1, p2 = bbox.get_points() clip = (p1[0], p1[1], p2[0], p2[1]) else: clip = None # build path for points, code in path.iter_segments(transform, clip=clip): if code == Path.MOVETO: x, y = tuple(points) writeln(self.fh, r"\pgfpathmoveto{\pgfqpoint{%fin}{%fin}}" % (f * x, f * y)) elif code == Path.CLOSEPOLY: writeln(self.fh, r"\pgfpathclose") elif code == Path.LINETO: x, y = tuple(points) writeln(self.fh, r"\pgfpathlineto{\pgfqpoint{%fin}{%fin}}" % (f * x, f * y)) elif code == Path.CURVE3: cx, cy, px, py = tuple(points) coords = cx * f, cy * f, px * f, py * f writeln(self.fh, r"\pgfpathquadraticcurveto" r"{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}" % coords) elif code == Path.CURVE4: c1x, c1y, c2x, c2y, px, py = tuple(points) coords = c1x * f, c1y * f, c2x * f, c2y * f, px * f, py * f writeln(self.fh, r"\pgfpathcurveto" r"{\pgfqpoint{%fin}{%fin}}" r"{\pgfqpoint{%fin}{%fin}}" r"{\pgfqpoint{%fin}{%fin}}" % coords) def _pgf_path_draw(self, stroke=True, fill=False): actions = [] if stroke: actions.append("stroke") if fill: actions.append("fill") writeln(self.fh, r"\pgfusepath{%s}" % ",".join(actions)) def option_scale_image(self): # docstring inherited return True def option_image_nocomposite(self): # docstring inherited return not rcParams['image.composite_image'] def draw_image(self, gc, x, y, im, transform=None): # docstring inherited h, w = im.shape[:2] if w == 0 or h == 0: return # save the images to png files path = os.path.dirname(self.fh.name) fname = os.path.splitext(os.path.basename(self.fh.name))[0] fname_img = "%s-img%d.png" % (fname, self.image_counter) self.image_counter += 1 _png.write_png(im[::-1], os.path.join(path, fname_img)) # reference the image in the pgf picture writeln(self.fh, r"\begin{pgfscope}") self._print_pgf_clip(gc) f = 1. / self.dpi # from display coords to inch if transform is None: writeln(self.fh, r"\pgfsys@transformshift{%fin}{%fin}" % (x * f, y * f)) w, h = w * f, h * f else: tr1, tr2, tr3, tr4, tr5, tr6 = transform.frozen().to_values() writeln(self.fh, r"\pgfsys@transformcm{%f}{%f}{%f}{%f}{%fin}{%fin}" % (tr1 * f, tr2 * f, tr3 * f, tr4 * f, (tr5 + x) * f, (tr6 + y) * f)) w = h = 1 # scale is already included in the transform interp = str(transform is None).lower() # interpolation in PDF reader writeln(self.fh, r"\pgftext[left,bottom]" r"{\pgfimage[interpolate=%s,width=%fin,height=%fin]{%s}}" % (interp, w, h, fname_img)) writeln(self.fh, r"\end{pgfscope}") def draw_tex(self, gc, x, y, s, prop, angle, ismath="TeX!", mtext=None): # docstring inherited self.draw_text(gc, x, y, s, prop, angle, ismath, mtext) def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): # docstring inherited # prepare string for tex s = common_texification(s) prop_cmds = _font_properties_str(prop) s = r"%s %s" % (prop_cmds, s) writeln(self.fh, r"\begin{pgfscope}") alpha = gc.get_alpha() if alpha != 1.0: writeln(self.fh, r"\pgfsetfillopacity{%f}" % alpha) writeln(self.fh, r"\pgfsetstrokeopacity{%f}" % alpha) rgb = tuple(gc.get_rgb())[:3] writeln(self.fh, r"\definecolor{textcolor}{rgb}{%f,%f,%f}" % rgb) writeln(self.fh, r"\pgfsetstrokecolor{textcolor}") writeln(self.fh, r"\pgfsetfillcolor{textcolor}") s = r"\color{textcolor}" + s f = 1.0 / self.figure.dpi text_args = [] if mtext and ( (angle == 0 or mtext.get_rotation_mode() == "anchor") and mtext.get_verticalalignment() != "center_baseline"): # if text anchoring can be supported, get the original coordinates # and add alignment information pos = mtext.get_unitless_position() x, y = mtext.get_transform().transform_point(pos) text_args.append("x=%fin" % (x * f)) text_args.append("y=%fin" % (y * f)) halign = {"left": "left", "right": "right", "center": ""} valign = {"top": "top", "bottom": "bottom", "baseline": "base", "center": ""} text_args.append(halign[mtext.get_horizontalalignment()]) text_args.append(valign[mtext.get_verticalalignment()]) else: # if not, use the text layout provided by matplotlib text_args.append("x=%fin" % (x * f)) text_args.append("y=%fin" % (y * f)) text_args.append("left") text_args.append("base") if angle != 0: text_args.append("rotate=%f" % angle) writeln(self.fh, r"\pgftext[%s]{%s}" % (",".join(text_args), s)) writeln(self.fh, r"\end{pgfscope}") def get_text_width_height_descent(self, s, prop, ismath): # docstring inherited # check if the math is supposed to be displaystyled s = common_texification(s) # get text metrics in units of latex pt, convert to display units w, h, d = self.latexManager.get_width_height_descent(s, prop) # TODO: this should be latex_pt_to_in instead of mpl_pt_to_in # but having a little bit more space around the text looks better, # plus the bounding box reported by LaTeX is VERY narrow f = mpl_pt_to_in * self.dpi return w * f, h * f, d * f def flipy(self): # docstring inherited return False def get_canvas_width_height(self): # docstring inherited return self.figure.get_figwidth(), self.figure.get_figheight() def points_to_pixels(self, points): # docstring inherited return points * mpl_pt_to_in * self.dpi def new_gc(self): # docstring inherited return GraphicsContextPgf() class GraphicsContextPgf(GraphicsContextBase): pass ######################################################################## class TmpDirCleaner: remaining_tmpdirs = set() @staticmethod def add(tmpdir): TmpDirCleaner.remaining_tmpdirs.add(tmpdir) @staticmethod def cleanup_remaining_tmpdirs(): for tmpdir in TmpDirCleaner.remaining_tmpdirs: error_message = "error deleting tmp directory {}".format(tmpdir) shutil.rmtree( tmpdir, onerror=lambda *args: _log.error(error_message)) class FigureCanvasPgf(FigureCanvasBase): filetypes = {"pgf": "LaTeX PGF picture", "pdf": "LaTeX compiled PGF picture", "png": "Portable Network Graphics", } def get_default_filetype(self): return 'pdf' def _print_pgf_to_fh(self, fh, *args, dryrun=False, bbox_inches_restore=None, **kwargs): if dryrun: renderer = RendererPgf(self.figure, None, dummy=True) self.figure.draw(renderer) return header_text = """%% Creator: Matplotlib, PGF backend %% %% To include the figure in your LaTeX document, write %% \\input{.pgf} %% %% Make sure the required packages are loaded in your preamble %% \\usepackage{pgf} %% %% Figures using additional raster images can only be included by \\input if %% they are in the same directory as the main LaTeX file. For loading figures %% from other directories you can use the `import` package %% \\usepackage{import} %% and then include the figures with %% \\import{}{.pgf} %% """ # append the preamble used by the backend as a comment for debugging header_info_preamble = ["%% Matplotlib used the following preamble"] for line in get_preamble().splitlines(): header_info_preamble.append("%% " + line) for line in get_fontspec().splitlines(): header_info_preamble.append("%% " + line) header_info_preamble.append("%%") header_info_preamble = "\n".join(header_info_preamble) # get figure size in inch w, h = self.figure.get_figwidth(), self.figure.get_figheight() dpi = self.figure.get_dpi() # create pgfpicture environment and write the pgf code fh.write(header_text) fh.write(header_info_preamble) fh.write("\n") writeln(fh, r"\begingroup") writeln(fh, r"\makeatletter") writeln(fh, r"\begin{pgfpicture}") writeln(fh, r"\pgfpathrectangle{\pgfpointorigin}{\pgfqpoint{%fin}{%fin}}" % (w, h)) writeln(fh, r"\pgfusepath{use as bounding box, clip}") renderer = MixedModeRenderer(self.figure, w, h, dpi, RendererPgf(self.figure, fh), bbox_inches_restore=bbox_inches_restore) self.figure.draw(renderer) # end the pgfpicture environment writeln(fh, r"\end{pgfpicture}") writeln(fh, r"\makeatother") writeln(fh, r"\endgroup") def print_pgf(self, fname_or_fh, *args, **kwargs): """ Output pgf commands for drawing the figure so it can be included and rendered in latex documents. """ if kwargs.get("dryrun", False): self._print_pgf_to_fh(None, *args, **kwargs) return with cbook.open_file_cm(fname_or_fh, "w", encoding="utf-8") as file: if not cbook.file_requires_unicode(file): file = codecs.getwriter("utf-8")(file) self._print_pgf_to_fh(file, *args, **kwargs) def _print_pdf_to_fh(self, fh, *args, **kwargs): w, h = self.figure.get_figwidth(), self.figure.get_figheight() try: # create temporary directory for compiling the figure tmpdir = tempfile.mkdtemp(prefix="mpl_pgf_") fname_pgf = os.path.join(tmpdir, "figure.pgf") fname_tex = os.path.join(tmpdir, "figure.tex") fname_pdf = os.path.join(tmpdir, "figure.pdf") # print figure to pgf and compile it with latex self.print_pgf(fname_pgf, *args, **kwargs) latex_preamble = get_preamble() latex_fontspec = get_fontspec() latexcode = """ \\documentclass[12pt]{minimal} \\usepackage[paperwidth=%fin, paperheight=%fin, margin=0in]{geometry} %s %s \\usepackage{pgf} \\begin{document} \\centering \\input{figure.pgf} \\end{document}""" % (w, h, latex_preamble, latex_fontspec) pathlib.Path(fname_tex).write_text(latexcode, encoding="utf-8") texcommand = rcParams["pgf.texsystem"] cbook._check_and_log_subprocess( [texcommand, "-interaction=nonstopmode", "-halt-on-error", "figure.tex"], _log, cwd=tmpdir) # copy file contents to target with open(fname_pdf, "rb") as fh_src: shutil.copyfileobj(fh_src, fh) finally: try: shutil.rmtree(tmpdir) except: TmpDirCleaner.add(tmpdir) def print_pdf(self, fname_or_fh, *args, **kwargs): """Use LaTeX to compile a Pgf generated figure to PDF.""" if kwargs.get("dryrun", False): self._print_pgf_to_fh(None, *args, **kwargs) return with cbook.open_file_cm(fname_or_fh, "wb") as file: self._print_pdf_to_fh(file, *args, **kwargs) def _print_png_to_fh(self, fh, *args, **kwargs): converter = make_pdf_to_png_converter() try: # create temporary directory for pdf creation and png conversion tmpdir = tempfile.mkdtemp(prefix="mpl_pgf_") fname_pdf = os.path.join(tmpdir, "figure.pdf") fname_png = os.path.join(tmpdir, "figure.png") # create pdf and try to convert it to png self.print_pdf(fname_pdf, *args, **kwargs) converter(fname_pdf, fname_png, dpi=self.figure.dpi) # copy file contents to target with open(fname_png, "rb") as fh_src: shutil.copyfileobj(fh_src, fh) finally: try: shutil.rmtree(tmpdir) except: TmpDirCleaner.add(tmpdir) def print_png(self, fname_or_fh, *args, **kwargs): """Use LaTeX to compile a pgf figure to pdf and convert it to png.""" if kwargs.get("dryrun", False): self._print_pgf_to_fh(None, *args, **kwargs) return with cbook.open_file_cm(fname_or_fh, "wb") as file: self._print_png_to_fh(file, *args, **kwargs) def get_renderer(self): return RendererPgf(self.figure, None, dummy=True) class FigureManagerPgf(FigureManagerBase): pass @_Backend.export class _BackendPgf(_Backend): FigureCanvas = FigureCanvasPgf FigureManager = FigureManagerPgf def _cleanup_all(): LatexManager._cleanup_remaining_instances() TmpDirCleaner.cleanup_remaining_tmpdirs() atexit.register(_cleanup_all) class PdfPages: """ A multi-page PDF file using the pgf backend Examples -------- >>> import matplotlib.pyplot as plt >>> # Initialize: >>> with PdfPages('foo.pdf') as pdf: ... # As many times as you like, create a figure fig and save it: ... fig = plt.figure() ... pdf.savefig(fig) ... # When no figure is specified the current figure is saved ... pdf.savefig() """ __slots__ = ( '_outputfile', 'keep_empty', '_tmpdir', '_basename', '_fname_tex', '_fname_pdf', '_n_figures', '_file', 'metadata', ) def __init__(self, filename, *, keep_empty=True, metadata=None): """ Create a new PdfPages object. Parameters ---------- filename : str Plots using :meth:`PdfPages.savefig` will be written to a file at this location. Any older file with the same name is overwritten. keep_empty : bool, optional If set to False, then empty pdf files will be deleted automatically when closed. metadata : dictionary, optional Information dictionary object (see PDF reference section 10.2.1 'Document Information Dictionary'), e.g.: `{'Creator': 'My software', 'Author': 'Me', 'Title': 'Awesome fig'}` The standard keys are `'Title'`, `'Author'`, `'Subject'`, `'Keywords'`, `'Producer'`, `'Creator'` and `'Trapped'`. Values have been predefined for `'Creator'` and `'Producer'`. They can be removed by setting them to the empty string. """ self._outputfile = filename self._n_figures = 0 self.keep_empty = keep_empty self.metadata = metadata or {} # create temporary directory for compiling the figure self._tmpdir = tempfile.mkdtemp(prefix="mpl_pgf_pdfpages_") self._basename = 'pdf_pages' self._fname_tex = os.path.join(self._tmpdir, self._basename + ".tex") self._fname_pdf = os.path.join(self._tmpdir, self._basename + ".pdf") self._file = open(self._fname_tex, 'wb') def _write_header(self, width_inches, height_inches): supported_keys = { 'title', 'author', 'subject', 'keywords', 'creator', 'producer', 'trapped' } infoDict = { 'creator': 'matplotlib %s, https://matplotlib.org' % __version__, 'producer': 'matplotlib pgf backend %s' % __version__, } metadata = {k.lower(): v for k, v in self.metadata.items()} infoDict.update(metadata) hyperref_options = '' for k, v in infoDict.items(): if k not in supported_keys: raise ValueError( 'Not a supported pdf metadata field: "{}"'.format(k) ) hyperref_options += 'pdf' + k + '={' + str(v) + '},' latex_preamble = get_preamble() latex_fontspec = get_fontspec() latex_header = r"""\PassOptionsToPackage{{ {metadata} }}{{hyperref}} \RequirePackage{{hyperref}} \documentclass[12pt]{{minimal}} \usepackage[ paperwidth={width}in, paperheight={height}in, margin=0in ]{{geometry}} {preamble} {fontspec} \usepackage{{pgf}} \setlength{{\parindent}}{{0pt}} \begin{{document}}%% """.format( width=width_inches, height=height_inches, preamble=latex_preamble, fontspec=latex_fontspec, metadata=hyperref_options, ) self._file.write(latex_header.encode('utf-8')) def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def close(self): """ Finalize this object, running LaTeX in a temporary directory and moving the final pdf file to `filename`. """ self._file.write(rb'\end{document}\n') self._file.close() if self._n_figures > 0: try: self._run_latex() finally: try: shutil.rmtree(self._tmpdir) except: TmpDirCleaner.add(self._tmpdir) elif self.keep_empty: open(self._outputfile, 'wb').close() def _run_latex(self): texcommand = rcParams["pgf.texsystem"] cbook._check_and_log_subprocess( [texcommand, "-interaction=nonstopmode", "-halt-on-error", os.path.basename(self._fname_tex)], _log, cwd=self._tmpdir) # copy file contents to target shutil.copyfile(self._fname_pdf, self._outputfile) def savefig(self, figure=None, **kwargs): """ Saves a :class:`~matplotlib.figure.Figure` to this file as a new page. Any other keyword arguments are passed to :meth:`~matplotlib.figure.Figure.savefig`. Parameters ---------- figure : :class:`~matplotlib.figure.Figure` or int, optional Specifies what figure is saved to file. If not specified, the active figure is saved. If a :class:`~matplotlib.figure.Figure` instance is provided, this figure is saved. If an int is specified, the figure instance to save is looked up by number. """ if not isinstance(figure, Figure): if figure is None: manager = Gcf.get_active() else: manager = Gcf.get_fig_manager(figure) if manager is None: raise ValueError("No figure {}".format(figure)) figure = manager.canvas.figure try: orig_canvas = figure.canvas figure.canvas = FigureCanvasPgf(figure) width, height = figure.get_size_inches() if self._n_figures == 0: self._write_header(width, height) else: # \pdfpagewidth and \pdfpageheight exist on pdftex, xetex, and # luatex<0.85; they were renamed to \pagewidth and \pageheight # on luatex>=0.85. self._file.write( br'\newpage' br'\ifdefined\pdfpagewidth\pdfpagewidth' br'\else\pagewidth\fi=%ain' br'\ifdefined\pdfpageheight\pdfpageheight' br'\else\pageheight\fi=%ain' b'%%\n' % (width, height) ) figure.savefig(self._file, format="pgf", **kwargs) self._n_figures += 1 finally: figure.canvas = orig_canvas def get_pagecount(self): """ Returns the current number of pages in the multipage pdf file. """ return self._n_figures