Convert automatically pgf/tikz files to png

1 minute read

Published:

When writing my dissertation, I tried to generate my figures in the most coherent way possible. I used a matplotlib stylesheet, and exported all my figures to pgf (TikZ is built on top of pgf, as LaTeX is built on top of TeX). For simple figures, everything was fine: vectorized figures, nice integration with LaTeX. However, for more complicated figures, such as contourf or geographical maps, the pgf files became very large (more than 5Mb). Instead of regenerating those files from the code (which maybe I should have done in the first place), I wrote this bash script in order to convert chosen figures in png, with enough dpi (Dots Per Inche). This create a .tex file, with only the figure. Once compiled, the output is converted using imagick and its convert command. Finally, we remove the auxiliary files created in the process. There probably exists better ways to do this.

Put this in a file named convert_pgf_to_png for instance:

#!/usr/bin/bash

filename=${1%.pgf}

# Create the .tex file
echo $filename
echo "\documentclass[preview,border=4mm]{standalone}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{amsmath}
\usepackage{url}
\usepackage{tikz}
\usepackage{color}
\usepackage{xcolor}
\begin{document}" > tmp.tex
echo "\input{"$1"}" >> tmp.tex
echo "\end{document}" >> tmp.tex

# Compile the .tex
pdflatex tmp.tex > cvert.log

# Convert using imagick
convert -density 500 -units pixelsperinch tmp.pdf $filename.png
# Do some housekeeping
rm -f tmp.tex tmp.aux tmp.pdf tmp.log tmp.fls tmp.fdb_latexmk tmp.ps tmp.dvi

Use chmod +x convert_pgf_to_png to be able to execute it, and you can then call it

./convert_pgf_to_png filename

where filename is the name of the pgf figure you want to convert (without the extension). This is based on a stackoverflow answer I found somewhere.