Skip to content

Instantly share code, notes, and snippets.

@MultisampledNight
Created September 6, 2022 21:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MultisampledNight/36c2a73d00a390db20699033a80be5a5 to your computer and use it in GitHub Desktop.
Save MultisampledNight/36c2a73d00a390db20699033a80be5a5 to your computer and use it in GitHub Desktop.
LaTeX file path as command line argument to SVG on stdout in the worst possible version (impure)
#!/usr/bin/env python
# Takes a filename of a LaTeX file as argv[1] and prints the resulting svg on
# stdout. Impure, depends on pdflatex and pdf2svg, creates a temporary dir.
import re
import subprocess
import sys
import tempfile
from pathlib import Path
SEARCH_AND_REPLACE = [
# actually utilize all that width available instead of squishing everything together
('width=".*" height=".*" viewbox=".*"', 'width="100%"'),
# fix up the fill which is always either empty or black, for some reason
# this way the SVG actually responds to the mdbook theme
('fill=".*"', 'style="fill: var(--fg)"'),
]
def latex_to_svg(source: Path) -> str:
with tempfile.TemporaryDirectory() as tmpdir:
tmpdir = Path(tmpdir)
svg_file = tmpdir / "lol.svg"
# perform the actual compilation
mute_args = {
"stdin": subprocess.DEVNULL,
"stdout": subprocess.DEVNULL,
"stderr": subprocess.DEVNULL,
}
subprocess.run(
["pdflatex", f"-output-directory={tmpdir}", source.resolve()], **mute_args
)
subprocess.run(
["pdf2svg", (tmpdir / source.stem).with_suffix(".pdf"), svg_file],
**mute_args,
)
with open(svg_file) as fh:
content = fh.read()
for search, replace in SEARCH_AND_REPLACE:
content = re.sub(search, replace, content)
return content
def panic(message: str):
print(message, file=sys.stderr)
sys.exit(1)
def main(argv: list):
latex_source_path = (
Path(argv[1])
if argv[1:]
else panic("please give me one argument as path to a latex file")
)
svg_content = latex_to_svg(latex_source_path)
sys.stdout.write(svg_content)
sys.stdout.flush() # not sure if this has even any effect, tbh
if __name__ == "__main__":
main(sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment