Differences between revisions 5 and 6
Revision 5 as of 2012-06-22 14:00:17
Size: 1810
Editor: drool
Comment: fixed closing braces, so that the last code block is visible
Revision 6 as of 2012-06-22 14:06:47
Size: 1831
Editor: drool
Comment: display java code with syntax highlighting
Deletions are marked like this. Additions are marked like this.
Line 7: Line 7:
{{{ {{{#!java
Line 16: Line 16:
{{{ {{{#!java
Line 33: Line 33:
{{{ {{{#!java
Line 48: Line 48:
}

How to extract SVG Elements and their styles

This page describes how to extract some elements from a SVG document, and get their styles (or other attributes). The basic idea is to let Batik do all the parsing work, compute the styles (you do not care if the styles are inherited or directly specified), and to ask only for the needed parts.

The first task is to create the document:

   1 String parser = XMLResourceDescriptor.getXMLParserClassName();
   2 SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);
   3 URI uri; // the URI of your SVG document
   4 Document doc = f.createDocument(uri.toString());

Then you want Batik to build the DOM for you (see BootSvgAndCssDom)

   1 UserAgent      userAgent;
   2 DocumentLoader loader;
   3 BridgeContext  ctx;
   4 GVTBuilder     builder;
   5 GraphicsNode   rootGN;
   6             
   7 userAgent = new UserAgentAdapter();
   8 loader    = new DocumentLoader(userAgent);
   9 ctx       = new BridgeContext(userAgent, loader);
  10 ctx.setDynamicState(BridgeContext.DYNAMIC);
  11 builder   = new GVTBuilder();
  12 rootGN    = builder.build(ctx, doc);

From now on, you can ask for a SVGOMSVGElement from the Document, and you can call for getComputedStyle:

   1 SVGOMSVGElement myRootSVGElement = (SVGOMSVGElement) doc.getDocumentElement();
   2 
   3 //I want all the "path" elements for example
   4 NodeList nl = myRootSVGElement.getElementsByTagName("path");
   5 
   6 for(int i=0;i<nl.getLength();++i){
   7         Element elt = (Element)nl.item(i);
   8 
   9         //I am interested in the "fill" value of the current path element
  10         String fillvalue = myRootSVGElement.getComputedStyle(elt, null).getPropertyValue("fill");
  11 
  12         //If I want to parse the "d" attribute
  13         String toParse = elt.getAttribute("d");
  14         //This string can then be fed to a PathParser if you want to create the shapes yourself
  15 }

BuildAndParse (last edited 2012-06-22 14:06:47 by drool)