Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering XML from draw.io as an image using mxCellRenderer

I am trying to programmatically read in an XML file generated by draw.io, an online flowchart/diagram creation service. Draw.io is built using mxGraph at its core, which has recently been externally named jgraphx (thus the tag on this post), though the class names have remained the same.

This StackOverflow post shows how to read in the raw XML data from the file and convert it to an mxGraph object, and this page of the mxGraph Javadocs describes how to convert from the mxGraph object to a renderable image.

Unfortunately for me, however, despite following both guides, the image that is "rendered" is always null and an IllegalArgumentException is thrown (because the image is null). My code is as follows:

String xmlFile = "work/test.xml";
String imageFile = "work/test.png";
mxGraph graph = new mxGraph();

try {
    Document doc = mxXmlUtils.parseXml(mxUtils.readFile(xmlFile));
    mxCodec codec = new mxCodec(doc);
    codec.decode(doc.getDocumentElement(), graph.getModel());
} catch (IOException e) {
    e.printStackTrace();
}

RenderedImage image = mxCellRenderer.createBufferedImage(graph, null, 1, \\
    Color.WHITE, false, null);

try {
    ImageIO.write(image, "png", new File(imageFile));
} catch (IOException e) {
    e.printStackTrace();
}

As you can see, this code should read in the XML data, create an mxGraph object from that data, then render the mxGraph object as an image in the current working directory. Instead, however, nothing happens and no image is created.

Has anyone ever experienced something like this? Am I overlooking something? Is there a better way to do what I'm trying to do? Any help would be appreciated.

FYI, here is a Pastebin with a sample XML file in case you want to try it for yourself.

like image 410
Jamison Bryant Avatar asked Feb 08 '16 16:02

Jamison Bryant


1 Answers

With some help from the draw.io support guys, I found the answer: the XML is obfuscated, yes, but not irretrievably so. It is simply compressed and needs to be decompressed. To do so:

  1. Base64 decode
  2. Inflate
  3. URL decode

I found this link which does all 3 of the above steps in one fell swoop: https://jgraph.github.io/drawio-tools/tools/convert.html.

Once I had the decompressed XML my code ran perfectly and generated the expected output.

See example implementation here: https://github.com/laingsimon/render-diagram/blob/master/drawio-renderer/src/main/java/com/simonlaing/drawiorenderer/models/DiagramDecoder.java

like image 51
Jamison Bryant Avatar answered Oct 17 '22 20:10

Jamison Bryant