Skip to content

Instantly share code, notes, and snippets.

@jrandolf
Last active December 3, 2020 21:01
Show Gist options
  • Save jrandolf/66574eb201440f8a4e2db41550a3157a to your computer and use it in GitHub Desktop.
Save jrandolf/66574eb201440f8a4e2db41550a3157a to your computer and use it in GitHub Desktop.
A small shell script to convert LaTeX code to SVG
#!/usr/bin/env bash
#######################################################
### REQUIREMENTS ######################################
#######################################################
## XeLaTeX: Available through most TeX distributions ##
## dvisvgm: Available through most TeX distributions ##
## svgo (optional, but highly recommended) ##
#######################################################
### Usage #############################################
#######################################################
## The script is accessed purely through pipes. For ##
## example: cat somefile.tex | latex2svg > somefile.svg
## Errors handling is built in; it will show the ##
## standard `! LaTeX Error` as well as the line ##
## number through `stderr`. ##
#######################################################
declare -r temp_dir=$(mktemp -d -t tikz)
trap "rm -rf $temp_dir" EXIT
die() {
if [[ -e "$temp_dir/source.log" ]]; then
cat "$temp_dir/source.log" | grep "^! LaTeX Error\|^l\.\d" 1>&2
fi
exit 1
}
cd $temp_dir
echo "$(</dev/stdin)" >source.tex
xelatex -interaction=nonstopmode -no-pdf -no-shell-escape -halt-on-error -output-directory=$temp_dir source.tex 1>/dev/null 2>&1
if [[ ! -e source.xdv ]]; then
die
fi
if ! type svgo 1> /dev/null 2>&1; then
dvisvgm -v 0 -s source.xdv | cat
else
dvisvgm -v 0 -s source.xdv | svgo -i - -o - | cat
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment