xmlgraphics-batik-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Fiebig, Sebastian" <Sebastian.Fie...@danet.de>
Subject Re: Add an id to elements providing meta information
Date Fri, 27 Mar 2009 08:23:06 GMT

Helder, thanks for your reply! Here is my full code:

// Get a DOMImplementation.
DOMImplementation domImpl =

// Create an instance of org.w3c.dom.Document.
String svgNS = "http://www.w3.org/2000/svg";
Document document = domImpl.createDocument(svgNS, "svg", null);

// Create an instance of the SVG Generator.
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

// Draw svg
svgGenerator.fill(new Rectangle(10, 10, 100, 100));

// Try getting last element to set id
Element root = document.getDocumentElement();
Node elem = svgGenerator.getRoot(root);
while (elem.getLastChild() != null) {
    elem = elem.getLastChild();
Element lastElement = (Element) elem;
lastElement.setAttribute("id", "1");

// Do the same with the next rectangle
svgGenerator.fill(new Rectangle(20, 20, 200, 200));

elem = svgGenerator.getRoot(root); 
while (elem.getLastChild() != null) {
    elem = elem.getLastChild();
lastElement = (Element)elem;
lastElement.setAttribute("id", "2");

// Finally, stream out SVG to the standard output using
// UTF-8 encoding.
boolean useCSS = true; // we want to use CSS style attributes
Writer out = new FileWriter("test.svg");
// Next line prints garbage
svgGenerator.stream(out, useCSS);

// Get root of document for print out
Node parent = lastElement;

while(parent.getParentNode() != null) {

    parent = parent.getParentNode();


TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");

//create string from xml tree
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(parent);
trans.transform(source, result);
String xmlString = sw.toString();

// print xml
System.out.println("Here's the xml:\n\n" + xmlString);

It's nearly the same as the one from the batik documentation[1]. I try
to draw elements with SVGGraphics2D and right after each drawing
operation, I add an id. With your last code snippet it "works", but
propably not as intended, because commentaries of Batik are found once
for each element. And second the streaming method of SVGGraphics2D is
not working (before I used your snippet it didn't either) and I have to
manually get the root of my dom tree and print it. Must I not change the
dom tree while SVGGraphics2D is using it? 

Thanks in advance!


[1] http://xmlgraphics.apache.org/batik/using/svg-generator.html

View raw message