By
Clemens Lode
,
December 23, 2024
pexels mikhail nilov 7534101 woman looking at a computer with green text

Converting TikZ Diagrams to PNG Files in Overleaf

When working with LaTeX documents in Overleaf, you might create multiple TikZ diagrams that you also want to use elsewhere - perhaps in presentations, blog posts, or documentation. While these diagrams are embedded as PDFs in your LaTeX document, you might need them as PNG files for web use.

The Challenge

Typically, each TikZ diagram lives in its own .tex file containing just the tikzpicture environment, without a complete LaTeX document structure. For example:

\begin{tikzpicture}
   \node[draw] (A) {Concept A};
   \node[draw, right=of A] (B) {Concept B};
   \draw[->] (A) -- (B);
\end{tikzpicture}

To convert this to a PNG, we need to:

  1. Wrap it in a complete LaTeX document
  2. Compile it to PDF
  3. Convert the PDF to PNG
  4. Do this for all diagrams in a directory

The Solution

We can automate this process using Overleaf's latexmkrc file. Our solution consists of two parts:

1. The Wrapper Template

First, we create a wrapper-header.tex file in our tex-images directory that contains everything up to where the TikZ diagram should be inserted:

\documentclass[border=10pt]{standalone}
\usepackage{tikz}
% Add your custom TikZ settings and libraries here
\begin{document}

2. The Automation Script

In our latexmkrc file, we add a Perl script that:

  • Reads all .tex files in the tex-images directory
  • Wraps each TikZ diagram in a complete LaTeX document
  • Compiles them to PDF
  • Converts them to PNG
  • Creates a zip file containing all PNGs

Here's the script with explanations:

# Open the directory containing our TikZ files
opendir(DIR, "./tex-images") or die "Cannot open directory: $!";

# Read our wrapper template once
open(my $header, "<", "./tex-images/wrapper-header.tex") or die "Can't open wrapper: $!";
my $header_content = do { local $/; <$header> };
close($header);

# Initialize array for tracking PNG files
my @png_files = ();

# Process each .tex file
while (my $file = readdir(DIR)) {
   
# Skip special directories and non-tex files
   next if ($file =~ /^\.{1,2}$/);
   next unless ($file =~ /\.tex$/);
   next if ($file eq 'wrapper-header.tex');
   
   
# Get base filename without .tex extension
   my $basename = $file;
   $basename =~ s/\.tex$//;
   
   
# Read the TikZ content
   open(my $in, "<", "./tex-images/$file") or die "Can't open $file: $!";
   my $tikz_content = do { local $/; <$in> };
   close($in);
   
   
# Create complete LaTeX document
   open(my $out, ">", "./tex-images/$basename.wrapped.tex") or die "Can't create wrapped file: $!";
   print $out $header_content;
   print $out $tikz_content;
   print $out "\n\\end{document}\n";
   close($out);
   
   
# Compile to PDF
   system "pdflatex -interaction=nonstopmode -shell-escape -output-directory=./tex-images ./tex-images/$basename.wrapped.tex";
   
   
# Convert to PNG (300 DPI)
   system "convert -density 300 ./tex-images/$basename.wrapped.pdf ./tex-images/$basename.png";
   
   push @png_files, "./tex-images/$basename.png";
}

closedir(DIR);

# Create final zip file containing all PNGs
if (@png_files) {
   my $png_list = join(" ", @png_files);
   system "zip -j tikz-exports.zip $png_list";
}

How It Works

Let's break down each step:

  1. File Organization: All your TikZ diagrams should be in a directory named tex-images, along with the wrapper-header.tex file.
  2. Reading Files: The script reads each .tex file in the directory, skipping the wrapper template and any non-tex files.
  3. Creating Complete Documents: For each TikZ file, it:
    • Takes the content from wrapper-header.tex
    • Adds the TikZ diagram code
    • Adds the \end{document} command
    • Saves this as a new .wrapped.tex file
  4. Compilation: Uses pdflatex to compile each wrapped file into a PDF, with all output files staying in the tex-images directory.
  5. Conversion: Uses ImageMagick's convert command to create high-resolution (300 DPI) PNGs from each PDF.
  6. Packaging: Creates a zip file containing all the generated PNGs, which you can then download from Overleaf.

Usage

To use this system:

  1. Create a tex-images directory in your Overleaf project
  2. Add the wrapper-header.tex file with your desired preamble
  3. Place all your TikZ diagrams in separate .tex files in this directory
  4. Add the script to your latexmkrc file
  5. Run a full compilation
  6. Download the resulting tikz-exports.zip file

The PNGs will be high-quality and ready for web use, presentations, or documentation.

Related Books and Services

No items found.
No items found.

Recommended Further Reading

December 23, 2024

About the Author

Clemens Lode

Hello! My name is Clemens and I am based in Düsseldorf, Germany. I’m an author of books on philosophy, science, and project management, and coach people to publish their books and improve their approach to leadership.

I like visiting the gym, learning to sing, observing animals, and creating videos on science and philosophy. I enjoy learning from nature and love the idea of optimizing systems.

In my youth, I was an active chess player reaching the national championship in Germany, and an active pen&paper player leading groups of adventurers on mental journeys. These activities align with my calm approach to moderating meetings, leading meetups, and focusing on details. My personality type in socionics is IEE/ENFp.

Read more...
Clemens Lode

Related Blog Posts

Related Topics

LaTeX

LaTeX

LaTeX, a document processing system, creates a typeset finished product. The system works more like a compiler than a word processor. While initially complicated to learn, LaTeX allows better management of larger projects like theses or books by splitting the document into text, style, and references. Leslie Lamport created laTeX in the 1980s; his goal was to separate content from styling.

Read more...
Book Publishing

Book Publishing

Book publishing has evolved with POD (print-on-demand) services. While it's never too late to write the next great novel or an award-winning nonfiction book, many people see book publishing as a marketing tool. No matter what your approach to your book, the challenge is finding and writing for the right audience.

Read more...

Do you have a question about our services?

Reach out, we'd love to hear from you! Schedule a video chat or message us by e-mail or WhatsApp!

Send us an e-mail (mail@lode.de), we will reply as soon as possible!

Reach out to us via a chat on WhatsApp!

Let's talk! Set up a free call with Clemens. Use Calendly to schedule the call.

Or send us your question or comment here and we'll get back to you ASAP:

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Rate us at Trustpilot