latextools.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. # -*- coding: utf-8 -*-
  2. """Tools for handling LaTeX."""
  3. # Copyright (c) IPython Development Team.
  4. # Distributed under the terms of the Modified BSD License.
  5. from io import BytesIO, open
  6. import os
  7. import tempfile
  8. import shutil
  9. import subprocess
  10. from base64 import encodebytes
  11. import textwrap
  12. from pathlib import Path
  13. from IPython.utils.process import find_cmd, FindCmdError
  14. from traitlets.config import get_config
  15. from traitlets.config.configurable import SingletonConfigurable
  16. from traitlets import List, Bool, Unicode
  17. class LaTeXTool(SingletonConfigurable):
  18. """An object to store configuration of the LaTeX tool."""
  19. def _config_default(self):
  20. return get_config()
  21. backends = List(
  22. Unicode(), ["matplotlib", "dvipng"],
  23. help="Preferred backend to draw LaTeX math equations. "
  24. "Backends in the list are checked one by one and the first "
  25. "usable one is used. Note that `matplotlib` backend "
  26. "is usable only for inline style equations. To draw "
  27. "display style equations, `dvipng` backend must be specified. ",
  28. # It is a List instead of Enum, to make configuration more
  29. # flexible. For example, to use matplotlib mainly but dvipng
  30. # for display style, the default ["matplotlib", "dvipng"] can
  31. # be used. To NOT use dvipng so that other repr such as
  32. # unicode pretty printing is used, you can use ["matplotlib"].
  33. ).tag(config=True)
  34. use_breqn = Bool(
  35. True,
  36. help="Use breqn.sty to automatically break long equations. "
  37. "This configuration takes effect only for dvipng backend.",
  38. ).tag(config=True)
  39. packages = List(
  40. ['amsmath', 'amsthm', 'amssymb', 'bm'],
  41. help="A list of packages to use for dvipng backend. "
  42. "'breqn' will be automatically appended when use_breqn=True.",
  43. ).tag(config=True)
  44. preamble = Unicode(
  45. help="Additional preamble to use when generating LaTeX source "
  46. "for dvipng backend.",
  47. ).tag(config=True)
  48. def latex_to_png(
  49. s: str, encode=False, backend=None, wrap=False, color="Black", scale=1.0
  50. ):
  51. """Render a LaTeX string to PNG.
  52. Parameters
  53. ----------
  54. s : str
  55. The raw string containing valid inline LaTeX.
  56. encode : bool, optional
  57. Should the PNG data base64 encoded to make it JSON'able.
  58. backend : {matplotlib, dvipng}
  59. Backend for producing PNG data.
  60. wrap : bool
  61. If true, Automatically wrap `s` as a LaTeX equation.
  62. color : string
  63. Foreground color name among dvipsnames, e.g. 'Maroon' or on hex RGB
  64. format, e.g. '#AA20FA'.
  65. scale : float
  66. Scale factor for the resulting PNG.
  67. None is returned when the backend cannot be used.
  68. """
  69. assert isinstance(s, str)
  70. allowed_backends = LaTeXTool.instance().backends
  71. if backend is None:
  72. backend = allowed_backends[0]
  73. if backend not in allowed_backends:
  74. return None
  75. if backend == 'matplotlib':
  76. f = latex_to_png_mpl
  77. elif backend == 'dvipng':
  78. f = latex_to_png_dvipng
  79. if color.startswith('#'):
  80. # Convert hex RGB color to LaTeX RGB color.
  81. if len(color) == 7:
  82. try:
  83. color = "RGB {}".format(" ".join([str(int(x, 16)) for x in
  84. textwrap.wrap(color[1:], 2)]))
  85. except ValueError as e:
  86. raise ValueError('Invalid color specification {}.'.format(color)) from e
  87. else:
  88. raise ValueError('Invalid color specification {}.'.format(color))
  89. else:
  90. raise ValueError('No such backend {0}'.format(backend))
  91. bin_data = f(s, wrap, color, scale)
  92. if encode and bin_data:
  93. bin_data = encodebytes(bin_data)
  94. return bin_data
  95. def latex_to_png_mpl(s, wrap, color='Black', scale=1.0):
  96. try:
  97. from matplotlib import figure, font_manager, mathtext
  98. from matplotlib.backends import backend_agg
  99. from pyparsing import ParseFatalException
  100. except ImportError:
  101. return None
  102. # mpl mathtext doesn't support display math, force inline
  103. s = s.replace('$$', '$')
  104. if wrap:
  105. s = u'${0}$'.format(s)
  106. try:
  107. prop = font_manager.FontProperties(size=12)
  108. dpi = 120 * scale
  109. buffer = BytesIO()
  110. # Adapted from mathtext.math_to_image
  111. parser = mathtext.MathTextParser("path")
  112. width, height, depth, _, _ = parser.parse(s, dpi=72, prop=prop)
  113. fig = figure.Figure(figsize=(width / 72, height / 72))
  114. fig.text(0, depth / height, s, fontproperties=prop, color=color)
  115. backend_agg.FigureCanvasAgg(fig)
  116. fig.savefig(buffer, dpi=dpi, format="png", transparent=True)
  117. return buffer.getvalue()
  118. except (ValueError, RuntimeError, ParseFatalException):
  119. return None
  120. def latex_to_png_dvipng(s, wrap, color='Black', scale=1.0):
  121. try:
  122. find_cmd('latex')
  123. find_cmd('dvipng')
  124. except FindCmdError:
  125. return None
  126. startupinfo = None
  127. if os.name == "nt":
  128. # prevent popup-windows
  129. startupinfo = subprocess.STARTUPINFO()
  130. startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  131. try:
  132. workdir = Path(tempfile.mkdtemp())
  133. tmpfile = "tmp.tex"
  134. dvifile = "tmp.dvi"
  135. outfile = "tmp.png"
  136. with workdir.joinpath(tmpfile).open("w", encoding="utf8") as f:
  137. f.writelines(genelatex(s, wrap))
  138. subprocess.check_call(
  139. ["latex", "-halt-on-error", "-interaction", "batchmode", tmpfile],
  140. cwd=workdir,
  141. stdout=subprocess.DEVNULL,
  142. stderr=subprocess.DEVNULL,
  143. startupinfo=startupinfo,
  144. )
  145. resolution = round(150 * scale)
  146. subprocess.check_call(
  147. [
  148. "dvipng",
  149. "-T",
  150. "tight",
  151. "-D",
  152. str(resolution),
  153. "-z",
  154. "9",
  155. "-bg",
  156. "Transparent",
  157. "-o",
  158. outfile,
  159. dvifile,
  160. "-fg",
  161. color,
  162. ],
  163. cwd=workdir,
  164. stdout=subprocess.DEVNULL,
  165. stderr=subprocess.DEVNULL,
  166. startupinfo=startupinfo,
  167. )
  168. with workdir.joinpath(outfile).open("rb") as f:
  169. return f.read()
  170. except subprocess.CalledProcessError:
  171. return None
  172. finally:
  173. shutil.rmtree(workdir)
  174. def kpsewhich(filename):
  175. """Invoke kpsewhich command with an argument `filename`."""
  176. try:
  177. find_cmd("kpsewhich")
  178. proc = subprocess.Popen(
  179. ["kpsewhich", filename],
  180. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  181. (stdout, stderr) = proc.communicate()
  182. return stdout.strip().decode('utf8', 'replace')
  183. except FindCmdError:
  184. pass
  185. def genelatex(body, wrap):
  186. """Generate LaTeX document for dvipng backend."""
  187. lt = LaTeXTool.instance()
  188. breqn = wrap and lt.use_breqn and kpsewhich("breqn.sty")
  189. yield r'\documentclass{article}'
  190. packages = lt.packages
  191. if breqn:
  192. packages = packages + ['breqn']
  193. for pack in packages:
  194. yield r'\usepackage{{{0}}}'.format(pack)
  195. yield r'\pagestyle{empty}'
  196. if lt.preamble:
  197. yield lt.preamble
  198. yield r'\begin{document}'
  199. if breqn:
  200. yield r'\begin{dmath*}'
  201. yield body
  202. yield r'\end{dmath*}'
  203. elif wrap:
  204. yield u'$${0}$$'.format(body)
  205. else:
  206. yield body
  207. yield u'\\end{document}'
  208. _data_uri_template_png = u"""<img src="data:image/png;base64,%s" alt=%s />"""
  209. def latex_to_html(s, alt='image'):
  210. """Render LaTeX to HTML with embedded PNG data using data URIs.
  211. Parameters
  212. ----------
  213. s : str
  214. The raw string containing valid inline LateX.
  215. alt : str
  216. The alt text to use for the HTML.
  217. """
  218. base64_data = latex_to_png(s, encode=True).decode('ascii')
  219. if base64_data:
  220. return _data_uri_template_png % (base64_data, alt)