backend_pgf.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188
  1. import atexit
  2. import codecs
  3. import datetime
  4. import functools
  5. import logging
  6. import math
  7. import os
  8. import pathlib
  9. import re
  10. import shutil
  11. import subprocess
  12. import sys
  13. import tempfile
  14. import weakref
  15. from PIL import Image
  16. import matplotlib as mpl
  17. from matplotlib import cbook, font_manager as fm
  18. from matplotlib.backend_bases import (
  19. _Backend, _check_savefig_extra_args, FigureCanvasBase, FigureManagerBase,
  20. GraphicsContextBase, RendererBase)
  21. from matplotlib.backends.backend_mixed import MixedModeRenderer
  22. from matplotlib.backends.backend_pdf import (
  23. _create_pdf_info_dict, _datetime_to_pdf)
  24. from matplotlib.path import Path
  25. from matplotlib.figure import Figure
  26. from matplotlib._pylab_helpers import Gcf
  27. _log = logging.getLogger(__name__)
  28. # Note: When formatting floating point values, it is important to use the
  29. # %f/{:f} format rather than %s/{} to avoid triggering scientific notation,
  30. # which is not recognized by TeX.
  31. def get_fontspec():
  32. """Build fontspec preamble from rc."""
  33. latex_fontspec = []
  34. texcommand = mpl.rcParams["pgf.texsystem"]
  35. if texcommand != "pdflatex":
  36. latex_fontspec.append("\\usepackage{fontspec}")
  37. if texcommand != "pdflatex" and mpl.rcParams["pgf.rcfonts"]:
  38. families = ["serif", "sans\\-serif", "monospace"]
  39. commands = ["setmainfont", "setsansfont", "setmonofont"]
  40. for family, command in zip(families, commands):
  41. # 1) Forward slashes also work on Windows, so don't mess with
  42. # backslashes. 2) The dirname needs to include a separator.
  43. path = pathlib.Path(fm.findfont(family))
  44. latex_fontspec.append(r"\%s{%s}[Path=%s]" % (
  45. command, path.name, path.parent.as_posix() + "/"))
  46. return "\n".join(latex_fontspec)
  47. def get_preamble():
  48. """Get LaTeX preamble from rc."""
  49. return mpl.rcParams["pgf.preamble"]
  50. ###############################################################################
  51. # This almost made me cry!!!
  52. # In the end, it's better to use only one unit for all coordinates, since the
  53. # arithmetic in latex seems to produce inaccurate conversions.
  54. latex_pt_to_in = 1. / 72.27
  55. latex_in_to_pt = 1. / latex_pt_to_in
  56. mpl_pt_to_in = 1. / 72.
  57. mpl_in_to_pt = 1. / mpl_pt_to_in
  58. ###############################################################################
  59. # helper functions
  60. NO_ESCAPE = r"(?<!\\)(?:\\\\)*"
  61. re_mathsep = re.compile(NO_ESCAPE + r"\$")
  62. @cbook.deprecated("3.2")
  63. def repl_escapetext(m):
  64. return "\\" + m.group(1)
  65. @cbook.deprecated("3.2")
  66. def repl_mathdefault(m):
  67. return m.group(0)[:-len(m.group(1))]
  68. _replace_escapetext = functools.partial(
  69. # When the next character is _, ^, $, or % (not preceded by an escape),
  70. # insert a backslash.
  71. re.compile(NO_ESCAPE + "(?=[_^$%])").sub, "\\\\")
  72. _replace_mathdefault = functools.partial(
  73. # Replace \mathdefault (when not preceded by an escape) by empty string.
  74. re.compile(NO_ESCAPE + r"(\\mathdefault)").sub, "")
  75. def common_texification(text):
  76. r"""
  77. Do some necessary and/or useful substitutions for texts to be included in
  78. LaTeX documents.
  79. This distinguishes text-mode and math-mode by replacing the math separator
  80. ``$`` with ``\(\displaystyle %s\)``. Escaped math separators (``\$``)
  81. are ignored.
  82. The following characters are escaped in text segments: ``_^$%``
  83. """
  84. # Sometimes, matplotlib adds the unknown command \mathdefault.
  85. # Not using \mathnormal instead since this looks odd for the latex cm font.
  86. text = _replace_mathdefault(text)
  87. # split text into normaltext and inline math parts
  88. parts = re_mathsep.split(text)
  89. for i, s in enumerate(parts):
  90. if not i % 2:
  91. # textmode replacements
  92. s = _replace_escapetext(s)
  93. else:
  94. # mathmode replacements
  95. s = r"\(\displaystyle %s\)" % s
  96. parts[i] = s
  97. return "".join(parts)
  98. def writeln(fh, line):
  99. # every line of a file included with \\input must be terminated with %
  100. # if not, latex will create additional vertical spaces for some reason
  101. fh.write(line)
  102. fh.write("%\n")
  103. def _font_properties_str(prop):
  104. # translate font properties to latex commands, return as string
  105. commands = []
  106. families = {"serif": r"\rmfamily", "sans": r"\sffamily",
  107. "sans-serif": r"\sffamily", "monospace": r"\ttfamily"}
  108. family = prop.get_family()[0]
  109. if family in families:
  110. commands.append(families[family])
  111. elif (any(font.name == family for font in fm.fontManager.ttflist)
  112. and mpl.rcParams["pgf.texsystem"] != "pdflatex"):
  113. commands.append(r"\setmainfont{%s}\rmfamily" % family)
  114. else:
  115. pass # print warning?
  116. size = prop.get_size_in_points()
  117. commands.append(r"\fontsize{%f}{%f}" % (size, size * 1.2))
  118. styles = {"normal": r"", "italic": r"\itshape", "oblique": r"\slshape"}
  119. commands.append(styles[prop.get_style()])
  120. boldstyles = ["semibold", "demibold", "demi", "bold", "heavy",
  121. "extra bold", "black"]
  122. if prop.get_weight() in boldstyles:
  123. commands.append(r"\bfseries")
  124. commands.append(r"\selectfont")
  125. return "".join(commands)
  126. def _metadata_to_str(key, value):
  127. """Convert metadata key/value to a form that hyperref accepts."""
  128. if isinstance(value, datetime.datetime):
  129. value = _datetime_to_pdf(value)
  130. elif key == 'Trapped':
  131. value = value.name.decode('ascii')
  132. else:
  133. value = str(value)
  134. return f'{key}={{{value}}}'
  135. def make_pdf_to_png_converter():
  136. """Return a function that converts a pdf file to a png file."""
  137. if shutil.which("pdftocairo"):
  138. def cairo_convert(pdffile, pngfile, dpi):
  139. cmd = ["pdftocairo", "-singlefile", "-png", "-r", "%d" % dpi,
  140. pdffile, os.path.splitext(pngfile)[0]]
  141. subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  142. return cairo_convert
  143. try:
  144. gs_info = mpl._get_executable_info("gs")
  145. except mpl.ExecutableNotFoundError:
  146. pass
  147. else:
  148. def gs_convert(pdffile, pngfile, dpi):
  149. cmd = [gs_info.executable,
  150. '-dQUIET', '-dSAFER', '-dBATCH', '-dNOPAUSE', '-dNOPROMPT',
  151. '-dUseCIEColor', '-dTextAlphaBits=4',
  152. '-dGraphicsAlphaBits=4', '-dDOINTERPOLATE',
  153. '-sDEVICE=png16m', '-sOutputFile=%s' % pngfile,
  154. '-r%d' % dpi, pdffile]
  155. subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  156. return gs_convert
  157. raise RuntimeError("No suitable pdf to png renderer found.")
  158. class LatexError(Exception):
  159. def __init__(self, message, latex_output=""):
  160. super().__init__(message)
  161. self.latex_output = latex_output
  162. class LatexManager:
  163. """
  164. The LatexManager opens an instance of the LaTeX application for
  165. determining the metrics of text elements. The LaTeX environment can be
  166. modified by setting fonts and/or a custom preamble in `.rcParams`.
  167. """
  168. _unclean_instances = weakref.WeakSet()
  169. @staticmethod
  170. def _build_latex_header():
  171. latex_preamble = get_preamble()
  172. latex_fontspec = get_fontspec()
  173. # Create LaTeX header with some content, else LaTeX will load some math
  174. # fonts later when we don't expect the additional output on stdout.
  175. # TODO: is this sufficient?
  176. latex_header = [
  177. r"\documentclass{minimal}",
  178. # Include TeX program name as a comment for cache invalidation.
  179. # TeX does not allow this to be the first line.
  180. rf"% !TeX program = {mpl.rcParams['pgf.texsystem']}",
  181. # Test whether \includegraphics supports interpolate option.
  182. r"\usepackage{graphicx}",
  183. latex_preamble,
  184. latex_fontspec,
  185. r"\begin{document}",
  186. r"text $math \mu$", # force latex to load fonts now
  187. r"\typeout{pgf_backend_query_start}",
  188. ]
  189. return "\n".join(latex_header)
  190. @classmethod
  191. def _get_cached_or_new(cls):
  192. """
  193. Return the previous LatexManager if the header and tex system did not
  194. change, or a new instance otherwise.
  195. """
  196. return cls._get_cached_or_new_impl(cls._build_latex_header())
  197. @classmethod
  198. @functools.lru_cache(1)
  199. def _get_cached_or_new_impl(cls, header): # Helper for _get_cached_or_new.
  200. return cls()
  201. @staticmethod
  202. def _cleanup_remaining_instances():
  203. unclean_instances = list(LatexManager._unclean_instances)
  204. for latex_manager in unclean_instances:
  205. latex_manager._cleanup()
  206. def _stdin_writeln(self, s):
  207. if self.latex is None:
  208. self._setup_latex_process()
  209. self.latex.stdin.write(s)
  210. self.latex.stdin.write("\n")
  211. self.latex.stdin.flush()
  212. def _expect(self, s):
  213. s = list(s)
  214. chars = []
  215. while True:
  216. c = self.latex.stdout.read(1)
  217. chars.append(c)
  218. if chars[-len(s):] == s:
  219. break
  220. if not c:
  221. self.latex.kill()
  222. self.latex = None
  223. raise LatexError("LaTeX process halted", "".join(chars))
  224. return "".join(chars)
  225. def _expect_prompt(self):
  226. return self._expect("\n*")
  227. def __init__(self):
  228. # store references for __del__
  229. self._os_path = os.path
  230. self._shutil = shutil
  231. # create a tmp directory for running latex, remember to cleanup
  232. self.tmpdir = tempfile.mkdtemp(prefix="mpl_pgf_lm_")
  233. LatexManager._unclean_instances.add(self)
  234. # test the LaTeX setup to ensure a clean startup of the subprocess
  235. self.texcommand = mpl.rcParams["pgf.texsystem"]
  236. self.latex_header = LatexManager._build_latex_header()
  237. latex_end = "\n\\makeatletter\n\\@@end\n"
  238. try:
  239. latex = subprocess.Popen(
  240. [self.texcommand, "-halt-on-error"],
  241. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  242. encoding="utf-8", cwd=self.tmpdir)
  243. except FileNotFoundError as err:
  244. raise RuntimeError(
  245. f"{self.texcommand} not found. Install it or change "
  246. f"rcParams['pgf.texsystem'] to an available TeX "
  247. f"implementation.") from err
  248. except OSError as err:
  249. raise RuntimeError("Error starting process %r" %
  250. self.texcommand) from err
  251. test_input = self.latex_header + latex_end
  252. stdout, stderr = latex.communicate(test_input)
  253. if latex.returncode != 0:
  254. raise LatexError("LaTeX returned an error, probably missing font "
  255. "or error in preamble:\n%s" % stdout)
  256. self.latex = None # Will be set up on first use.
  257. self.str_cache = {} # cache for strings already processed
  258. def _setup_latex_process(self):
  259. # open LaTeX process for real work
  260. self.latex = subprocess.Popen(
  261. [self.texcommand, "-halt-on-error"],
  262. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  263. encoding="utf-8", cwd=self.tmpdir)
  264. # write header with 'pgf_backend_query_start' token
  265. self._stdin_writeln(self._build_latex_header())
  266. # read all lines until our 'pgf_backend_query_start' token appears
  267. self._expect("*pgf_backend_query_start")
  268. self._expect_prompt()
  269. @cbook.deprecated("3.3")
  270. def latex_stdin_utf8(self):
  271. return self.latex.stdin
  272. def _cleanup(self):
  273. if not self._os_path.isdir(self.tmpdir):
  274. return
  275. try:
  276. self.latex.communicate()
  277. except Exception:
  278. pass
  279. try:
  280. self._shutil.rmtree(self.tmpdir)
  281. LatexManager._unclean_instances.discard(self)
  282. except Exception:
  283. sys.stderr.write("error deleting tmp directory %s\n" % self.tmpdir)
  284. def __del__(self):
  285. _log.debug("deleting LatexManager")
  286. self._cleanup()
  287. def get_width_height_descent(self, text, prop):
  288. """
  289. Get the width, total height and descent for a text typeset by the
  290. current LaTeX environment.
  291. """
  292. # apply font properties and define textbox
  293. prop_cmds = _font_properties_str(prop)
  294. textbox = "\\sbox0{%s %s}" % (prop_cmds, text)
  295. # check cache
  296. if textbox in self.str_cache:
  297. return self.str_cache[textbox]
  298. # send textbox to LaTeX and wait for prompt
  299. self._stdin_writeln(textbox)
  300. try:
  301. self._expect_prompt()
  302. except LatexError as e:
  303. raise ValueError("Error processing '{}'\nLaTeX Output:\n{}"
  304. .format(text, e.latex_output)) from e
  305. # typeout width, height and text offset of the last textbox
  306. self._stdin_writeln(r"\typeout{\the\wd0,\the\ht0,\the\dp0}")
  307. # read answer from latex and advance to the next prompt
  308. try:
  309. answer = self._expect_prompt()
  310. except LatexError as e:
  311. raise ValueError("Error processing '{}'\nLaTeX Output:\n{}"
  312. .format(text, e.latex_output)) from e
  313. # parse metrics from the answer string
  314. try:
  315. width, height, offset = answer.splitlines()[0].split(",")
  316. except Exception as err:
  317. raise ValueError("Error processing '{}'\nLaTeX Output:\n{}"
  318. .format(text, answer)) from err
  319. w, h, o = float(width[:-2]), float(height[:-2]), float(offset[:-2])
  320. # the height returned from LaTeX goes from base to top.
  321. # the height matplotlib expects goes from bottom to top.
  322. self.str_cache[textbox] = (w, h + o, o)
  323. return w, h + o, o
  324. @functools.lru_cache(1)
  325. def _get_image_inclusion_command():
  326. man = LatexManager._get_cached_or_new()
  327. man._stdin_writeln(
  328. r"\includegraphics[interpolate=true]{%s}"
  329. # Don't mess with backslashes on Windows.
  330. % cbook._get_data_path("images/matplotlib.png").as_posix())
  331. try:
  332. prompt = man._expect_prompt()
  333. return r"\includegraphics"
  334. except LatexError:
  335. # Discard the broken manager.
  336. LatexManager._get_cached_or_new_impl.cache_clear()
  337. return r"\pgfimage"
  338. class RendererPgf(RendererBase):
  339. @cbook._delete_parameter("3.3", "dummy")
  340. def __init__(self, figure, fh, dummy=False):
  341. """
  342. Create a new PGF renderer that translates any drawing instruction
  343. into text commands to be interpreted in a latex pgfpicture environment.
  344. Attributes
  345. ----------
  346. figure : `matplotlib.figure.Figure`
  347. Matplotlib figure to initialize height, width and dpi from.
  348. fh : file-like
  349. File handle for the output of the drawing commands.
  350. """
  351. RendererBase.__init__(self)
  352. self.dpi = figure.dpi
  353. self.fh = fh
  354. self.figure = figure
  355. self.image_counter = 0
  356. self._latexManager = LatexManager._get_cached_or_new() # deprecated
  357. if dummy:
  358. # dummy==True deactivate all methods
  359. for m in RendererPgf.__dict__:
  360. if m.startswith("draw_"):
  361. self.__dict__[m] = lambda *args, **kwargs: None
  362. latexManager = cbook._deprecate_privatize_attribute("3.2")
  363. def draw_markers(self, gc, marker_path, marker_trans, path, trans,
  364. rgbFace=None):
  365. # docstring inherited
  366. writeln(self.fh, r"\begin{pgfscope}")
  367. # convert from display units to in
  368. f = 1. / self.dpi
  369. # set style and clip
  370. self._print_pgf_clip(gc)
  371. self._print_pgf_path_styles(gc, rgbFace)
  372. # build marker definition
  373. bl, tr = marker_path.get_extents(marker_trans).get_points()
  374. coords = bl[0] * f, bl[1] * f, tr[0] * f, tr[1] * f
  375. writeln(self.fh,
  376. r"\pgfsys@defobject{currentmarker}"
  377. r"{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}{" % coords)
  378. self._print_pgf_path(None, marker_path, marker_trans)
  379. self._pgf_path_draw(stroke=gc.get_linewidth() != 0.0,
  380. fill=rgbFace is not None)
  381. writeln(self.fh, r"}")
  382. # draw marker for each vertex
  383. for point, code in path.iter_segments(trans, simplify=False):
  384. x, y = point[0] * f, point[1] * f
  385. writeln(self.fh, r"\begin{pgfscope}")
  386. writeln(self.fh, r"\pgfsys@transformshift{%fin}{%fin}" % (x, y))
  387. writeln(self.fh, r"\pgfsys@useobject{currentmarker}{}")
  388. writeln(self.fh, r"\end{pgfscope}")
  389. writeln(self.fh, r"\end{pgfscope}")
  390. def draw_path(self, gc, path, transform, rgbFace=None):
  391. # docstring inherited
  392. writeln(self.fh, r"\begin{pgfscope}")
  393. # draw the path
  394. self._print_pgf_clip(gc)
  395. self._print_pgf_path_styles(gc, rgbFace)
  396. self._print_pgf_path(gc, path, transform, rgbFace)
  397. self._pgf_path_draw(stroke=gc.get_linewidth() != 0.0,
  398. fill=rgbFace is not None)
  399. writeln(self.fh, r"\end{pgfscope}")
  400. # if present, draw pattern on top
  401. if gc.get_hatch():
  402. writeln(self.fh, r"\begin{pgfscope}")
  403. self._print_pgf_path_styles(gc, rgbFace)
  404. # combine clip and path for clipping
  405. self._print_pgf_clip(gc)
  406. self._print_pgf_path(gc, path, transform, rgbFace)
  407. writeln(self.fh, r"\pgfusepath{clip}")
  408. # build pattern definition
  409. writeln(self.fh,
  410. r"\pgfsys@defobject{currentpattern}"
  411. r"{\pgfqpoint{0in}{0in}}{\pgfqpoint{1in}{1in}}{")
  412. writeln(self.fh, r"\begin{pgfscope}")
  413. writeln(self.fh,
  414. r"\pgfpathrectangle"
  415. r"{\pgfqpoint{0in}{0in}}{\pgfqpoint{1in}{1in}}")
  416. writeln(self.fh, r"\pgfusepath{clip}")
  417. scale = mpl.transforms.Affine2D().scale(self.dpi)
  418. self._print_pgf_path(None, gc.get_hatch_path(), scale)
  419. self._pgf_path_draw(stroke=True)
  420. writeln(self.fh, r"\end{pgfscope}")
  421. writeln(self.fh, r"}")
  422. # repeat pattern, filling the bounding rect of the path
  423. f = 1. / self.dpi
  424. (xmin, ymin), (xmax, ymax) = \
  425. path.get_extents(transform).get_points()
  426. xmin, xmax = f * xmin, f * xmax
  427. ymin, ymax = f * ymin, f * ymax
  428. repx, repy = math.ceil(xmax - xmin), math.ceil(ymax - ymin)
  429. writeln(self.fh,
  430. r"\pgfsys@transformshift{%fin}{%fin}" % (xmin, ymin))
  431. for iy in range(repy):
  432. for ix in range(repx):
  433. writeln(self.fh, r"\pgfsys@useobject{currentpattern}{}")
  434. writeln(self.fh, r"\pgfsys@transformshift{1in}{0in}")
  435. writeln(self.fh, r"\pgfsys@transformshift{-%din}{0in}" % repx)
  436. writeln(self.fh, r"\pgfsys@transformshift{0in}{1in}")
  437. writeln(self.fh, r"\end{pgfscope}")
  438. def _print_pgf_clip(self, gc):
  439. f = 1. / self.dpi
  440. # check for clip box
  441. bbox = gc.get_clip_rectangle()
  442. if bbox:
  443. p1, p2 = bbox.get_points()
  444. w, h = p2 - p1
  445. coords = p1[0] * f, p1[1] * f, w * f, h * f
  446. writeln(self.fh,
  447. r"\pgfpathrectangle"
  448. r"{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}"
  449. % coords)
  450. writeln(self.fh, r"\pgfusepath{clip}")
  451. # check for clip path
  452. clippath, clippath_trans = gc.get_clip_path()
  453. if clippath is not None:
  454. self._print_pgf_path(gc, clippath, clippath_trans)
  455. writeln(self.fh, r"\pgfusepath{clip}")
  456. def _print_pgf_path_styles(self, gc, rgbFace):
  457. # cap style
  458. capstyles = {"butt": r"\pgfsetbuttcap",
  459. "round": r"\pgfsetroundcap",
  460. "projecting": r"\pgfsetrectcap"}
  461. writeln(self.fh, capstyles[gc.get_capstyle()])
  462. # join style
  463. joinstyles = {"miter": r"\pgfsetmiterjoin",
  464. "round": r"\pgfsetroundjoin",
  465. "bevel": r"\pgfsetbeveljoin"}
  466. writeln(self.fh, joinstyles[gc.get_joinstyle()])
  467. # filling
  468. has_fill = rgbFace is not None
  469. if gc.get_forced_alpha():
  470. fillopacity = strokeopacity = gc.get_alpha()
  471. else:
  472. strokeopacity = gc.get_rgb()[3]
  473. fillopacity = rgbFace[3] if has_fill and len(rgbFace) > 3 else 1.0
  474. if has_fill:
  475. writeln(self.fh,
  476. r"\definecolor{currentfill}{rgb}{%f,%f,%f}"
  477. % tuple(rgbFace[:3]))
  478. writeln(self.fh, r"\pgfsetfillcolor{currentfill}")
  479. if has_fill and fillopacity != 1.0:
  480. writeln(self.fh, r"\pgfsetfillopacity{%f}" % fillopacity)
  481. # linewidth and color
  482. lw = gc.get_linewidth() * mpl_pt_to_in * latex_in_to_pt
  483. stroke_rgba = gc.get_rgb()
  484. writeln(self.fh, r"\pgfsetlinewidth{%fpt}" % lw)
  485. writeln(self.fh,
  486. r"\definecolor{currentstroke}{rgb}{%f,%f,%f}"
  487. % stroke_rgba[:3])
  488. writeln(self.fh, r"\pgfsetstrokecolor{currentstroke}")
  489. if strokeopacity != 1.0:
  490. writeln(self.fh, r"\pgfsetstrokeopacity{%f}" % strokeopacity)
  491. # line style
  492. dash_offset, dash_list = gc.get_dashes()
  493. if dash_list is None:
  494. writeln(self.fh, r"\pgfsetdash{}{0pt}")
  495. else:
  496. writeln(self.fh,
  497. r"\pgfsetdash{%s}{%fpt}"
  498. % ("".join(r"{%fpt}" % dash for dash in dash_list),
  499. dash_offset))
  500. def _print_pgf_path(self, gc, path, transform, rgbFace=None):
  501. f = 1. / self.dpi
  502. # check for clip box / ignore clip for filled paths
  503. bbox = gc.get_clip_rectangle() if gc else None
  504. if bbox and (rgbFace is None):
  505. p1, p2 = bbox.get_points()
  506. clip = (p1[0], p1[1], p2[0], p2[1])
  507. else:
  508. clip = None
  509. # build path
  510. for points, code in path.iter_segments(transform, clip=clip):
  511. if code == Path.MOVETO:
  512. x, y = tuple(points)
  513. writeln(self.fh,
  514. r"\pgfpathmoveto{\pgfqpoint{%fin}{%fin}}" %
  515. (f * x, f * y))
  516. elif code == Path.CLOSEPOLY:
  517. writeln(self.fh, r"\pgfpathclose")
  518. elif code == Path.LINETO:
  519. x, y = tuple(points)
  520. writeln(self.fh,
  521. r"\pgfpathlineto{\pgfqpoint{%fin}{%fin}}" %
  522. (f * x, f * y))
  523. elif code == Path.CURVE3:
  524. cx, cy, px, py = tuple(points)
  525. coords = cx * f, cy * f, px * f, py * f
  526. writeln(self.fh,
  527. r"\pgfpathquadraticcurveto"
  528. r"{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}"
  529. % coords)
  530. elif code == Path.CURVE4:
  531. c1x, c1y, c2x, c2y, px, py = tuple(points)
  532. coords = c1x * f, c1y * f, c2x * f, c2y * f, px * f, py * f
  533. writeln(self.fh,
  534. r"\pgfpathcurveto"
  535. r"{\pgfqpoint{%fin}{%fin}}"
  536. r"{\pgfqpoint{%fin}{%fin}}"
  537. r"{\pgfqpoint{%fin}{%fin}}"
  538. % coords)
  539. def _pgf_path_draw(self, stroke=True, fill=False):
  540. actions = []
  541. if stroke:
  542. actions.append("stroke")
  543. if fill:
  544. actions.append("fill")
  545. writeln(self.fh, r"\pgfusepath{%s}" % ",".join(actions))
  546. def option_scale_image(self):
  547. # docstring inherited
  548. return True
  549. def option_image_nocomposite(self):
  550. # docstring inherited
  551. return not mpl.rcParams['image.composite_image']
  552. def draw_image(self, gc, x, y, im, transform=None):
  553. # docstring inherited
  554. h, w = im.shape[:2]
  555. if w == 0 or h == 0:
  556. return
  557. if not os.path.exists(getattr(self.fh, "name", "")):
  558. cbook._warn_external(
  559. "streamed pgf-code does not support raster graphics, consider "
  560. "using the pgf-to-pdf option.")
  561. # save the images to png files
  562. path = pathlib.Path(self.fh.name)
  563. fname_img = "%s-img%d.png" % (path.stem, self.image_counter)
  564. Image.fromarray(im[::-1]).save(path.parent / fname_img)
  565. self.image_counter += 1
  566. # reference the image in the pgf picture
  567. writeln(self.fh, r"\begin{pgfscope}")
  568. self._print_pgf_clip(gc)
  569. f = 1. / self.dpi # from display coords to inch
  570. if transform is None:
  571. writeln(self.fh,
  572. r"\pgfsys@transformshift{%fin}{%fin}" % (x * f, y * f))
  573. w, h = w * f, h * f
  574. else:
  575. tr1, tr2, tr3, tr4, tr5, tr6 = transform.frozen().to_values()
  576. writeln(self.fh,
  577. r"\pgfsys@transformcm{%f}{%f}{%f}{%f}{%fin}{%fin}" %
  578. (tr1 * f, tr2 * f, tr3 * f, tr4 * f,
  579. (tr5 + x) * f, (tr6 + y) * f))
  580. w = h = 1 # scale is already included in the transform
  581. interp = str(transform is None).lower() # interpolation in PDF reader
  582. writeln(self.fh,
  583. r"\pgftext[left,bottom]"
  584. r"{%s[interpolate=%s,width=%fin,height=%fin]{%s}}" %
  585. (_get_image_inclusion_command(),
  586. interp, w, h, fname_img))
  587. writeln(self.fh, r"\end{pgfscope}")
  588. def draw_tex(self, gc, x, y, s, prop, angle, ismath="TeX!", mtext=None):
  589. # docstring inherited
  590. self.draw_text(gc, x, y, s, prop, angle, ismath, mtext)
  591. def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
  592. # docstring inherited
  593. # prepare string for tex
  594. s = common_texification(s)
  595. prop_cmds = _font_properties_str(prop)
  596. s = r"%s %s" % (prop_cmds, s)
  597. writeln(self.fh, r"\begin{pgfscope}")
  598. alpha = gc.get_alpha()
  599. if alpha != 1.0:
  600. writeln(self.fh, r"\pgfsetfillopacity{%f}" % alpha)
  601. writeln(self.fh, r"\pgfsetstrokeopacity{%f}" % alpha)
  602. rgb = tuple(gc.get_rgb())[:3]
  603. writeln(self.fh, r"\definecolor{textcolor}{rgb}{%f,%f,%f}" % rgb)
  604. writeln(self.fh, r"\pgfsetstrokecolor{textcolor}")
  605. writeln(self.fh, r"\pgfsetfillcolor{textcolor}")
  606. s = r"\color{textcolor}" + s
  607. dpi = self.figure.dpi
  608. text_args = []
  609. if mtext and (
  610. (angle == 0 or
  611. mtext.get_rotation_mode() == "anchor") and
  612. mtext.get_verticalalignment() != "center_baseline"):
  613. # if text anchoring can be supported, get the original coordinates
  614. # and add alignment information
  615. pos = mtext.get_unitless_position()
  616. x, y = mtext.get_transform().transform(pos)
  617. halign = {"left": "left", "right": "right", "center": ""}
  618. valign = {"top": "top", "bottom": "bottom",
  619. "baseline": "base", "center": ""}
  620. text_args.extend([
  621. f"x={x/dpi:f}in",
  622. f"y={y/dpi:f}in",
  623. halign[mtext.get_horizontalalignment()],
  624. valign[mtext.get_verticalalignment()],
  625. ])
  626. else:
  627. # if not, use the text layout provided by Matplotlib.
  628. text_args.append(f"x={x/dpi:f}in, y={y/dpi:f}in, left, base")
  629. if angle != 0:
  630. text_args.append("rotate=%f" % angle)
  631. writeln(self.fh, r"\pgftext[%s]{%s}" % (",".join(text_args), s))
  632. writeln(self.fh, r"\end{pgfscope}")
  633. def get_text_width_height_descent(self, s, prop, ismath):
  634. # docstring inherited
  635. # check if the math is supposed to be displaystyled
  636. s = common_texification(s)
  637. # get text metrics in units of latex pt, convert to display units
  638. w, h, d = (LatexManager._get_cached_or_new()
  639. .get_width_height_descent(s, prop))
  640. # TODO: this should be latex_pt_to_in instead of mpl_pt_to_in
  641. # but having a little bit more space around the text looks better,
  642. # plus the bounding box reported by LaTeX is VERY narrow
  643. f = mpl_pt_to_in * self.dpi
  644. return w * f, h * f, d * f
  645. def flipy(self):
  646. # docstring inherited
  647. return False
  648. def get_canvas_width_height(self):
  649. # docstring inherited
  650. return (self.figure.get_figwidth() * self.dpi,
  651. self.figure.get_figheight() * self.dpi)
  652. def points_to_pixels(self, points):
  653. # docstring inherited
  654. return points * mpl_pt_to_in * self.dpi
  655. @cbook.deprecated("3.3", alternative="GraphicsContextBase")
  656. class GraphicsContextPgf(GraphicsContextBase):
  657. pass
  658. class TmpDirCleaner:
  659. remaining_tmpdirs = set()
  660. @staticmethod
  661. def add(tmpdir):
  662. TmpDirCleaner.remaining_tmpdirs.add(tmpdir)
  663. @staticmethod
  664. def cleanup_remaining_tmpdirs():
  665. for tmpdir in TmpDirCleaner.remaining_tmpdirs:
  666. error_message = "error deleting tmp directory {}".format(tmpdir)
  667. shutil.rmtree(
  668. tmpdir,
  669. onerror=lambda *args: _log.error(error_message))
  670. class FigureCanvasPgf(FigureCanvasBase):
  671. filetypes = {"pgf": "LaTeX PGF picture",
  672. "pdf": "LaTeX compiled PGF picture",
  673. "png": "Portable Network Graphics", }
  674. def get_default_filetype(self):
  675. return 'pdf'
  676. @_check_savefig_extra_args
  677. @cbook._delete_parameter("3.2", "dryrun")
  678. def _print_pgf_to_fh(self, fh, *,
  679. dryrun=False, bbox_inches_restore=None):
  680. if dryrun:
  681. renderer = RendererPgf(self.figure, None, dummy=True)
  682. self.figure.draw(renderer)
  683. return
  684. header_text = """%% Creator: Matplotlib, PGF backend
  685. %%
  686. %% To include the figure in your LaTeX document, write
  687. %% \\input{<filename>.pgf}
  688. %%
  689. %% Make sure the required packages are loaded in your preamble
  690. %% \\usepackage{pgf}
  691. %%
  692. %% and, on pdftex
  693. %% \\usepackage[utf8]{inputenc}\\DeclareUnicodeCharacter{2212}{-}
  694. %%
  695. %% or, on luatex and xetex
  696. %% \\usepackage{unicode-math}
  697. %%
  698. %% Figures using additional raster images can only be included by \\input if
  699. %% they are in the same directory as the main LaTeX file. For loading figures
  700. %% from other directories you can use the `import` package
  701. %% \\usepackage{import}
  702. %%
  703. %% and then include the figures with
  704. %% \\import{<path to file>}{<filename>.pgf}
  705. %%
  706. """
  707. # append the preamble used by the backend as a comment for debugging
  708. header_info_preamble = ["%% Matplotlib used the following preamble"]
  709. for line in get_preamble().splitlines():
  710. header_info_preamble.append("%% " + line)
  711. for line in get_fontspec().splitlines():
  712. header_info_preamble.append("%% " + line)
  713. header_info_preamble.append("%%")
  714. header_info_preamble = "\n".join(header_info_preamble)
  715. # get figure size in inch
  716. w, h = self.figure.get_figwidth(), self.figure.get_figheight()
  717. dpi = self.figure.get_dpi()
  718. # create pgfpicture environment and write the pgf code
  719. fh.write(header_text)
  720. fh.write(header_info_preamble)
  721. fh.write("\n")
  722. writeln(fh, r"\begingroup")
  723. writeln(fh, r"\makeatletter")
  724. writeln(fh, r"\begin{pgfpicture}")
  725. writeln(fh,
  726. r"\pgfpathrectangle{\pgfpointorigin}{\pgfqpoint{%fin}{%fin}}"
  727. % (w, h))
  728. writeln(fh, r"\pgfusepath{use as bounding box, clip}")
  729. renderer = MixedModeRenderer(self.figure, w, h, dpi,
  730. RendererPgf(self.figure, fh),
  731. bbox_inches_restore=bbox_inches_restore)
  732. self.figure.draw(renderer)
  733. # end the pgfpicture environment
  734. writeln(fh, r"\end{pgfpicture}")
  735. writeln(fh, r"\makeatother")
  736. writeln(fh, r"\endgroup")
  737. def print_pgf(self, fname_or_fh, *args, **kwargs):
  738. """
  739. Output pgf macros for drawing the figure so it can be included and
  740. rendered in latex documents.
  741. """
  742. if kwargs.get("dryrun", False):
  743. self._print_pgf_to_fh(None, *args, **kwargs)
  744. return
  745. with cbook.open_file_cm(fname_or_fh, "w", encoding="utf-8") as file:
  746. if not cbook.file_requires_unicode(file):
  747. file = codecs.getwriter("utf-8")(file)
  748. self._print_pgf_to_fh(file, *args, **kwargs)
  749. def _print_pdf_to_fh(self, fh, *args, metadata=None, **kwargs):
  750. w, h = self.figure.get_figwidth(), self.figure.get_figheight()
  751. info_dict = _create_pdf_info_dict('pgf', metadata or {})
  752. hyperref_options = ','.join(
  753. _metadata_to_str(k, v) for k, v in info_dict.items())
  754. try:
  755. # create temporary directory for compiling the figure
  756. tmpdir = tempfile.mkdtemp(prefix="mpl_pgf_")
  757. fname_pgf = os.path.join(tmpdir, "figure.pgf")
  758. fname_tex = os.path.join(tmpdir, "figure.tex")
  759. fname_pdf = os.path.join(tmpdir, "figure.pdf")
  760. # print figure to pgf and compile it with latex
  761. self.print_pgf(fname_pgf, *args, **kwargs)
  762. latex_preamble = get_preamble()
  763. latex_fontspec = get_fontspec()
  764. latexcode = """
  765. \\PassOptionsToPackage{pdfinfo={%s}}{hyperref}
  766. \\RequirePackage{hyperref}
  767. \\documentclass[12pt]{minimal}
  768. \\usepackage[paperwidth=%fin, paperheight=%fin, margin=0in]{geometry}
  769. %s
  770. %s
  771. \\usepackage{pgf}
  772. \\begin{document}
  773. \\centering
  774. \\input{figure.pgf}
  775. \\end{document}""" % (hyperref_options, w, h, latex_preamble, latex_fontspec)
  776. pathlib.Path(fname_tex).write_text(latexcode, encoding="utf-8")
  777. texcommand = mpl.rcParams["pgf.texsystem"]
  778. cbook._check_and_log_subprocess(
  779. [texcommand, "-interaction=nonstopmode", "-halt-on-error",
  780. "figure.tex"], _log, cwd=tmpdir)
  781. # copy file contents to target
  782. with open(fname_pdf, "rb") as fh_src:
  783. shutil.copyfileobj(fh_src, fh)
  784. finally:
  785. try:
  786. shutil.rmtree(tmpdir)
  787. except:
  788. TmpDirCleaner.add(tmpdir)
  789. def print_pdf(self, fname_or_fh, *args, **kwargs):
  790. """Use LaTeX to compile a Pgf generated figure to PDF."""
  791. if kwargs.get("dryrun", False):
  792. self._print_pgf_to_fh(None, *args, **kwargs)
  793. return
  794. with cbook.open_file_cm(fname_or_fh, "wb") as file:
  795. self._print_pdf_to_fh(file, *args, **kwargs)
  796. def _print_png_to_fh(self, fh, *args, **kwargs):
  797. converter = make_pdf_to_png_converter()
  798. try:
  799. # create temporary directory for pdf creation and png conversion
  800. tmpdir = tempfile.mkdtemp(prefix="mpl_pgf_")
  801. fname_pdf = os.path.join(tmpdir, "figure.pdf")
  802. fname_png = os.path.join(tmpdir, "figure.png")
  803. # create pdf and try to convert it to png
  804. self.print_pdf(fname_pdf, *args, **kwargs)
  805. converter(fname_pdf, fname_png, dpi=self.figure.dpi)
  806. # copy file contents to target
  807. with open(fname_png, "rb") as fh_src:
  808. shutil.copyfileobj(fh_src, fh)
  809. finally:
  810. try:
  811. shutil.rmtree(tmpdir)
  812. except:
  813. TmpDirCleaner.add(tmpdir)
  814. def print_png(self, fname_or_fh, *args, **kwargs):
  815. """Use LaTeX to compile a pgf figure to pdf and convert it to png."""
  816. if kwargs.get("dryrun", False):
  817. self._print_pgf_to_fh(None, *args, **kwargs)
  818. return
  819. with cbook.open_file_cm(fname_or_fh, "wb") as file:
  820. self._print_png_to_fh(file, *args, **kwargs)
  821. def get_renderer(self):
  822. return RendererPgf(self.figure, None)
  823. FigureManagerPgf = FigureManagerBase
  824. @_Backend.export
  825. class _BackendPgf(_Backend):
  826. FigureCanvas = FigureCanvasPgf
  827. def _cleanup_all():
  828. LatexManager._cleanup_remaining_instances()
  829. TmpDirCleaner.cleanup_remaining_tmpdirs()
  830. atexit.register(_cleanup_all)
  831. class PdfPages:
  832. """
  833. A multi-page PDF file using the pgf backend
  834. Examples
  835. --------
  836. >>> import matplotlib.pyplot as plt
  837. >>> # Initialize:
  838. >>> with PdfPages('foo.pdf') as pdf:
  839. ... # As many times as you like, create a figure fig and save it:
  840. ... fig = plt.figure()
  841. ... pdf.savefig(fig)
  842. ... # When no figure is specified the current figure is saved
  843. ... pdf.savefig()
  844. """
  845. __slots__ = (
  846. '_outputfile',
  847. 'keep_empty',
  848. '_tmpdir',
  849. '_basename',
  850. '_fname_tex',
  851. '_fname_pdf',
  852. '_n_figures',
  853. '_file',
  854. '_info_dict',
  855. '_metadata',
  856. )
  857. def __init__(self, filename, *, keep_empty=True, metadata=None):
  858. """
  859. Create a new PdfPages object.
  860. Parameters
  861. ----------
  862. filename : str or path-like
  863. Plots using `PdfPages.savefig` will be written to a file at this
  864. location. Any older file with the same name is overwritten.
  865. keep_empty : bool, default: True
  866. If set to False, then empty pdf files will be deleted automatically
  867. when closed.
  868. metadata : dict, optional
  869. Information dictionary object (see PDF reference section 10.2.1
  870. 'Document Information Dictionary'), e.g.:
  871. ``{'Creator': 'My software', 'Author': 'Me', 'Title': 'Awesome'}``.
  872. The standard keys are 'Title', 'Author', 'Subject', 'Keywords',
  873. 'Creator', 'Producer', 'CreationDate', 'ModDate', and
  874. 'Trapped'. Values have been predefined for 'Creator', 'Producer'
  875. and 'CreationDate'. They can be removed by setting them to `None`.
  876. """
  877. self._outputfile = filename
  878. self._n_figures = 0
  879. self.keep_empty = keep_empty
  880. self._metadata = (metadata or {}).copy()
  881. if metadata:
  882. for key in metadata:
  883. canonical = {
  884. 'creationdate': 'CreationDate',
  885. 'moddate': 'ModDate',
  886. }.get(key.lower(), key.lower().title())
  887. if canonical != key:
  888. cbook.warn_deprecated(
  889. '3.3', message='Support for setting PDF metadata keys '
  890. 'case-insensitively is deprecated since %(since)s and '
  891. 'will be removed %(removal)s; '
  892. f'set {canonical} instead of {key}.')
  893. self._metadata[canonical] = self._metadata.pop(key)
  894. self._info_dict = _create_pdf_info_dict('pgf', self._metadata)
  895. # create temporary directory for compiling the figure
  896. self._tmpdir = tempfile.mkdtemp(prefix="mpl_pgf_pdfpages_")
  897. self._basename = 'pdf_pages'
  898. self._fname_tex = os.path.join(self._tmpdir, self._basename + ".tex")
  899. self._fname_pdf = os.path.join(self._tmpdir, self._basename + ".pdf")
  900. self._file = open(self._fname_tex, 'wb')
  901. @cbook.deprecated('3.3')
  902. @property
  903. def metadata(self):
  904. return self._metadata
  905. def _write_header(self, width_inches, height_inches):
  906. hyperref_options = ','.join(
  907. _metadata_to_str(k, v) for k, v in self._info_dict.items())
  908. latex_preamble = get_preamble()
  909. latex_fontspec = get_fontspec()
  910. latex_header = r"""\PassOptionsToPackage{{
  911. pdfinfo={{
  912. {metadata}
  913. }}
  914. }}{{hyperref}}
  915. \RequirePackage{{hyperref}}
  916. \documentclass[12pt]{{minimal}}
  917. \usepackage[
  918. paperwidth={width}in,
  919. paperheight={height}in,
  920. margin=0in
  921. ]{{geometry}}
  922. {preamble}
  923. {fontspec}
  924. \usepackage{{pgf}}
  925. \setlength{{\parindent}}{{0pt}}
  926. \begin{{document}}%%
  927. """.format(
  928. width=width_inches,
  929. height=height_inches,
  930. preamble=latex_preamble,
  931. fontspec=latex_fontspec,
  932. metadata=hyperref_options,
  933. )
  934. self._file.write(latex_header.encode('utf-8'))
  935. def __enter__(self):
  936. return self
  937. def __exit__(self, exc_type, exc_val, exc_tb):
  938. self.close()
  939. def close(self):
  940. """
  941. Finalize this object, running LaTeX in a temporary directory
  942. and moving the final pdf file to *filename*.
  943. """
  944. self._file.write(rb'\end{document}\n')
  945. self._file.close()
  946. if self._n_figures > 0:
  947. try:
  948. self._run_latex()
  949. finally:
  950. try:
  951. shutil.rmtree(self._tmpdir)
  952. except:
  953. TmpDirCleaner.add(self._tmpdir)
  954. elif self.keep_empty:
  955. open(self._outputfile, 'wb').close()
  956. def _run_latex(self):
  957. texcommand = mpl.rcParams["pgf.texsystem"]
  958. cbook._check_and_log_subprocess(
  959. [texcommand, "-interaction=nonstopmode", "-halt-on-error",
  960. os.path.basename(self._fname_tex)],
  961. _log, cwd=self._tmpdir)
  962. # copy file contents to target
  963. shutil.copyfile(self._fname_pdf, self._outputfile)
  964. def savefig(self, figure=None, **kwargs):
  965. """
  966. Save a `.Figure` to this file as a new page.
  967. Any other keyword arguments are passed to `~.Figure.savefig`.
  968. Parameters
  969. ----------
  970. figure : `.Figure` or int, optional
  971. Specifies what figure is saved to file. If not specified, the
  972. active figure is saved. If a `.Figure` instance is provided, this
  973. figure is saved. If an int is specified, the figure instance to
  974. save is looked up by number.
  975. """
  976. if not isinstance(figure, Figure):
  977. if figure is None:
  978. manager = Gcf.get_active()
  979. else:
  980. manager = Gcf.get_fig_manager(figure)
  981. if manager is None:
  982. raise ValueError("No figure {}".format(figure))
  983. figure = manager.canvas.figure
  984. try:
  985. orig_canvas = figure.canvas
  986. figure.canvas = FigureCanvasPgf(figure)
  987. width, height = figure.get_size_inches()
  988. if self._n_figures == 0:
  989. self._write_header(width, height)
  990. else:
  991. # \pdfpagewidth and \pdfpageheight exist on pdftex, xetex, and
  992. # luatex<0.85; they were renamed to \pagewidth and \pageheight
  993. # on luatex>=0.85.
  994. self._file.write(
  995. br'\newpage'
  996. br'\ifdefined\pdfpagewidth\pdfpagewidth'
  997. br'\else\pagewidth\fi=%ain'
  998. br'\ifdefined\pdfpageheight\pdfpageheight'
  999. br'\else\pageheight\fi=%ain'
  1000. b'%%\n' % (width, height)
  1001. )
  1002. figure.savefig(self._file, format="pgf", **kwargs)
  1003. self._n_figures += 1
  1004. finally:
  1005. figure.canvas = orig_canvas
  1006. def get_pagecount(self):
  1007. """Return the current number of pages in the multipage pdf file."""
  1008. return self._n_figures