mirror of
https://git.freetards.xyz/array.in.a.matrix/TexLiLy.git
synced 2025-04-02 13:21:42 -04:00
53 lines
1.5 KiB
Python
53 lines
1.5 KiB
Python
# Converts a TeX file into a PNG/SVG file.
|
|
template = r"""
|
|
\documentclass[utf8,preview,varwidth]{{standalone}}
|
|
\usepackage{{amsmath}}
|
|
\usepackage[active]{{preview}}
|
|
\usepackage[utf8]{{inputenc}}
|
|
\usepackage{{tikz}}
|
|
% TODO: Add user packages here.
|
|
{packages}
|
|
\begin{{document}}
|
|
% The user content goes here.
|
|
{content}
|
|
|
|
\end{{document}}
|
|
"""
|
|
|
|
|
|
def render(user: str, source: str, png: bool = True) -> str:
|
|
import tempfile
|
|
import subprocess
|
|
import utils
|
|
import os
|
|
|
|
# Put the user's packages in the format too.
|
|
directory = utils.create_user_dir(user)
|
|
pkgs = ""
|
|
|
|
for f in os.listdir(directory):
|
|
if f.endswith(".sty"):
|
|
base = os.path.join(directory, f[:-4])
|
|
pkgs += "\\usepackage{{{base}}}\n ".format(base=base)
|
|
print(pkgs)
|
|
|
|
fmt = template.format(content=source, packages=pkgs)
|
|
|
|
tmp = tempfile.NamedTemporaryFile(delete=False)
|
|
tmp.write(bytes(fmt, encoding="utf8"))
|
|
tmp.close()
|
|
|
|
# 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:
|
|
subprocess.run(["dvipng", "-D", "5000", 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")
|