Skip to content

Instantly share code, notes, and snippets.

@codingtim
Created January 24, 2017 12:26
Show Gist options
  • Save codingtim/8bddbd23a3b6820cdd335654a430ba1e to your computer and use it in GitHub Desktop.
Save codingtim/8bddbd23a3b6820cdd335654a430ba1e to your computer and use it in GitHub Desktop.
import com.mxgraph.canvas.mxICanvas;
import com.mxgraph.canvas.mxSvgCanvas;
import com.mxgraph.io.mxCodec;
import com.mxgraph.util.mxCellRenderer;
import com.mxgraph.util.mxDomUtils;
import com.mxgraph.util.mxUtils;
import com.mxgraph.util.mxXmlUtils;
import com.mxgraph.view.mxGraph;
public class DrawIoConverter{
//https://github.com/jgraph/mxgraph/tree/master/java
//http://stackoverflow.com/questions/35274068/rendering-xml-from-draw-io-as-an-image-using-mxcellrenderer/35322632
private void convert(Path file, Path outputPath) {
getLog().info("Converting: " + file.toString() + " to " + outputPath.toString());
try {
Files.createDirectories(outputPath.getParent());
mxGraph graph = new mxGraph();
Element node = DocumentBuilderFactory
.newInstance()
.newDocumentBuilder()
.parse(new ByteArrayInputStream(Files.readAllBytes(file)))
.getDocumentElement();
String diagramEncoded = node.getElementsByTagName("diagram").item(0).getTextContent();
byte[] bytes = DatatypeConverter.parseBase64Binary(diagramEncoded);
Inflater decompresser = new Inflater(true);
decompresser.setInput(bytes);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
while (!decompresser.finished()) {
int count = decompresser.inflate(buffer);
outputStream.write(buffer, 0, count);
}
outputStream.close();
decompresser.end();
String decoded = URLDecoder.decode(outputStream.toString(), "UTF-8");
// Parses XML into graph
Document doc = mxXmlUtils.parseXml(decoded);
mxCodec codec = new mxCodec(doc);
codec.decode(doc.getDocumentElement(), graph.getModel());
// Renders graph to SVG
mxSvgCanvas canvas = (mxSvgCanvas) mxCellRenderer.drawCells(graph,
null, 1, null, new mxCellRenderer.CanvasFactory() {
public mxICanvas createCanvas(int width, int height) {
return new mxSvgCanvas(mxDomUtils
.createSvgDocument(width, height));
}
});
mxUtils.writeFile(mxXmlUtils.getXml(canvas.getDocument()), outputPath.toString());
} catch (IOException | DataFormatException | SAXException | ParserConfigurationException e) {
getLog().error("Error converting xml to svg; file: " + file.toString() + " ; error: " + e.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment