Skip to content

Instantly share code, notes, and snippets.

@twsh twsh/figure.py
Last active Aug 1, 2019

Embed
What would you like to do?
Pandoc filter to turn figure environments into images based on https://github.com/jgm/pandocfilters/blob/master/examples/tikz.py
#!/usr/bin/env python3
"""
Pandoc filter to process raw latex tikz environments into images.
Assumes that pdflatex is in the path, and that the standalone
package is available. Also assumes that ImageMagick's convert
is in the path. Images are put in the tikz-images directory.
"""
import os
import re
import shutil
import sys
from subprocess import call
from tempfile import mkdtemp
from pandocfilters import toJSONFilter, Para, Image, get_filename4code, get_extension
def tikz2image(tikz_src, filetype, outfile):
tmpdir = mkdtemp()
olddir = os.getcwd()
os.chdir(tmpdir)
f = open('tikz.tex', 'w')
f.write("""\\documentclass[preview,tikz]{standalone}
\\usepackage{tikz-qtree}
\\usepackage{amsmath}
\\begin{document}
""")
f.write(tikz_src)
f.write("\n\\end{document}\n")
f.close()
call(["pdflatex", 'tikz.tex'], stdout=sys.stderr)
os.chdir(olddir)
if filetype == 'pdf':
shutil.copyfile(tmpdir + '/tikz.pdf', outfile + '.pdf')
else:
call(["convert", tmpdir + '/tikz.pdf', outfile + '.' + filetype])
shutil.rmtree(tmpdir)
def tikz(key, value, format, _):
if key == 'RawBlock':
[fmt, code] = value
if fmt == "latex" and re.match("\\\\begin{figure}", code):
outfile = get_filename4code("tikz", code)
filetype = get_extension(format, "png", html="png", latex="pdf")
src = outfile + '.' + filetype
if not os.path.isfile(src):
tikz2image(code, filetype, outfile)
sys.stderr.write('Created image ' + src + '\n')
return Para([Image(['', [], []], [], [src, ""])])
if __name__ == "__main__":
toJSONFilter(tikz)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.