backend_ps.py 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340
  1. """
  2. A PostScript backend, which can produce both PostScript .ps and .eps.
  3. """
  4. import codecs
  5. import datetime
  6. from enum import Enum
  7. import functools
  8. from io import StringIO
  9. import itertools
  10. import logging
  11. import os
  12. import pathlib
  13. import shutil
  14. from tempfile import TemporaryDirectory
  15. import time
  16. import numpy as np
  17. import matplotlib as mpl
  18. from matplotlib import _api, cbook, _path, _text_helpers
  19. from matplotlib._afm import AFM
  20. from matplotlib.backend_bases import (
  21. _Backend, FigureCanvasBase, FigureManagerBase, RendererBase)
  22. from matplotlib.cbook import is_writable_file_like, file_requires_unicode
  23. from matplotlib.font_manager import get_font
  24. from matplotlib.ft2font import LOAD_NO_SCALE, FT2Font
  25. from matplotlib._ttconv import convert_ttf_to_ps
  26. from matplotlib._mathtext_data import uni2type1
  27. from matplotlib.path import Path
  28. from matplotlib.texmanager import TexManager
  29. from matplotlib.transforms import Affine2D
  30. from matplotlib.backends.backend_mixed import MixedModeRenderer
  31. from . import _backend_pdf_ps
  32. _log = logging.getLogger(__name__)
  33. debugPS = False
  34. @_api.deprecated("3.7")
  35. class PsBackendHelper:
  36. def __init__(self):
  37. self._cached = {}
  38. @_api.caching_module_getattr
  39. class __getattr__:
  40. # module-level deprecations
  41. ps_backend_helper = _api.deprecated("3.7", obj_type="")(
  42. property(lambda self: PsBackendHelper()))
  43. psDefs = _api.deprecated("3.8", obj_type="")(property(lambda self: _psDefs))
  44. papersize = {'letter': (8.5, 11),
  45. 'legal': (8.5, 14),
  46. 'ledger': (11, 17),
  47. 'a0': (33.11, 46.81),
  48. 'a1': (23.39, 33.11),
  49. 'a2': (16.54, 23.39),
  50. 'a3': (11.69, 16.54),
  51. 'a4': (8.27, 11.69),
  52. 'a5': (5.83, 8.27),
  53. 'a6': (4.13, 5.83),
  54. 'a7': (2.91, 4.13),
  55. 'a8': (2.05, 2.91),
  56. 'a9': (1.46, 2.05),
  57. 'a10': (1.02, 1.46),
  58. 'b0': (40.55, 57.32),
  59. 'b1': (28.66, 40.55),
  60. 'b2': (20.27, 28.66),
  61. 'b3': (14.33, 20.27),
  62. 'b4': (10.11, 14.33),
  63. 'b5': (7.16, 10.11),
  64. 'b6': (5.04, 7.16),
  65. 'b7': (3.58, 5.04),
  66. 'b8': (2.51, 3.58),
  67. 'b9': (1.76, 2.51),
  68. 'b10': (1.26, 1.76)}
  69. def _get_papertype(w, h):
  70. for key, (pw, ph) in sorted(papersize.items(), reverse=True):
  71. if key.startswith('l'):
  72. continue
  73. if w < pw and h < ph:
  74. return key
  75. return 'a0'
  76. def _nums_to_str(*args, sep=" "):
  77. return sep.join(f"{arg:1.3f}".rstrip("0").rstrip(".") for arg in args)
  78. def _move_path_to_path_or_stream(src, dst):
  79. """
  80. Move the contents of file at *src* to path-or-filelike *dst*.
  81. If *dst* is a path, the metadata of *src* are *not* copied.
  82. """
  83. if is_writable_file_like(dst):
  84. fh = (open(src, encoding='latin-1')
  85. if file_requires_unicode(dst)
  86. else open(src, 'rb'))
  87. with fh:
  88. shutil.copyfileobj(fh, dst)
  89. else:
  90. shutil.move(src, dst, copy_function=shutil.copyfile)
  91. def _font_to_ps_type3(font_path, chars):
  92. """
  93. Subset *chars* from the font at *font_path* into a Type 3 font.
  94. Parameters
  95. ----------
  96. font_path : path-like
  97. Path to the font to be subsetted.
  98. chars : str
  99. The characters to include in the subsetted font.
  100. Returns
  101. -------
  102. str
  103. The string representation of a Type 3 font, which can be included
  104. verbatim into a PostScript file.
  105. """
  106. font = get_font(font_path, hinting_factor=1)
  107. glyph_ids = [font.get_char_index(c) for c in chars]
  108. preamble = """\
  109. %!PS-Adobe-3.0 Resource-Font
  110. %%Creator: Converted from TrueType to Type 3 by Matplotlib.
  111. 10 dict begin
  112. /FontName /{font_name} def
  113. /PaintType 0 def
  114. /FontMatrix [{inv_units_per_em} 0 0 {inv_units_per_em} 0 0] def
  115. /FontBBox [{bbox}] def
  116. /FontType 3 def
  117. /Encoding [{encoding}] def
  118. /CharStrings {num_glyphs} dict dup begin
  119. /.notdef 0 def
  120. """.format(font_name=font.postscript_name,
  121. inv_units_per_em=1 / font.units_per_EM,
  122. bbox=" ".join(map(str, font.bbox)),
  123. encoding=" ".join(f"/{font.get_glyph_name(glyph_id)}"
  124. for glyph_id in glyph_ids),
  125. num_glyphs=len(glyph_ids) + 1)
  126. postamble = """
  127. end readonly def
  128. /BuildGlyph {
  129. exch begin
  130. CharStrings exch
  131. 2 copy known not {pop /.notdef} if
  132. true 3 1 roll get exec
  133. end
  134. } _d
  135. /BuildChar {
  136. 1 index /Encoding get exch get
  137. 1 index /BuildGlyph get exec
  138. } _d
  139. FontName currentdict end definefont pop
  140. """
  141. entries = []
  142. for glyph_id in glyph_ids:
  143. g = font.load_glyph(glyph_id, LOAD_NO_SCALE)
  144. v, c = font.get_path()
  145. entries.append(
  146. "/%(name)s{%(bbox)s sc\n" % {
  147. "name": font.get_glyph_name(glyph_id),
  148. "bbox": " ".join(map(str, [g.horiAdvance, 0, *g.bbox])),
  149. }
  150. + _path.convert_to_string(
  151. # Convert back to TrueType's internal units (1/64's).
  152. # (Other dimensions are already in these units.)
  153. Path(v * 64, c), None, None, False, None, 0,
  154. # No code for quad Beziers triggers auto-conversion to cubics.
  155. # Drop intermediate closepolys (relying on the outline
  156. # decomposer always explicitly moving to the closing point
  157. # first).
  158. [b"m", b"l", b"", b"c", b""], True).decode("ascii")
  159. + "ce} _d"
  160. )
  161. return preamble + "\n".join(entries) + postamble
  162. def _font_to_ps_type42(font_path, chars, fh):
  163. """
  164. Subset *chars* from the font at *font_path* into a Type 42 font at *fh*.
  165. Parameters
  166. ----------
  167. font_path : path-like
  168. Path to the font to be subsetted.
  169. chars : str
  170. The characters to include in the subsetted font.
  171. fh : file-like
  172. Where to write the font.
  173. """
  174. subset_str = ''.join(chr(c) for c in chars)
  175. _log.debug("SUBSET %s characters: %s", font_path, subset_str)
  176. try:
  177. fontdata = _backend_pdf_ps.get_glyphs_subset(font_path, subset_str)
  178. _log.debug("SUBSET %s %d -> %d", font_path, os.stat(font_path).st_size,
  179. fontdata.getbuffer().nbytes)
  180. # Give ttconv a subsetted font along with updated glyph_ids.
  181. font = FT2Font(fontdata)
  182. glyph_ids = [font.get_char_index(c) for c in chars]
  183. with TemporaryDirectory() as tmpdir:
  184. tmpfile = os.path.join(tmpdir, "tmp.ttf")
  185. with open(tmpfile, 'wb') as tmp:
  186. tmp.write(fontdata.getvalue())
  187. # TODO: allow convert_ttf_to_ps to input file objects (BytesIO)
  188. convert_ttf_to_ps(os.fsencode(tmpfile), fh, 42, glyph_ids)
  189. except RuntimeError:
  190. _log.warning(
  191. "The PostScript backend does not currently "
  192. "support the selected font.")
  193. raise
  194. def _log_if_debug_on(meth):
  195. """
  196. Wrap `RendererPS` method *meth* to emit a PS comment with the method name,
  197. if the global flag `debugPS` is set.
  198. """
  199. @functools.wraps(meth)
  200. def wrapper(self, *args, **kwargs):
  201. if debugPS:
  202. self._pswriter.write(f"% {meth.__name__}\n")
  203. return meth(self, *args, **kwargs)
  204. return wrapper
  205. class RendererPS(_backend_pdf_ps.RendererPDFPSBase):
  206. """
  207. The renderer handles all the drawing primitives using a graphics
  208. context instance that controls the colors/styles.
  209. """
  210. _afm_font_dir = cbook._get_data_path("fonts/afm")
  211. _use_afm_rc_name = "ps.useafm"
  212. def __init__(self, width, height, pswriter, imagedpi=72):
  213. # Although postscript itself is dpi independent, we need to inform the
  214. # image code about a requested dpi to generate high resolution images
  215. # and them scale them before embedding them.
  216. super().__init__(width, height)
  217. self._pswriter = pswriter
  218. if mpl.rcParams['text.usetex']:
  219. self.textcnt = 0
  220. self.psfrag = []
  221. self.imagedpi = imagedpi
  222. # current renderer state (None=uninitialised)
  223. self.color = None
  224. self.linewidth = None
  225. self.linejoin = None
  226. self.linecap = None
  227. self.linedash = None
  228. self.fontname = None
  229. self.fontsize = None
  230. self._hatches = {}
  231. self.image_magnification = imagedpi / 72
  232. self._clip_paths = {}
  233. self._path_collection_id = 0
  234. self._character_tracker = _backend_pdf_ps.CharacterTracker()
  235. self._logwarn_once = functools.cache(_log.warning)
  236. def _is_transparent(self, rgb_or_rgba):
  237. if rgb_or_rgba is None:
  238. return True # Consistent with rgbFace semantics.
  239. elif len(rgb_or_rgba) == 4:
  240. if rgb_or_rgba[3] == 0:
  241. return True
  242. if rgb_or_rgba[3] != 1:
  243. self._logwarn_once(
  244. "The PostScript backend does not support transparency; "
  245. "partially transparent artists will be rendered opaque.")
  246. return False
  247. else: # len() == 3.
  248. return False
  249. def set_color(self, r, g, b, store=True):
  250. if (r, g, b) != self.color:
  251. self._pswriter.write(f"{_nums_to_str(r)} setgray\n"
  252. if r == g == b else
  253. f"{_nums_to_str(r, g, b)} setrgbcolor\n")
  254. if store:
  255. self.color = (r, g, b)
  256. def set_linewidth(self, linewidth, store=True):
  257. linewidth = float(linewidth)
  258. if linewidth != self.linewidth:
  259. self._pswriter.write(f"{_nums_to_str(linewidth)} setlinewidth\n")
  260. if store:
  261. self.linewidth = linewidth
  262. @staticmethod
  263. def _linejoin_cmd(linejoin):
  264. # Support for directly passing integer values is for backcompat.
  265. linejoin = {'miter': 0, 'round': 1, 'bevel': 2, 0: 0, 1: 1, 2: 2}[
  266. linejoin]
  267. return f"{linejoin:d} setlinejoin\n"
  268. def set_linejoin(self, linejoin, store=True):
  269. if linejoin != self.linejoin:
  270. self._pswriter.write(self._linejoin_cmd(linejoin))
  271. if store:
  272. self.linejoin = linejoin
  273. @staticmethod
  274. def _linecap_cmd(linecap):
  275. # Support for directly passing integer values is for backcompat.
  276. linecap = {'butt': 0, 'round': 1, 'projecting': 2, 0: 0, 1: 1, 2: 2}[
  277. linecap]
  278. return f"{linecap:d} setlinecap\n"
  279. def set_linecap(self, linecap, store=True):
  280. if linecap != self.linecap:
  281. self._pswriter.write(self._linecap_cmd(linecap))
  282. if store:
  283. self.linecap = linecap
  284. def set_linedash(self, offset, seq, store=True):
  285. if self.linedash is not None:
  286. oldo, oldseq = self.linedash
  287. if np.array_equal(seq, oldseq) and oldo == offset:
  288. return
  289. self._pswriter.write(f"[{_nums_to_str(*seq)}] {_nums_to_str(offset)} setdash\n"
  290. if seq is not None and len(seq) else
  291. "[] 0 setdash\n")
  292. if store:
  293. self.linedash = (offset, seq)
  294. def set_font(self, fontname, fontsize, store=True):
  295. if (fontname, fontsize) != (self.fontname, self.fontsize):
  296. self._pswriter.write(f"/{fontname} {fontsize:1.3f} selectfont\n")
  297. if store:
  298. self.fontname = fontname
  299. self.fontsize = fontsize
  300. def create_hatch(self, hatch):
  301. sidelen = 72
  302. if hatch in self._hatches:
  303. return self._hatches[hatch]
  304. name = 'H%d' % len(self._hatches)
  305. linewidth = mpl.rcParams['hatch.linewidth']
  306. pageheight = self.height * 72
  307. self._pswriter.write(f"""\
  308. << /PatternType 1
  309. /PaintType 2
  310. /TilingType 2
  311. /BBox[0 0 {sidelen:d} {sidelen:d}]
  312. /XStep {sidelen:d}
  313. /YStep {sidelen:d}
  314. /PaintProc {{
  315. pop
  316. {linewidth:g} setlinewidth
  317. {self._convert_path(
  318. Path.hatch(hatch), Affine2D().scale(sidelen), simplify=False)}
  319. gsave
  320. fill
  321. grestore
  322. stroke
  323. }} bind
  324. >>
  325. matrix
  326. 0 {pageheight:g} translate
  327. makepattern
  328. /{name} exch def
  329. """)
  330. self._hatches[hatch] = name
  331. return name
  332. def get_image_magnification(self):
  333. """
  334. Get the factor by which to magnify images passed to draw_image.
  335. Allows a backend to have images at a different resolution to other
  336. artists.
  337. """
  338. return self.image_magnification
  339. def _convert_path(self, path, transform, clip=False, simplify=None):
  340. if clip:
  341. clip = (0.0, 0.0, self.width * 72.0, self.height * 72.0)
  342. else:
  343. clip = None
  344. return _path.convert_to_string(
  345. path, transform, clip, simplify, None,
  346. 6, [b"m", b"l", b"", b"c", b"cl"], True).decode("ascii")
  347. def _get_clip_cmd(self, gc):
  348. clip = []
  349. rect = gc.get_clip_rectangle()
  350. if rect is not None:
  351. clip.append(f"{_nums_to_str(*rect.p0, *rect.size)} rectclip\n")
  352. path, trf = gc.get_clip_path()
  353. if path is not None:
  354. key = (path, id(trf))
  355. custom_clip_cmd = self._clip_paths.get(key)
  356. if custom_clip_cmd is None:
  357. custom_clip_cmd = "c%d" % len(self._clip_paths)
  358. self._pswriter.write(f"""\
  359. /{custom_clip_cmd} {{
  360. {self._convert_path(path, trf, simplify=False)}
  361. clip
  362. newpath
  363. }} bind def
  364. """)
  365. self._clip_paths[key] = custom_clip_cmd
  366. clip.append(f"{custom_clip_cmd}\n")
  367. return "".join(clip)
  368. @_log_if_debug_on
  369. def draw_image(self, gc, x, y, im, transform=None):
  370. # docstring inherited
  371. h, w = im.shape[:2]
  372. imagecmd = "false 3 colorimage"
  373. data = im[::-1, :, :3] # Vertically flipped rgb values.
  374. hexdata = data.tobytes().hex("\n", -64) # Linewrap to 128 chars.
  375. if transform is None:
  376. matrix = "1 0 0 1 0 0"
  377. xscale = w / self.image_magnification
  378. yscale = h / self.image_magnification
  379. else:
  380. matrix = " ".join(map(str, transform.frozen().to_values()))
  381. xscale = 1.0
  382. yscale = 1.0
  383. self._pswriter.write(f"""\
  384. gsave
  385. {self._get_clip_cmd(gc)}
  386. {x:g} {y:g} translate
  387. [{matrix}] concat
  388. {xscale:g} {yscale:g} scale
  389. /DataString {w:d} string def
  390. {w:d} {h:d} 8 [ {w:d} 0 0 -{h:d} 0 {h:d} ]
  391. {{
  392. currentfile DataString readhexstring pop
  393. }} bind {imagecmd}
  394. {hexdata}
  395. grestore
  396. """)
  397. @_log_if_debug_on
  398. def draw_path(self, gc, path, transform, rgbFace=None):
  399. # docstring inherited
  400. clip = rgbFace is None and gc.get_hatch_path() is None
  401. simplify = path.should_simplify and clip
  402. ps = self._convert_path(path, transform, clip=clip, simplify=simplify)
  403. self._draw_ps(ps, gc, rgbFace)
  404. @_log_if_debug_on
  405. def draw_markers(
  406. self, gc, marker_path, marker_trans, path, trans, rgbFace=None):
  407. # docstring inherited
  408. ps_color = (
  409. None
  410. if self._is_transparent(rgbFace)
  411. else f'{_nums_to_str(rgbFace[0])} setgray'
  412. if rgbFace[0] == rgbFace[1] == rgbFace[2]
  413. else f'{_nums_to_str(*rgbFace[:3])} setrgbcolor')
  414. # construct the generic marker command:
  415. # don't want the translate to be global
  416. ps_cmd = ['/o {', 'gsave', 'newpath', 'translate']
  417. lw = gc.get_linewidth()
  418. alpha = (gc.get_alpha()
  419. if gc.get_forced_alpha() or len(gc.get_rgb()) == 3
  420. else gc.get_rgb()[3])
  421. stroke = lw > 0 and alpha > 0
  422. if stroke:
  423. ps_cmd.append('%.1f setlinewidth' % lw)
  424. ps_cmd.append(self._linejoin_cmd(gc.get_joinstyle()))
  425. ps_cmd.append(self._linecap_cmd(gc.get_capstyle()))
  426. ps_cmd.append(self._convert_path(marker_path, marker_trans,
  427. simplify=False))
  428. if rgbFace:
  429. if stroke:
  430. ps_cmd.append('gsave')
  431. if ps_color:
  432. ps_cmd.extend([ps_color, 'fill'])
  433. if stroke:
  434. ps_cmd.append('grestore')
  435. if stroke:
  436. ps_cmd.append('stroke')
  437. ps_cmd.extend(['grestore', '} bind def'])
  438. for vertices, code in path.iter_segments(
  439. trans,
  440. clip=(0, 0, self.width*72, self.height*72),
  441. simplify=False):
  442. if len(vertices):
  443. x, y = vertices[-2:]
  444. ps_cmd.append(f"{x:g} {y:g} o")
  445. ps = '\n'.join(ps_cmd)
  446. self._draw_ps(ps, gc, rgbFace, fill=False, stroke=False)
  447. @_log_if_debug_on
  448. def draw_path_collection(self, gc, master_transform, paths, all_transforms,
  449. offsets, offset_trans, facecolors, edgecolors,
  450. linewidths, linestyles, antialiaseds, urls,
  451. offset_position):
  452. # Is the optimization worth it? Rough calculation:
  453. # cost of emitting a path in-line is
  454. # (len_path + 2) * uses_per_path
  455. # cost of definition+use is
  456. # (len_path + 3) + 3 * uses_per_path
  457. len_path = len(paths[0].vertices) if len(paths) > 0 else 0
  458. uses_per_path = self._iter_collection_uses_per_path(
  459. paths, all_transforms, offsets, facecolors, edgecolors)
  460. should_do_optimization = \
  461. len_path + 3 * uses_per_path + 3 < (len_path + 2) * uses_per_path
  462. if not should_do_optimization:
  463. return RendererBase.draw_path_collection(
  464. self, gc, master_transform, paths, all_transforms,
  465. offsets, offset_trans, facecolors, edgecolors,
  466. linewidths, linestyles, antialiaseds, urls,
  467. offset_position)
  468. path_codes = []
  469. for i, (path, transform) in enumerate(self._iter_collection_raw_paths(
  470. master_transform, paths, all_transforms)):
  471. name = 'p%d_%d' % (self._path_collection_id, i)
  472. path_bytes = self._convert_path(path, transform, simplify=False)
  473. self._pswriter.write(f"""\
  474. /{name} {{
  475. newpath
  476. translate
  477. {path_bytes}
  478. }} bind def
  479. """)
  480. path_codes.append(name)
  481. for xo, yo, path_id, gc0, rgbFace in self._iter_collection(
  482. gc, path_codes, offsets, offset_trans,
  483. facecolors, edgecolors, linewidths, linestyles,
  484. antialiaseds, urls, offset_position):
  485. ps = f"{xo:g} {yo:g} {path_id}"
  486. self._draw_ps(ps, gc0, rgbFace)
  487. self._path_collection_id += 1
  488. @_log_if_debug_on
  489. def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None):
  490. # docstring inherited
  491. if self._is_transparent(gc.get_rgb()):
  492. return # Special handling for fully transparent.
  493. if not hasattr(self, "psfrag"):
  494. self._logwarn_once(
  495. "The PS backend determines usetex status solely based on "
  496. "rcParams['text.usetex'] and does not support having "
  497. "usetex=True only for some elements; this element will thus "
  498. "be rendered as if usetex=False.")
  499. self.draw_text(gc, x, y, s, prop, angle, False, mtext)
  500. return
  501. w, h, bl = self.get_text_width_height_descent(s, prop, ismath="TeX")
  502. fontsize = prop.get_size_in_points()
  503. thetext = 'psmarker%d' % self.textcnt
  504. color = _nums_to_str(*gc.get_rgb()[:3], sep=',')
  505. fontcmd = {'sans-serif': r'{\sffamily %s}',
  506. 'monospace': r'{\ttfamily %s}'}.get(
  507. mpl.rcParams['font.family'][0], r'{\rmfamily %s}')
  508. s = fontcmd % s
  509. tex = r'\color[rgb]{%s} %s' % (color, s)
  510. # Stick to bottom-left alignment, so subtract descent from the text-normal
  511. # direction since text is normally positioned by its baseline.
  512. rangle = np.radians(angle + 90)
  513. pos = _nums_to_str(x - bl * np.cos(rangle), y - bl * np.sin(rangle))
  514. self.psfrag.append(
  515. r'\psfrag{%s}[bl][bl][1][%f]{\fontsize{%f}{%f}%s}' % (
  516. thetext, angle, fontsize, fontsize*1.25, tex))
  517. self._pswriter.write(f"""\
  518. gsave
  519. {pos} moveto
  520. ({thetext})
  521. show
  522. grestore
  523. """)
  524. self.textcnt += 1
  525. @_log_if_debug_on
  526. def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
  527. # docstring inherited
  528. if self._is_transparent(gc.get_rgb()):
  529. return # Special handling for fully transparent.
  530. if ismath == 'TeX':
  531. return self.draw_tex(gc, x, y, s, prop, angle)
  532. if ismath:
  533. return self.draw_mathtext(gc, x, y, s, prop, angle)
  534. stream = [] # list of (ps_name, x, char_name)
  535. if mpl.rcParams['ps.useafm']:
  536. font = self._get_font_afm(prop)
  537. ps_name = (font.postscript_name.encode("ascii", "replace")
  538. .decode("ascii"))
  539. scale = 0.001 * prop.get_size_in_points()
  540. thisx = 0
  541. last_name = None # kerns returns 0 for None.
  542. for c in s:
  543. name = uni2type1.get(ord(c), f"uni{ord(c):04X}")
  544. try:
  545. width = font.get_width_from_char_name(name)
  546. except KeyError:
  547. name = 'question'
  548. width = font.get_width_char('?')
  549. kern = font.get_kern_dist_from_name(last_name, name)
  550. last_name = name
  551. thisx += kern * scale
  552. stream.append((ps_name, thisx, name))
  553. thisx += width * scale
  554. else:
  555. font = self._get_font_ttf(prop)
  556. self._character_tracker.track(font, s)
  557. for item in _text_helpers.layout(s, font):
  558. ps_name = (item.ft_object.postscript_name
  559. .encode("ascii", "replace").decode("ascii"))
  560. glyph_name = item.ft_object.get_glyph_name(item.glyph_idx)
  561. stream.append((ps_name, item.x, glyph_name))
  562. self.set_color(*gc.get_rgb())
  563. for ps_name, group in itertools. \
  564. groupby(stream, lambda entry: entry[0]):
  565. self.set_font(ps_name, prop.get_size_in_points(), False)
  566. thetext = "\n".join(f"{x:g} 0 m /{name:s} glyphshow"
  567. for _, x, name in group)
  568. self._pswriter.write(f"""\
  569. gsave
  570. {self._get_clip_cmd(gc)}
  571. {x:g} {y:g} translate
  572. {angle:g} rotate
  573. {thetext}
  574. grestore
  575. """)
  576. @_log_if_debug_on
  577. def draw_mathtext(self, gc, x, y, s, prop, angle):
  578. """Draw the math text using matplotlib.mathtext."""
  579. width, height, descent, glyphs, rects = \
  580. self._text2path.mathtext_parser.parse(s, 72, prop)
  581. self.set_color(*gc.get_rgb())
  582. self._pswriter.write(
  583. f"gsave\n"
  584. f"{x:g} {y:g} translate\n"
  585. f"{angle:g} rotate\n")
  586. lastfont = None
  587. for font, fontsize, num, ox, oy in glyphs:
  588. self._character_tracker.track_glyph(font, num)
  589. if (font.postscript_name, fontsize) != lastfont:
  590. lastfont = font.postscript_name, fontsize
  591. self._pswriter.write(
  592. f"/{font.postscript_name} {fontsize} selectfont\n")
  593. glyph_name = (
  594. font.get_name_char(chr(num)) if isinstance(font, AFM) else
  595. font.get_glyph_name(font.get_char_index(num)))
  596. self._pswriter.write(
  597. f"{ox:g} {oy:g} moveto\n"
  598. f"/{glyph_name} glyphshow\n")
  599. for ox, oy, w, h in rects:
  600. self._pswriter.write(f"{ox} {oy} {w} {h} rectfill\n")
  601. self._pswriter.write("grestore\n")
  602. @_log_if_debug_on
  603. def draw_gouraud_triangle(self, gc, points, colors, trans):
  604. self.draw_gouraud_triangles(gc, points.reshape((1, 3, 2)),
  605. colors.reshape((1, 3, 4)), trans)
  606. @_log_if_debug_on
  607. def draw_gouraud_triangles(self, gc, points, colors, trans):
  608. assert len(points) == len(colors)
  609. if len(points) == 0:
  610. return
  611. assert points.ndim == 3
  612. assert points.shape[1] == 3
  613. assert points.shape[2] == 2
  614. assert colors.ndim == 3
  615. assert colors.shape[1] == 3
  616. assert colors.shape[2] == 4
  617. shape = points.shape
  618. flat_points = points.reshape((shape[0] * shape[1], 2))
  619. flat_points = trans.transform(flat_points)
  620. flat_colors = colors.reshape((shape[0] * shape[1], 4))
  621. points_min = np.min(flat_points, axis=0) - (1 << 12)
  622. points_max = np.max(flat_points, axis=0) + (1 << 12)
  623. factor = np.ceil((2 ** 32 - 1) / (points_max - points_min))
  624. xmin, ymin = points_min
  625. xmax, ymax = points_max
  626. data = np.empty(
  627. shape[0] * shape[1],
  628. dtype=[('flags', 'u1'), ('points', '2>u4'), ('colors', '3u1')])
  629. data['flags'] = 0
  630. data['points'] = (flat_points - points_min) * factor
  631. data['colors'] = flat_colors[:, :3] * 255.0
  632. hexdata = data.tobytes().hex("\n", -64) # Linewrap to 128 chars.
  633. self._pswriter.write(f"""\
  634. gsave
  635. << /ShadingType 4
  636. /ColorSpace [/DeviceRGB]
  637. /BitsPerCoordinate 32
  638. /BitsPerComponent 8
  639. /BitsPerFlag 8
  640. /AntiAlias true
  641. /Decode [ {xmin:g} {xmax:g} {ymin:g} {ymax:g} 0 1 0 1 0 1 ]
  642. /DataSource <
  643. {hexdata}
  644. >
  645. >>
  646. shfill
  647. grestore
  648. """)
  649. def _draw_ps(self, ps, gc, rgbFace, *, fill=True, stroke=True):
  650. """
  651. Emit the PostScript snippet *ps* with all the attributes from *gc*
  652. applied. *ps* must consist of PostScript commands to construct a path.
  653. The *fill* and/or *stroke* kwargs can be set to False if the *ps*
  654. string already includes filling and/or stroking, in which case
  655. `_draw_ps` is just supplying properties and clipping.
  656. """
  657. write = self._pswriter.write
  658. mightstroke = (gc.get_linewidth() > 0
  659. and not self._is_transparent(gc.get_rgb()))
  660. if not mightstroke:
  661. stroke = False
  662. if self._is_transparent(rgbFace):
  663. fill = False
  664. hatch = gc.get_hatch()
  665. if mightstroke:
  666. self.set_linewidth(gc.get_linewidth())
  667. self.set_linejoin(gc.get_joinstyle())
  668. self.set_linecap(gc.get_capstyle())
  669. self.set_linedash(*gc.get_dashes())
  670. if mightstroke or hatch:
  671. self.set_color(*gc.get_rgb()[:3])
  672. write('gsave\n')
  673. write(self._get_clip_cmd(gc))
  674. write(ps.strip())
  675. write("\n")
  676. if fill:
  677. if stroke or hatch:
  678. write("gsave\n")
  679. self.set_color(*rgbFace[:3], store=False)
  680. write("fill\n")
  681. if stroke or hatch:
  682. write("grestore\n")
  683. if hatch:
  684. hatch_name = self.create_hatch(hatch)
  685. write("gsave\n")
  686. write(_nums_to_str(*gc.get_hatch_color()[:3]))
  687. write(f" {hatch_name} setpattern fill grestore\n")
  688. if stroke:
  689. write("stroke\n")
  690. write("grestore\n")
  691. class _Orientation(Enum):
  692. portrait, landscape = range(2)
  693. def swap_if_landscape(self, shape):
  694. return shape[::-1] if self.name == "landscape" else shape
  695. class FigureCanvasPS(FigureCanvasBase):
  696. fixed_dpi = 72
  697. filetypes = {'ps': 'Postscript',
  698. 'eps': 'Encapsulated Postscript'}
  699. def get_default_filetype(self):
  700. return 'ps'
  701. def _print_ps(
  702. self, fmt, outfile, *,
  703. metadata=None, papertype=None, orientation='portrait',
  704. bbox_inches_restore=None, **kwargs):
  705. dpi = self.figure.dpi
  706. self.figure.dpi = 72 # Override the dpi kwarg
  707. dsc_comments = {}
  708. if isinstance(outfile, (str, os.PathLike)):
  709. filename = pathlib.Path(outfile).name
  710. dsc_comments["Title"] = \
  711. filename.encode("ascii", "replace").decode("ascii")
  712. dsc_comments["Creator"] = (metadata or {}).get(
  713. "Creator",
  714. f"Matplotlib v{mpl.__version__}, https://matplotlib.org/")
  715. # See https://reproducible-builds.org/specs/source-date-epoch/
  716. source_date_epoch = os.getenv("SOURCE_DATE_EPOCH")
  717. dsc_comments["CreationDate"] = (
  718. datetime.datetime.fromtimestamp(
  719. int(source_date_epoch),
  720. datetime.timezone.utc).strftime("%a %b %d %H:%M:%S %Y")
  721. if source_date_epoch
  722. else time.ctime())
  723. dsc_comments = "\n".join(
  724. f"%%{k}: {v}" for k, v in dsc_comments.items())
  725. if papertype is None:
  726. papertype = mpl.rcParams['ps.papersize']
  727. papertype = papertype.lower()
  728. _api.check_in_list(['figure', 'auto', *papersize], papertype=papertype)
  729. orientation = _api.check_getitem(
  730. _Orientation, orientation=orientation.lower())
  731. printer = (self._print_figure_tex
  732. if mpl.rcParams['text.usetex'] else
  733. self._print_figure)
  734. printer(fmt, outfile, dpi=dpi, dsc_comments=dsc_comments,
  735. orientation=orientation, papertype=papertype,
  736. bbox_inches_restore=bbox_inches_restore, **kwargs)
  737. def _print_figure(
  738. self, fmt, outfile, *,
  739. dpi, dsc_comments, orientation, papertype,
  740. bbox_inches_restore=None):
  741. """
  742. Render the figure to a filesystem path or a file-like object.
  743. Parameters are as for `.print_figure`, except that *dsc_comments* is a
  744. string containing Document Structuring Convention comments,
  745. generated from the *metadata* parameter to `.print_figure`.
  746. """
  747. is_eps = fmt == 'eps'
  748. if not (isinstance(outfile, (str, os.PathLike))
  749. or is_writable_file_like(outfile)):
  750. raise ValueError("outfile must be a path or a file-like object")
  751. # find the appropriate papertype
  752. width, height = self.figure.get_size_inches()
  753. if papertype == 'auto':
  754. papertype = _get_papertype(*orientation.swap_if_landscape((width, height)))
  755. if is_eps or papertype == 'figure':
  756. paper_width, paper_height = width, height
  757. else:
  758. paper_width, paper_height = orientation.swap_if_landscape(
  759. papersize[papertype])
  760. # center the figure on the paper
  761. xo = 72 * 0.5 * (paper_width - width)
  762. yo = 72 * 0.5 * (paper_height - height)
  763. llx = xo
  764. lly = yo
  765. urx = llx + self.figure.bbox.width
  766. ury = lly + self.figure.bbox.height
  767. rotation = 0
  768. if orientation is _Orientation.landscape:
  769. llx, lly, urx, ury = lly, llx, ury, urx
  770. xo, yo = 72 * paper_height - yo, xo
  771. rotation = 90
  772. bbox = (llx, lly, urx, ury)
  773. self._pswriter = StringIO()
  774. # mixed mode rendering
  775. ps_renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi)
  776. renderer = MixedModeRenderer(
  777. self.figure, width, height, dpi, ps_renderer,
  778. bbox_inches_restore=bbox_inches_restore)
  779. self.figure.draw(renderer)
  780. def print_figure_impl(fh):
  781. # write the PostScript headers
  782. if is_eps:
  783. print("%!PS-Adobe-3.0 EPSF-3.0", file=fh)
  784. else:
  785. print("%!PS-Adobe-3.0", file=fh)
  786. if papertype != 'figure':
  787. print(f"%%DocumentPaperSizes: {papertype}", file=fh)
  788. print("%%Pages: 1", file=fh)
  789. print(f"%%LanguageLevel: 3\n"
  790. f"{dsc_comments}\n"
  791. f"%%Orientation: {orientation.name}\n"
  792. f"{get_bbox_header(bbox)[0]}\n"
  793. f"%%EndComments\n",
  794. end="", file=fh)
  795. Ndict = len(_psDefs)
  796. print("%%BeginProlog", file=fh)
  797. if not mpl.rcParams['ps.useafm']:
  798. Ndict += len(ps_renderer._character_tracker.used)
  799. print("/mpldict %d dict def" % Ndict, file=fh)
  800. print("mpldict begin", file=fh)
  801. print("\n".join(_psDefs), file=fh)
  802. if not mpl.rcParams['ps.useafm']:
  803. for font_path, chars \
  804. in ps_renderer._character_tracker.used.items():
  805. if not chars:
  806. continue
  807. fonttype = mpl.rcParams['ps.fonttype']
  808. # Can't use more than 255 chars from a single Type 3 font.
  809. if len(chars) > 255:
  810. fonttype = 42
  811. fh.flush()
  812. if fonttype == 3:
  813. fh.write(_font_to_ps_type3(font_path, chars))
  814. else: # Type 42 only.
  815. _font_to_ps_type42(font_path, chars, fh)
  816. print("end", file=fh)
  817. print("%%EndProlog", file=fh)
  818. if not is_eps:
  819. print("%%Page: 1 1", file=fh)
  820. print("mpldict begin", file=fh)
  821. print("%s translate" % _nums_to_str(xo, yo), file=fh)
  822. if rotation:
  823. print("%d rotate" % rotation, file=fh)
  824. print(f"0 0 {_nums_to_str(width*72, height*72)} rectclip", file=fh)
  825. # write the figure
  826. print(self._pswriter.getvalue(), file=fh)
  827. # write the trailer
  828. print("end", file=fh)
  829. print("showpage", file=fh)
  830. if not is_eps:
  831. print("%%EOF", file=fh)
  832. fh.flush()
  833. if mpl.rcParams['ps.usedistiller']:
  834. # We are going to use an external program to process the output.
  835. # Write to a temporary file.
  836. with TemporaryDirectory() as tmpdir:
  837. tmpfile = os.path.join(tmpdir, "tmp.ps")
  838. with open(tmpfile, 'w', encoding='latin-1') as fh:
  839. print_figure_impl(fh)
  840. if mpl.rcParams['ps.usedistiller'] == 'ghostscript':
  841. _try_distill(gs_distill,
  842. tmpfile, is_eps, ptype=papertype, bbox=bbox)
  843. elif mpl.rcParams['ps.usedistiller'] == 'xpdf':
  844. _try_distill(xpdf_distill,
  845. tmpfile, is_eps, ptype=papertype, bbox=bbox)
  846. _move_path_to_path_or_stream(tmpfile, outfile)
  847. else: # Write directly to outfile.
  848. with cbook.open_file_cm(outfile, "w", encoding="latin-1") as file:
  849. if not file_requires_unicode(file):
  850. file = codecs.getwriter("latin-1")(file)
  851. print_figure_impl(file)
  852. def _print_figure_tex(
  853. self, fmt, outfile, *,
  854. dpi, dsc_comments, orientation, papertype,
  855. bbox_inches_restore=None):
  856. """
  857. If :rc:`text.usetex` is True, a temporary pair of tex/eps files
  858. are created to allow tex to manage the text layout via the PSFrags
  859. package. These files are processed to yield the final ps or eps file.
  860. The rest of the behavior is as for `._print_figure`.
  861. """
  862. is_eps = fmt == 'eps'
  863. width, height = self.figure.get_size_inches()
  864. xo = 0
  865. yo = 0
  866. llx = xo
  867. lly = yo
  868. urx = llx + self.figure.bbox.width
  869. ury = lly + self.figure.bbox.height
  870. bbox = (llx, lly, urx, ury)
  871. self._pswriter = StringIO()
  872. # mixed mode rendering
  873. ps_renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi)
  874. renderer = MixedModeRenderer(self.figure,
  875. width, height, dpi, ps_renderer,
  876. bbox_inches_restore=bbox_inches_restore)
  877. self.figure.draw(renderer)
  878. # write to a temp file, we'll move it to outfile when done
  879. with TemporaryDirectory() as tmpdir:
  880. tmppath = pathlib.Path(tmpdir, "tmp.ps")
  881. tmppath.write_text(
  882. f"""\
  883. %!PS-Adobe-3.0 EPSF-3.0
  884. %%LanguageLevel: 3
  885. {dsc_comments}
  886. {get_bbox_header(bbox)[0]}
  887. %%EndComments
  888. %%BeginProlog
  889. /mpldict {len(_psDefs)} dict def
  890. mpldict begin
  891. {"".join(_psDefs)}
  892. end
  893. %%EndProlog
  894. mpldict begin
  895. {_nums_to_str(xo, yo)} translate
  896. 0 0 {_nums_to_str(width*72, height*72)} rectclip
  897. {self._pswriter.getvalue()}
  898. end
  899. showpage
  900. """,
  901. encoding="latin-1")
  902. if orientation is _Orientation.landscape: # now, ready to rotate
  903. width, height = height, width
  904. bbox = (lly, llx, ury, urx)
  905. # set the paper size to the figure size if is_eps. The
  906. # resulting ps file has the given size with correct bounding
  907. # box so that there is no need to call 'pstoeps'
  908. if is_eps or papertype == 'figure':
  909. paper_width, paper_height = orientation.swap_if_landscape(
  910. self.figure.get_size_inches())
  911. else:
  912. if papertype == 'auto':
  913. papertype = _get_papertype(width, height)
  914. paper_width, paper_height = papersize[papertype]
  915. psfrag_rotated = _convert_psfrags(
  916. tmppath, ps_renderer.psfrag, paper_width, paper_height,
  917. orientation.name)
  918. if (mpl.rcParams['ps.usedistiller'] == 'ghostscript'
  919. or mpl.rcParams['text.usetex']):
  920. _try_distill(gs_distill,
  921. tmppath, is_eps, ptype=papertype, bbox=bbox,
  922. rotated=psfrag_rotated)
  923. elif mpl.rcParams['ps.usedistiller'] == 'xpdf':
  924. _try_distill(xpdf_distill,
  925. tmppath, is_eps, ptype=papertype, bbox=bbox,
  926. rotated=psfrag_rotated)
  927. _move_path_to_path_or_stream(tmppath, outfile)
  928. print_ps = functools.partialmethod(_print_ps, "ps")
  929. print_eps = functools.partialmethod(_print_ps, "eps")
  930. def draw(self):
  931. self.figure.draw_without_rendering()
  932. return super().draw()
  933. def _convert_psfrags(tmppath, psfrags, paper_width, paper_height, orientation):
  934. """
  935. When we want to use the LaTeX backend with postscript, we write PSFrag tags
  936. to a temporary postscript file, each one marking a position for LaTeX to
  937. render some text. convert_psfrags generates a LaTeX document containing the
  938. commands to convert those tags to text. LaTeX/dvips produces the postscript
  939. file that includes the actual text.
  940. """
  941. with mpl.rc_context({
  942. "text.latex.preamble":
  943. mpl.rcParams["text.latex.preamble"] +
  944. mpl.texmanager._usepackage_if_not_loaded("color") +
  945. mpl.texmanager._usepackage_if_not_loaded("graphicx") +
  946. mpl.texmanager._usepackage_if_not_loaded("psfrag") +
  947. r"\geometry{papersize={%(width)sin,%(height)sin},margin=0in}"
  948. % {"width": paper_width, "height": paper_height}
  949. }):
  950. dvifile = TexManager().make_dvi(
  951. "\n"
  952. r"\begin{figure}""\n"
  953. r" \centering\leavevmode""\n"
  954. r" %(psfrags)s""\n"
  955. r" \includegraphics*[angle=%(angle)s]{%(epsfile)s}""\n"
  956. r"\end{figure}"
  957. % {
  958. "psfrags": "\n".join(psfrags),
  959. "angle": 90 if orientation == 'landscape' else 0,
  960. "epsfile": tmppath.resolve().as_posix(),
  961. },
  962. fontsize=10) # tex's default fontsize.
  963. with TemporaryDirectory() as tmpdir:
  964. psfile = os.path.join(tmpdir, "tmp.ps")
  965. cbook._check_and_log_subprocess(
  966. ['dvips', '-q', '-R0', '-o', psfile, dvifile], _log)
  967. shutil.move(psfile, tmppath)
  968. # check if the dvips created a ps in landscape paper. Somehow,
  969. # above latex+dvips results in a ps file in a landscape mode for a
  970. # certain figure sizes (e.g., 8.3in, 5.8in which is a5). And the
  971. # bounding box of the final output got messed up. We check see if
  972. # the generated ps file is in landscape and return this
  973. # information. The return value is used in pstoeps step to recover
  974. # the correct bounding box. 2010-06-05 JJL
  975. with open(tmppath) as fh:
  976. psfrag_rotated = "Landscape" in fh.read(1000)
  977. return psfrag_rotated
  978. def _try_distill(func, tmppath, *args, **kwargs):
  979. try:
  980. func(str(tmppath), *args, **kwargs)
  981. except mpl.ExecutableNotFoundError as exc:
  982. _log.warning("%s. Distillation step skipped.", exc)
  983. def gs_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False):
  984. """
  985. Use ghostscript's pswrite or epswrite device to distill a file.
  986. This yields smaller files without illegal encapsulated postscript
  987. operators. The output is low-level, converting text to outlines.
  988. """
  989. if eps:
  990. paper_option = ["-dEPSCrop"]
  991. elif ptype == "figure":
  992. # The bbox will have its lower-left corner at (0, 0), so upper-right
  993. # corner corresponds with paper size.
  994. paper_option = [f"-dDEVICEWIDTHPOINTS={bbox[2]}",
  995. f"-dDEVICEHEIGHTPOINTS={bbox[3]}"]
  996. else:
  997. paper_option = [f"-sPAPERSIZE={ptype}"]
  998. psfile = tmpfile + '.ps'
  999. dpi = mpl.rcParams['ps.distiller.res']
  1000. cbook._check_and_log_subprocess(
  1001. [mpl._get_executable_info("gs").executable,
  1002. "-dBATCH", "-dNOPAUSE", "-r%d" % dpi, "-sDEVICE=ps2write",
  1003. *paper_option, f"-sOutputFile={psfile}", tmpfile],
  1004. _log)
  1005. os.remove(tmpfile)
  1006. shutil.move(psfile, tmpfile)
  1007. # While it is best if above steps preserve the original bounding
  1008. # box, there seem to be cases when it is not. For those cases,
  1009. # the original bbox can be restored during the pstoeps step.
  1010. if eps:
  1011. # For some versions of gs, above steps result in a ps file where the
  1012. # original bbox is no more correct. Do not adjust bbox for now.
  1013. pstoeps(tmpfile, bbox, rotated=rotated)
  1014. def xpdf_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False):
  1015. """
  1016. Use ghostscript's ps2pdf and xpdf's/poppler's pdftops to distill a file.
  1017. This yields smaller files without illegal encapsulated postscript
  1018. operators. This distiller is preferred, generating high-level postscript
  1019. output that treats text as text.
  1020. """
  1021. mpl._get_executable_info("gs") # Effectively checks for ps2pdf.
  1022. mpl._get_executable_info("pdftops")
  1023. if eps:
  1024. paper_option = ["-dEPSCrop"]
  1025. elif ptype == "figure":
  1026. # The bbox will have its lower-left corner at (0, 0), so upper-right
  1027. # corner corresponds with paper size.
  1028. paper_option = [f"-dDEVICEWIDTHPOINTS#{bbox[2]}",
  1029. f"-dDEVICEHEIGHTPOINTS#{bbox[3]}"]
  1030. else:
  1031. paper_option = [f"-sPAPERSIZE#{ptype}"]
  1032. with TemporaryDirectory() as tmpdir:
  1033. tmppdf = pathlib.Path(tmpdir, "tmp.pdf")
  1034. tmpps = pathlib.Path(tmpdir, "tmp.ps")
  1035. # Pass options as `-foo#bar` instead of `-foo=bar` to keep Windows
  1036. # happy (https://ghostscript.com/doc/9.56.1/Use.htm#MS_Windows).
  1037. cbook._check_and_log_subprocess(
  1038. ["ps2pdf",
  1039. "-dAutoFilterColorImages#false",
  1040. "-dAutoFilterGrayImages#false",
  1041. "-sAutoRotatePages#None",
  1042. "-sGrayImageFilter#FlateEncode",
  1043. "-sColorImageFilter#FlateEncode",
  1044. *paper_option,
  1045. tmpfile, tmppdf], _log)
  1046. cbook._check_and_log_subprocess(
  1047. ["pdftops", "-paper", "match", "-level3", tmppdf, tmpps], _log)
  1048. shutil.move(tmpps, tmpfile)
  1049. if eps:
  1050. pstoeps(tmpfile)
  1051. def get_bbox_header(lbrt, rotated=False):
  1052. """
  1053. Return a postscript header string for the given bbox lbrt=(l, b, r, t).
  1054. Optionally, return rotate command.
  1055. """
  1056. l, b, r, t = lbrt
  1057. if rotated:
  1058. rotate = f"{l+r:.2f} {0:.2f} translate\n90 rotate"
  1059. else:
  1060. rotate = ""
  1061. bbox_info = '%%%%BoundingBox: %d %d %d %d' % (l, b, np.ceil(r), np.ceil(t))
  1062. hires_bbox_info = f'%%HiResBoundingBox: {l:.6f} {b:.6f} {r:.6f} {t:.6f}'
  1063. return '\n'.join([bbox_info, hires_bbox_info]), rotate
  1064. def pstoeps(tmpfile, bbox=None, rotated=False):
  1065. """
  1066. Convert the postscript to encapsulated postscript. The bbox of
  1067. the eps file will be replaced with the given *bbox* argument. If
  1068. None, original bbox will be used.
  1069. """
  1070. # if rotated==True, the output eps file need to be rotated
  1071. if bbox:
  1072. bbox_info, rotate = get_bbox_header(bbox, rotated=rotated)
  1073. else:
  1074. bbox_info, rotate = None, None
  1075. epsfile = tmpfile + '.eps'
  1076. with open(epsfile, 'wb') as epsh, open(tmpfile, 'rb') as tmph:
  1077. write = epsh.write
  1078. # Modify the header:
  1079. for line in tmph:
  1080. if line.startswith(b'%!PS'):
  1081. write(b"%!PS-Adobe-3.0 EPSF-3.0\n")
  1082. if bbox:
  1083. write(bbox_info.encode('ascii') + b'\n')
  1084. elif line.startswith(b'%%EndComments'):
  1085. write(line)
  1086. write(b'%%BeginProlog\n'
  1087. b'save\n'
  1088. b'countdictstack\n'
  1089. b'mark\n'
  1090. b'newpath\n'
  1091. b'/showpage {} def\n'
  1092. b'/setpagedevice {pop} def\n'
  1093. b'%%EndProlog\n'
  1094. b'%%Page 1 1\n')
  1095. if rotate:
  1096. write(rotate.encode('ascii') + b'\n')
  1097. break
  1098. elif bbox and line.startswith((b'%%Bound', b'%%HiResBound',
  1099. b'%%DocumentMedia', b'%%Pages')):
  1100. pass
  1101. else:
  1102. write(line)
  1103. # Now rewrite the rest of the file, and modify the trailer.
  1104. # This is done in a second loop such that the header of the embedded
  1105. # eps file is not modified.
  1106. for line in tmph:
  1107. if line.startswith(b'%%EOF'):
  1108. write(b'cleartomark\n'
  1109. b'countdictstack\n'
  1110. b'exch sub { end } repeat\n'
  1111. b'restore\n'
  1112. b'showpage\n'
  1113. b'%%EOF\n')
  1114. elif line.startswith(b'%%PageBoundingBox'):
  1115. pass
  1116. else:
  1117. write(line)
  1118. os.remove(tmpfile)
  1119. shutil.move(epsfile, tmpfile)
  1120. FigureManagerPS = FigureManagerBase
  1121. # The following Python dictionary psDefs contains the entries for the
  1122. # PostScript dictionary mpldict. This dictionary implements most of
  1123. # the matplotlib primitives and some abbreviations.
  1124. #
  1125. # References:
  1126. # https://www.adobe.com/content/dam/acom/en/devnet/actionscript/articles/PLRM.pdf
  1127. # http://preserve.mactech.com/articles/mactech/Vol.09/09.04/PostscriptTutorial
  1128. # http://www.math.ubc.ca/people/faculty/cass/graphics/text/www/
  1129. #
  1130. # The usage comments use the notation of the operator summary
  1131. # in the PostScript Language reference manual.
  1132. _psDefs = [
  1133. # name proc *_d* -
  1134. # Note that this cannot be bound to /d, because when embedding a Type3 font
  1135. # we may want to define a "d" glyph using "/d{...} d" which would locally
  1136. # overwrite the definition.
  1137. "/_d { bind def } bind def",
  1138. # x y *m* -
  1139. "/m { moveto } _d",
  1140. # x y *l* -
  1141. "/l { lineto } _d",
  1142. # x y *r* -
  1143. "/r { rlineto } _d",
  1144. # x1 y1 x2 y2 x y *c* -
  1145. "/c { curveto } _d",
  1146. # *cl* -
  1147. "/cl { closepath } _d",
  1148. # *ce* -
  1149. "/ce { closepath eofill } _d",
  1150. # wx wy llx lly urx ury *setcachedevice* -
  1151. "/sc { setcachedevice } _d",
  1152. ]
  1153. @_Backend.export
  1154. class _BackendPS(_Backend):
  1155. backend_version = 'Level II'
  1156. FigureCanvas = FigureCanvasPS