Yesterday I was facing a problem of exporting JGraph graph to a SVG format image. Neither SVGGraphWriter, neither a solution presented in JGraph tutorial didn’t work.
Using SVGGraphWriter from JGraph I got all of my graph nodes and connections just dumped one on the other. JGraph manual (can be found here, page 97) proposes using Apache Batik and painting the graph using SVGGraphics2D provided by the library. The problem is that
JGraph graph = ... SVGGraphics2D graphics = ... ... graph.paint(graphics);
just doesn’t work. So I decided to explore JGraph source and see if there is any way I can make this work.
And voila few minutes and I found a solution:
OutputStreamWriter writer = ...; Object cells = graph.getRoots(); Rectangle2D bounds = graph.toScreen(graph.getCellBounds(cells));</code> DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); Document document = domImpl.createDocument(null, "svg", null); SVGGraphics2D svgGraphics = new SVGGraphics2D(document); svgGraphics.setSVGCanvasSize(new Dimension((int)Math.round(bounds.getWidth()), (int)Math.round(bounds.getHeight()))); RepaintManager repaintManager = RepaintManager.currentManager(graph); repaintManager.setDoubleBufferingEnabled(false); BasicGraphUI gui = (BasicGraphUI) graph.getUI(); // The magic is those two lines gui.drawGraph(svgGraphics, bounds); svgGraphics.stream(writer, false);