Skip to content

Instantly share code, notes, and snippets.

Last active September 21, 2023 01:56
  • Star 17 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save gmarull/dcc8218385014559c1ca46047457c364 to your computer and use it in GitHub Desktop.
Render TeX to SVG in Python using matplotlib and display with PyQt
import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtSvg import QSvgWidget
from io import BytesIO
import matplotlib.pyplot as plt
# matplotlib: force computer modern font set
plt.rc('mathtext', fontset='cm')
def tex2svg(formula, fontsize=12, dpi=300):
"""Render TeX formula to SVG.
formula (str): TeX formula.
fontsize (int, optional): Font size.
dpi (int, optional): DPI.
str: SVG render.
fig = plt.figure(figsize=(0.01, 0.01))
fig.text(0, 0, r'${}$'.format(formula), fontsize=fontsize)
output = BytesIO()
fig.savefig(output, dpi=dpi, transparent=True, format='svg',
bbox_inches='tight', pad_inches=0.0, frameon=False)
def main():
FORMULA = r'\int_{-\infty}^\infty e^{-x^2}\,dx = \sqrt{\pi}'
app = QApplication(sys.argv)
svg = QSvgWidget()
if __name__ == '__main__':
Copy link

gmarull commented Mar 5, 2018

Preview (scaled window):


Copy link

GzuPark commented Jan 9, 2021

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment