|
| 1 | +""" |
| 2 | +Render equation block as a png |
| 3 | +""" |
| 4 | + |
| 5 | +import subprocess |
| 6 | +import tempfile |
| 7 | +from pathlib import Path |
| 8 | + |
| 9 | +import pdf2image |
| 10 | + |
| 11 | + |
| 12 | +def get_eqn(path="docs/lpl.md") -> str: |
| 13 | + """Collect the first back-ticked math block from `path`""" |
| 14 | + lines = [] |
| 15 | + in_eq = False |
| 16 | + with open(path) as f: |
| 17 | + for line in f: |
| 18 | + line = line.strip() |
| 19 | + if not in_eq and line == "```math": |
| 20 | + in_eq = True |
| 21 | + elif in_eq and line == "```": |
| 22 | + in_eq = False |
| 23 | + break |
| 24 | + elif in_eq: |
| 25 | + lines.append(line) |
| 26 | + else: |
| 27 | + pass |
| 28 | + |
| 29 | + return "\n".join(lines) |
| 30 | + |
| 31 | + |
| 32 | +def latex_to_png(latex_str: str, out_path: str, dpi: int = 400, verbose: bool = False): |
| 33 | + """Render `latex_str` using pdflatex""" |
| 34 | + content = ( |
| 35 | + r""" |
| 36 | +\documentclass[preview,border=2pt]{standalone} |
| 37 | +\usepackage{amsmath,amssymb} |
| 38 | +\begin{document} |
| 39 | +%s |
| 40 | +\end{document} |
| 41 | +""" |
| 42 | + % latex_str |
| 43 | + ) |
| 44 | + |
| 45 | + with tempfile.TemporaryDirectory() as td: |
| 46 | + path = Path(td) / "eq.tex" |
| 47 | + path.write_text(content) |
| 48 | + result = subprocess.run( |
| 49 | + [ |
| 50 | + "pdflatex", |
| 51 | + "-interaction=nonstopmode", |
| 52 | + "-output-directory", |
| 53 | + td, |
| 54 | + str(path), |
| 55 | + ], |
| 56 | + capture_output=True, |
| 57 | + ) |
| 58 | + |
| 59 | + if verbose: |
| 60 | + print(result.stdout.decode("utf-8")) |
| 61 | + print(result.stderr.decode("utf-8")) |
| 62 | + |
| 63 | + pages = pdf2image.convert_from_path(str(Path(td) / "eq.pdf"), dpi=dpi) |
| 64 | + |
| 65 | + pages[0].save(out_path, "PNG") |
| 66 | + |
| 67 | + |
| 68 | +if __name__ == "__main__": |
| 69 | + eqn = get_eqn() |
| 70 | + print(eqn) |
| 71 | + latex_to_png(eqn, "tmp_eqn.png", verbose=False) |
0 commit comments