Batik has very clumsy API and I also had to struggle with it. This is how I approached a similar problem.
import org.apache.batik.anim.dom.SVGStylableElement;
private void fill(SVGStylableElement element, String fillValue) {
element.getStyle().setProperty("fill", fillValue, "");
}
Usage is pretty obvious. First parameter is an instance of a SVGStylableElement
(see below). Second is the color value that you want to set (e.g. "#FF0000"). Note that setProperty()
has also third parameter - it's can be used to set !important
in CSS (I didn't need it).
So first you need to get an instance of SVGStylableElement
.
import org.w3c.dom.Element;
import org.w3c.dom.svg.SVGDocument;
private Optional<SVGStylableElement> getElement(final SVGDocument svg, String id) {
Element element = svg.getElementById(id);
if (null == element) {
return Optional.empty();
}
if (!SVGStylableElement.class.isAssignableFrom(element.getClass())) {
return Optional.empty();
}
return Optional.of((SVGStylableElement) element);
}
The method above is in Java8+ style but can be re-written for older Java version if needed. You provide an instance of SVGDocument
and element id (in your example that would be "path3622").
I assume that you already have an instance of SVGDocument
created somehow so I omit it here.
The last but required method is initialization of CSS Engine. This is kind of Batik's magic. You can find more info there https://wiki.apache.org/xmlgraphics-batik/BootSvgAndCssDom
import org.apache.batik.bridge.BridgeContext;
import org.apache.batik.bridge.DocumentLoader;
import org.apache.batik.bridge.GVTBuilder;
import org.apache.batik.bridge.UserAgentAdapter;
private void initializeEngine(SVGDocument svg) {
UserAgentAdapter userAgent = new UserAgentAdapter();
DocumentLoader loader = new DocumentLoader(userAgent);
BridgeContext ctx = new BridgeContext(userAgent, loader);
ctx.setDynamicState(BridgeContext.DYNAMIC);
GVTBuilder builder = new GVTBuilder();
builder.build(ctx, svg);
}
So remember to call this initializeEngine(...)
method once just after you created instance of SVGDocument
. If you don't do this, you get NPE in element.getStyle()
in fill(...)
method.
Just for reference, these are entries in my pom.xml that I used:
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-svg-dom</artifactId>
<version>1.9.1</version>
</dependency>
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-anim</artifactId>
<version>1.9.1</version>
</dependency>
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-bridge</artifactId>
<version>1.9.1</version>
</dependency>