Skip to content

Instantly share code, notes, and snippets.

@j9ac9k
Created October 21, 2017 03:12
Show Gist options
  • Save j9ac9k/90ab6f6be3de34385e4ed16ca85f2b82 to your computer and use it in GitHub Desktop.
Save j9ac9k/90ab6f6be3de34385e4ed16ca85f2b82 to your computer and use it in GitHub Desktop.
tikz pandoc-filter
#!/usr/bin/env python
"""
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{standalone}
\\usepackage{tikz}
\\usetikzlibrary{arrows,automata}
\\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 == 'CodeBlock':
[[ident, classes, keyvals], code] = value
if "latex" in classes and "\\begin{tikzpicture}" in 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