TexLiLy/latex.py
2023-06-12 21:23:20 +02:00

40 lines
1.2 KiB
Python

# Converts a TeX file into a PNG/SVG file.
template = r"""
\documentclass[utf8,preview]{{standalone}}
\usepackage{{amsmath}}
\usepackage[active,tightpage]{{preview}}
\usepackage[utf8]{{inputenc}}
% TODO: Add user packages here.
\begin{{document}}
% The user content goes here.
{content}
\end{{document}}
"""
def render(user: str, source: str, png: bool = True) -> str:
import tempfile
import subprocess
fmt = template.format(content=source)
tmp = tempfile.NamedTemporaryFile(delete=False)
tmp.write(bytes(fmt, encoding="utf8"))
tmp.close()
print(tmp.name)
# Parse our templated file thru' LaTeX and dvipng.
# TODO: Allow arbitrary DPI and foreground color.
ret = subprocess.run(["latex", "-halt-on-error", tmp.name], cwd="/tmp", capture_output=True)
if ret.returncode != 0:
raise FileNotFoundError(ret.stdout.decode())
if png:
print("PNG")
subprocess.run(["dvipng", "-D", "2000", tmp.name + ".dvi", "-bg", "Transparent",
"-fg", "rgb 1 1 1", "-o", tmp.name + ".png"], cwd="/tmp")
return tmp.name + ".png"
# TODO:
raise NotImplementedError("SVG support is not currently implemented")