TikZ Web Export (pdf to png or svg)

Tags: Tikz , LaTeX , converting png to pdf

(Español: Exportar figuras de TikZ para la web (de pdf a png o svg))

TikZ is, in very concise terms, a programing language to generate images based on LaTeX. One runs PdfLateX on a TikZ source file (a plain text file) and gets as output a beautiful looking pdf.

For a detailed example, you can see this post in which I show the TikZ code of the following image, or this other post in which I go into even more details of the TikZ syntax to create the plot of a function with mathematics LaTeX labels.

TikZ figure generated from this .tex file. This is the original pdf output.

TikZ figure generated from this .tex file. This is the original pdf output.

TikZ plays an important role in this blog because I enjoy both explaining things graphically and the actual process of creating the TikZ code for images. Once I dedicate the time to generate a good TikZ figure with well thought out code, I can often reuse the code with minor tweaks to very easily generate many more images to further illustrate the ideas I am trying to convey. TikZ becomes a very efficient high quality tool when this happens. This is part of the benefit of “coding” an image instead of creating it with graphical software.

One of the key things I had to figure out to be able to use TikZ for this blog was a way to change the vector graphic pdf files it generates into more web-friendly formats, since webpages do not support pdf images. There are two possible paths one can take:

  • Create a bitmap ( raster) high quality version. A good format widely supported format for this right now is png.
  • Transform into a web-friendly vector graphic format. The current way to go for the web is svg.

The key things one wants from these conversions are:

  1. Maintain high quality (no noticeable pixelation).
  2. Maintain small file sizes to not have long-loading sluggish blog posts.

The raster pngs are often more useful than the vector graphics svg because, unlike svgs, one can use them in different contexts easily like:

  • including in emails.
  • importing into LibreOffice, google documents, word files.
  • sharing in Slack.

The downside of raster images is that (1) and (2) above are conflicting conditions, and one needs to find the right compromises to get a bit of both.

I found several websites claiming that (1) and (2) cannot be accomplished together in a conversion from pdf to png, and after several failed experiments I was starting to believe them. But I finally came up with a workflow that lets me have my cake and eat it too.

In this blog post I explain how I do these conversions.

First, a note about about raster vs vector graphics formats

The difference between raster and vector images is summed up in the following figure.

Demonstration of differences between bitmap and SVG images. Image by Yug, modifications by Cfaerber et al. from Wikipedia. CC-BY 2.5 license.

Demonstration of differences between bitmap and SVG images. Image by Yug, modifications by Cfaerber et al. from Wikipedia. CC-BY 2.5 license.

Bitmap (raster) images are images built out of pixels, each one of a specific color. The more pixels the image has, the higher quality it has, but the larger the file size.

For example, my MacBook saves screenshots using the bitmap (raster) format png: this file specifies the color of every single pixel the screen was showing. Since my MacBook has a high resolution screen, these screenshots are usually unnecessarily big (in filesize).

Vector images are different in that they have “pen stroke instructions” in some internal code. This has two main advantages when the images are schematic-diagram-like (not photography-like):

  • filesizes can be very small (since describing the “pen strokes” to generate a diagram is usually much more efficient than saying whether a pixel should be colored or not.
  • infinitely scalable with no quality reduction: images can be zoomed in forever without pixels ever appearing (no pixelation occurs).

An example showing the benefits of TikZ vector graphic pdf output

This a figure I made with TikZ is from this post

If I open the pdf, I can keep zooming in, and it always looks super sharp! Here is the portion on the top left

and even closer! Super sharp.

Compare this to what you see when you zoom into the same image when it is in png format:

How I do the conversions: from pdf TikZ output to png

Here is the conversion to png method I have settled upon. It uses the MacOS terminal and ImageMagick.

Prerequisites: Install ImageMagick

  • Install the fantastic Homebrew if you don’t have it already (from the terminal.app). Instructions at their website.
  • Install the also fantastic ImageMagick from the terminal using Homebrew by executing the command:
    brew install imagemagick
    

If steps above work well, then typing the following command in the terminal should provide relevant information (mentioning ImageMagick and its version) instead of an error message:

convert --version

Conversion from pdf to png using Imagemagick

  • Navigate inside the terminal to the folder that contains the pdf file (say filename.pdf) that was created by TikZ.
  • Execute the following command in the terminal:
    convert -density 600 filename.pdf filename.png
    

That is it! You should now have a the png image filename.png in the same folder, with both a very high resolution (the -density 600 part of the command specifies that the png should have a resolution of 600pixels/inch) and a reasonably small filesize (about half as big as the Preview.app export).

Further tweaks - background color

The png exports using ImageMagick have by default transparent background. If you want your image to have a specific background color, then adding -background white -flatten to the command will make the background white. Like this:

convert -density 600 -background white -flatten filename.pdf filename.png

Further tweaks …

ImageMagick has tons of options and capabilities. Try some internet searches about the options, or type the following command directly in the terminal:

convert --help

Note: using native MacOS tools

The Preview.app in MacOS can export any pdf into png format in any resolution (file > Export..., select png as output format). The downside is that exports somewhat big compared to the other method I described above, and it is hard to “automate”. Nonetheless, it may be easier for many people!

Conversion from pdf to svg

As I mention above, I decided to go with raster pngs because I could use them in different context besides websites. In any case, I did test several methods to get svgs out of the TikZ pdfs, and I did find a method to get an avg with similar file sizes to the very sharp 600 pixels/inch pngs.

TikZ –> pdf –> svg path

One can generate an svg directly from the pdf TikZ output by using David Barton’s pdf2svg ( source code).

Installing pdf2svg is a breeze with Homebrew (run command on the terminal):

brew install pdf2svg

Once installed, conversion is accomplished by using:

pdf2svg input_filename.pdf output_filename.svg

The pdf2svg does not seem to have many options (see pdf2svg --help).

TikZ –> dvi –> svg path

This is an alternate path that I did not get to work. It uses dvisvgm. I do not know if it is better than the other svg option I described above. My MacOS was complaining about PostScript specials. Good places to start troubleshoting issues for anyone interested may be here and here.

Complete Example

This is an image I used in this post in which using TikZ saved me hours of work because I could generate plots for different time periods by just changing one number in the TikZ code.

Here are the file sizes of several export formats. I include the exported images below too.

Format File size
TikZ source file (tiny!) 3kb
pdf vector TikZ output 42kb
svg output using pdf2svg 128kb
png output using ImageMagick at 600pixels/inch 156kb
png output using MacOS Preview.app at 600pixels/inch 309kb

In my high resolution screen, I can barely notice any differences between each version. See below.

svg version using pdf2svg:

png version using ImageMagick:

png version using Preview.app:

Summary

If you want to generate a relatively small size high resolution png for a TikZ image, just make sure you have ImageMagick installed, and in the terminal run

convert -density 600 filename.pdf filename.png

or (if you want a white background instead of transparent one)

convert -density 600 -background white -flatten filename.pdf filename.png

Subscribe

Want to get an email when a new post is added? If so, subscribe here.