In order to save your graph you have to call mxCellRendered to render your graph to a mxicanvas from which you get your Document (dom document).
From the Renderer it goes like this:
mxGraph.drawCell() -> mxGraph.drawState() -> mxICanvas.drawCell() -> mxICanvas.drawShape()
mxICanvas knows only the cell's geometry and style.
I wanted the cell id attribute added in the svg file as well, so I did the following
- extended the mxGraph to override the drawCell() in order to add the cell id in the style of the cell, and
- extended the mxSvgCanvas for adding the id attribute for the shapes that interested me
The function to save as svg graph goes like:
// use the extended svg canvas, where the cell id is added as attribute
public void createSVG(mxGraphExtended g) {
String filename = "\home\koula\graph.svg";
mxSvgCanvasExtended canvas = (mxSvgCanvasExtended) mxCellRenderer.drawCells(
g, null, 1, null, new CanvasFactory() {
public mxICanvas createCanvas(int width, int height) {
mxSvgCanvasExtended canvas = new mxSvgCanvasExtended(mxDomUtils
.createSvgDocument(width, height));
canvas.setEmbedded(true);
return canvas;
}
});
try {
mxUtils.writeFile(mxXmlUtils.getXml(canvas.getDocument()), filename);
} catch (IOException e) {
e.printStackTrace();
}
}
The overriden drawCell():
public class mxGraphExtended extends mxGraph {
@Override
public void drawCell(mxICanvas canvas, Object cell) {
// add the cell's id as a style attribute
// cause canvas only get the style and geometry
mxCellState state = this.getView().getState(cell);
state.getStyle().put("cellid", ((mxCell)cell).getId());
super.drawCell(canvas, cell);
}
}
The overridden drawShape() goes like:
public class mxSvgCanvasExtended extends mxSvgCanvas {
//... have coppied only the related code
@Override
public Element drawShape(int x, int y, int w, int h,
Map<String, Object> style)
{
//...
// Draws the shape
String shape = mxUtils.getString(style, mxConstants.STYLE_SHAPE, "");
String cellid = mxUtils.getString(style, "cellid", "");
Element elem = null;
// ...
// e.g. if image, add the cell id
if (shape.equals(mxConstants.SHAPE_IMAGE)) {
String img = getImageForStyle(style);
if (img != null) {
// Vertical and horizontal image flipping
boolean flipH = mxUtils.isTrue(style,
mxConstants.STYLE_IMAGE_FLIPH, false);
boolean flipV = mxUtils.isTrue(style,
mxConstants.STYLE_IMAGE_FLIPV, false);
elem = createImageElement(x, y, w, h, img,
PRESERVE_IMAGE_ASPECT, flipH, flipV, isEmbedded());
/* so here we are */
// add the cell id atribute
if(!cellid.equals("")) {
elem.setAttribute("id", cellid);
}
}
} else if (shape.equals(mxConstants.SHAPE_LINE))
// ...
}// end drawShape
} // end class
Hope this help.