Using Graphviz with SVG Output in PHP
Since adding the functionality to process syntax highlighting through Pygments I had been on the look out for similar external tools I could integrate. One area that I felt was lacking in my posts was accompanying visual aids, which would be useful when explaining a new concept or algorithm. Like most developers I feel at home in an editor, so delving into another software package did not appeal to me. It was highly desirable to maintain my current work-flow and store all content related to a post (unless necessary) within the single markdown file. Graphviz was the tool for job, enabling graphs to be described using a small DSL and results outputted in a variety of formats. Along with the ability to describe graphs in plain-text, the option to output results in SVG allowed me keep post dependencies down to a minimum. SVG (Scalable Vector Graphics) is an XML-based vector image format, providing lossless-scaling and small file sizes. This allowed me to embedded outputted graphs within the rendered post, similar in process to syntax highlighting with Pygments.
Below is a simple example implementation to output SVG variants of each defined graph within a supplied string (post). I made the assumption that the ‘dot’ command (provided by Graphviz) is present in the user’s path (this can be easily altered). For consistency I decided to declare graph definitions using Markdown Extra’s fenced blocks notation, discussed further in the Pygments post. Providing the code block with a unique ‘.dot-show’ language type-hint allowed me to be sure of no conflicting pre-processes.
Looking at the example above you will notice the use of the same regular expression replacement and process command calls found in the Pygments implementation. All that has been altered is the processing occurred on the outputted result and of course the command itself. Comments and unnecessary headers are removed from the resulting output, along with the inclusion of random ‘id’ element names (as multiple graphs may use the same names). The ‘max-height’ style replaces the defined width and height of the SVG element to fix an issue I found in maintaining height ratio when resizing the graph.
Now that we have an example implementation to work with, lets see some of the impressive results we can achieve when using Graphviz and SVG output.
UML Class Diagram
Inspired by the great article found here, I was able to describe a simple UML Class Diagram in .dot notation and output the results in SVG.
Huffman Coding Tree
Using this generator I was able to visually represent the Huffman Tree for a given string.