Generate UML Sequence Diagrams from Text with PlantUML

Page content

Setup

I recently needed to draw a UML sequence diagram. That’s usually something I’d do in Microsoft’s Visio ™. I was aware of text-to-chart utilities such as Medusa so I assumed that similar tools would be available for generating sequence diagrams. A quick search of the web yielded an open source tool called PlantUML. PlantUML is a set of tools for converting text scripts to various kinds of UML diagrams. To use the bare-bones setup for PlantUML, you’ll need a Java Virtual Machine (JVM). You’ll then need to download the jar file containing the base PlantUML runtime classes. You can download the jar and the reference guide from this URL:

https://plantuml.com/download

At the time of this writing, the filename is plantuml-1.2023.10.jar. This will change as new versions are released. In order to follow along, please rename the jar file to plantuml.jar.

To invoke the software with a help screen, you can issue the following command:

java -jar plantuml.jar -help

Which should yield a stream of help text that looks something like this:

Usage: java -jar plantuml.jar [options] -gui
        (to execute the GUI)
    or java -jar plantuml.jar [options] [file/dir] [file/dir] [file/dir]
        (to process files or directories)

You can use the following wildcards in files/dirs:
        *       means any characters but '\'
        ?       one and only one character but '\'
        **      means any characters (used to recurse through directories)

where options include:
    -darkmode           To use dark mode for diagrams
    -gui                To run the graphical user interface
    -tpng               To generate images using PNG format (default)
    -tsvg               To generate images using SVG format
    -teps               To generate images using EPS format
    -tpdf               To generate images using PDF format
    -tvdx               To generate images using VDX format
    -txmi               To generate XMI file for class diagram
    -tscxml             To generate SCXML file for state diagram
    -thtml              To generate HTML file for class diagram
    -ttxt               To generate images with ASCII art
    -tutxt              To generate images with ASCII art using Unicode characters
    -tlatex             To generate images using LaTeX/Tikz format
    -tlatex:nopreamble  To generate images using LaTeX/Tikz format without preamble
    -o[utput] "dir"     To generate images in the specified directory
    -DVAR1=value        To set a preprocessing variable as if '!define VAR1 value' were used
    -Sparam1=value      To set a skin parameter as if 'skinparam param1 value' were used
    -Ppragma1=value     To set pragma as if '!pragma pragma1 value' were used
    -I\path\to\file     To include file as if '!include file' were used
    -I\path\to\*.puml   To include files with pattern
    -theme xxx          To use a specific theme
    -charset xxx        To use a specific charset (default is windows-1252)
    -e[x]clude pattern  To exclude files that match the provided pattern
    -metadata           To retrieve PlantUML sources from PNG images
    -nometadata         To NOT export metadata in PNG/SVG generated files
    -checkmetadata              Skip PNG files that don't need to be regenerated
    -version            To display information about PlantUML and Java versions
    -v[erbose]          To have log information
    -quiet              To NOT print error message into the console
    -debugsvek          To generate intermediate svek files
    -h[elp]             To display this help message
    -testdot            To test the installation of graphviz
    -graphvizdot "exe"  To specify dot executable
    -p[ipe]             To use stdin for PlantUML source and stdout for PNG/SVG/EPS generation
    -encodesprite 4|8|16[z] "file"      To encode a sprite at gray level (z for compression) from an image
    -computeurl|-encodeurl      To compute the encoded URL of a PlantUML source file
    -decodeurl          To retrieve the PlantUML source from an encoded URL
    -syntax             To report any syntax error from standard input without generating images
    -language           To print the list of PlantUML keywords
    -checkonly          To check the syntax of files without generating images
    -failfast           To stop processing as soon as a syntax error in diagram occurs
    -failfast2          To do a first syntax check before processing files, to fail even faster
    -noerror            To skip images when error in diagrams
    -duration           To print the duration of complete diagrams processing
    -nbthread N         To use (N) threads for processing
    -nbthread auto      To use 8 threads for processing
    -timeout N          Processing timeout in (N) seconds. Defaults to 15 minutes (900 seconds).
    -author[s]          To print information about PlantUML authors
    -overwrite          To allow to overwrite read only files
    -printfonts         To print fonts available on your system
    -enablestats        To enable statistics computation
    -disablestats       To disable statistics computation (default)
    -htmlstats          To output general statistics in file plantuml-stats.html
    -xmlstats           To output general statistics in file plantuml-stats.xml
    -realtimestats      To generate statistics on the fly rather than at the end
    -loopstats          To continuously print statistics about usage
    -splash             To display a splash screen with some progress bar
    -progress           To display a textual progress bar in console
    -pipeimageindex N   To generate the Nth image with pipe option
    -stdlib             To print standard library info
    -extractstdlib      To extract PlantUML Standard Library into stdlib folder
    -filedir xxx        To behave as if the PlantUML source is in this dir (only affects '-pipe' and PicoWeb 'POST /render')
    -filename "example.puml"    To override %filename% variable
    -preproc            To output preprocessor text of diagrams
    -cypher             To cypher texts of diagrams so that you can share them
    -picoweb            To start internal HTTP Server. See https://plantuml.com/picoweb

If needed, you can setup the environment variable GRAPHVIZ_DOT.

If the -help parameter is omitted, you’ll likely end up seeing the GUI interface to PlantUML. We’ll work with the GUI in just a little while. For now, let’s stick with the command-line version.

Some First Examples

Now, let’s edit a simple PlantUML source script.

example1.puml

@startuml
Browser -> Web Server: Request a document
Web Server --> Bob: Respond with document
@enduml

To generate output, run the following command:

java -jar plantuml.jar example1.puml

PlantUML will then yield a PNG file by default. It bases the output filename on the primary portion of the input filename. This new file will be called example1.png:

The initial syntax is pretty simple. PlantUML can generate a variety of UML documents including sequence diagrams. PlantUML bases the decision on what to generate on the context of statements / directives in the script. We won’t be covering the other types of diagrams that it can generate in this article.

Let’s dress up the example a bit with a title. Let’s also remove those footer boxes.

example2.puml

@startuml
hide footbox
title "A Simple Example\nA Basic HTTP Request"
Browser -> "Web Server": Request a document
"Web Server" --> Browser: Respond with document
@enduml

Render the PNG file example2.png with the command:

java -jar plantuml.jar example2.puml

Note that a multiline title is now present and the footer boxes have been removed.

The directive hide footbox removes the footer boxes from the drawing.

Quoted strings in PlantUML’s script format permit slash-based escape sequences akin to those used in C/Java/JavaScript et al. Using a “slash-n” in the title directive causes the title to be broken up into two lines, centered by default.

Output Formats

The command-line options for controlling the output file format all use the pattern -t{format-name} :

    -tpng               To generate images using PNG format (default) 
    -tsvg               To generate images using SVG format
    -teps               To generate images using EPS format
    -tpdf               To generate images using PDF format
    -tvdx               To generate images using VDX format
    -txmi               To generate XMI file for class diagram
    -tscxml             To generate SCXML file for state diagram
    -thtml              To generate HTML file for class diagram
    -ttxt               To generate images with ASCII art
    -tutxt              To generate images with ASCII art using Unicode characters
    -tlatex             To generate images using LaTeX/Tikz format
    -tlatex:nopreamble  To generate images using LaTeX/Tikz format without preamble

We’ve been letting the output format default to png. Let’s try generating text output.

java -jar plantuml.jar -ttxt example2.puml

The output file has .atxt as the extention. Here’s example2.atxt :

           A Simple Example           
           A Basic HTTP Request       
                                      
     ,-------.            ,----------.
     |Browser|            |Web Server|
     `---+---'            `----+-----'
         | Request a document  |      
         |--------------------->      
         |                     |      
         |Respond with document|      
         |<- - - - - - - - - - -      
         |                     |      
         |                     |      

I have not tried most of the other formats. I did try the -tpdf which seems to require the package org.apache.batik.apps.rasterizer.SVGConverter. I don’t have that in the classpath, so I can’t generate PDF’s directly. We can work around that if there’s some reason that you can’t use the SVGConverter package.

By using -tsvg we can generate a version of the file in Scalable Vector Graphics format.

java -jar plantuml.jar -tsvg example2.puml

The generated file looks like this :

It probably doesn’t look too much different than the png file.

SVG files lend themselves to visual scaling, as their name implies. If you place the two images above into view and zoom in on the images either by stretching the image or by hitting CTRL+, you’ll note that the PNG file starts to become blurry. The SVG format file redraws most portions of itself on the fly giving us a consistently crisp image when we alter the scale of the view.

Embedding Images in Documents

While we weren’t successful in generating PDF files in the out-of-the-box distribution of PlantUML, we can use a word processor such as Microsoft Word™ with embedded SVG graphics. Note that we could use PNG files in the Word document, but the SVG images retain their clarity when resizing the images to fit inside the document.

From Word we can then print the output to a PDF file.

The Graphical User Interface

You can initiate the PlantUML GUI using one of these command-lines :

java -jar plantuml.jar

or

java -jar plantuml.jar -gui

You should see a window that looks something like this:

Double-clicking on the second line for example2, should open a new window:

Open example2.puml and change the title directive to read title “A Very Simple Example\nA Basic HTTP Request” ( adding the word “Very” before the word “Simple” ). Once you save the file, PlantUML will automatically regenerate the output file ( PNG, in this case ) and it will re-render it in real-time:

Working with the document in this fashion lends itself to group development of a diagram. One person can act as the scribe to modify the puml source while others watch through video-conferencing applications.

Embedded Usage

A number of automation tools such as those used for source code building CI/CD pipelines generate puml output.

Source control systems such as Gitlab can be configured to render puml document directly with some text extensions in the AsciiDoc, Markdown, or reStructuredText documents. Please refer to this document for more information:

https://docs.gitlab.com/ee/administration/integration/plantuml.html

What’s Next?

This document and examples provided are intended to be used as a sort of quick-start for using PlantUML. The formal documentation provides much more coverage of the syntax and other useful directives. The online version of the documentation for sequence diagrams is here :

https://plantuml.com/sequence-diagram

An interactive forum is also available for discussing PlantUML :

https://forum.plantuml.net/

Have fun!