1
0
Fork 0
dotfiles/.local/bin/scripts/l2p
2026-01-06 07:36:53 +03:00

48 lines
1.2 KiB
Python
Executable file

#!/usr/bin/python3
from io import BytesIO
import os
import subprocess
import random
from string import ascii_letters
from subprocess import PIPE
import sys
from PIL import Image
LATEX_TEMPLATE = r'''
\documentclass{{minimal}}
\begin{{document}}
$$
{}
$$
\end{{document}}
'''
dpi = 1024
padding = 72
run = lambda args: subprocess.run(args, stdout=PIPE, stderr=PIPE)
filename = "".join(random.choices(ascii_letters, k=8))
tex_fn = filename + '.tex'
try:
with open(tex_fn, 'w') as f:
f.write(LATEX_TEMPLATE.format(' '.join(sys.argv[2:])))
ps = run(['latex', '-interaction=nonstopmode', tex_fn])
print(ps.stdout.decode(), ps.stderr.decode())
ps.check_returncode()
ps = run(['dvipng', '-q', '-T', 'tight', '-D', str(dpi), filename + '.dvi', '-o', filename + '.png'])
print(ps.stdout.decode(), ps.stderr.decode())
ps.check_returncode()
img = Image.open(filename + '.png')
new_img = Image.new('RGB', (img.width + padding * 2, img.height + padding * 2), (255, 255, 255))
new_img.paste(img, (padding, padding))
new_img.save(sys.argv[1] + ".png", 'png')
finally:
for fn in [f'{filename}.{ext}' for ext in ('aux', 'dvi', 'log', 'tex', 'png')] + ['texput.log']:
if os.path.isfile(fn):
os.remove(fn)