Skip to content

Instantly share code, notes, and snippets.

Last active November 30, 2022 04:34
  • Star 17 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
tikz2svg - convert tikz input into svg
#!/usr/bin/env python
# author:
# license: MIT
# tikz2svg: convert tikz input into svg
# depends on:
# - pdflatex: comes with your tex dist
# - pdf2svg: brew install pdf2svg
import os
import sys
import hashlib
import functools
from subprocess import Popen, PIPE
class cmds(object):
pdflatex = 'pdflatex --shell-escape -file-line-error -interaction=nonstopmode --'
pdf2svg = 'pdf2svg texput.pdf out.svg'
latex_doc ='''
\\tikzset{every picture/.style={scale=1}}
# util to run command in a subprocess, and communicate with it.
def run(cmd, stdin=None, exit_on_error=True):
# print '>', cmd
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
if stdin:
# error out if necessary
if p.returncode != 0 and exit_on_error:
print '>', cmd
print 'Error.'
print '-' * 20, 'STDIN'
print stdin
print '-' * 20, 'STDOUT'
print '-' * 20, 'STDERR'
# memoize with a file cache.
def memoize_in_file(fn):
def memoized(*args, **kwds):
i = fn.__name__ + str(*args) + str(**kwds)
h = hashlib.sha1(i).hexdigest()
if os.path.exists(h):
with open(h) as f:
out = fn(*args, **kwds)
with open(h, 'w') as f:
return out
return memoized
# conversion functions
def tikz2tex(tikz):
return latex_doc % {'content': tikz}
def tex2pdf(tex):
return run(cmds.pdflatex.split(' '), stdin=tex)
def pdf2svg(pdf):
with open('out.svg') as f:
def tikz2svg(tikz):
tex = tikz2tex(tikz)
pdf = tex2pdf(tex)
svg = pdf2svg(pdf)
return svg
# move to tmp because latex litters :(
def chdir(inp):
h = hashlib.sha1(inp).hexdigest()
d = '/tmp/%s' % h
run('mkdir -p %s' % d, exit_on_error=False)
if __name__ == '__main__':
if '-h' in sys.argv or '--help' in sys.argv:
print 'Usage: %s [<file>]' % sys.argv[0]
print 'Outputs svg conversion of tikz input (files or stdin).'
import fileinput
lines = ''.join([l for l in fileinput.input()])
print tikz2svg(lines)
Copy link

jbenet commented Apr 9, 2014

Fixed extra \n bug.

Copy link

jason-s commented Jan 9, 2017

your webpage link is broken

Copy link

bump on the webpage link

Copy link

mitar commented Jun 22, 2019

Lol about that fact that Juan's link is dead. IPFS FTW.

Copy link

jbenet commented Feb 19, 2022

I broke the blog dir structure -- fixed link:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment