public class ImageConverterSVG2G2D extends AbstractImageConverter {
/** {@inheritDoc} */
public Image convert(Image src, Map hints) throws ImageException {
checkSourceFlavor(src);
final ImageXMLDOM svg = (ImageXMLDOM)src;
if (!SVGDOMImplementation.SVG_NAMESPACE_URI.equals(svg.getRootNamespace())) {
throw new IllegalArgumentException("XML DOM is not in the SVG namespace: "
+ svg.getRootNamespace());
}
//Prepare
float pxToMillimeter = UnitConv.IN2MM / 72; //default: 72dpi
Number ptm = (Number)hints.get(ImageProcessingHints.SOURCE_RESOLUTION);
if (ptm != null) {
pxToMillimeter = (float)(UnitConv.IN2MM / ptm.doubleValue());
}
SVGUserAgent ua = new SVGUserAgent(
pxToMillimeter,
new AffineTransform());
GVTBuilder builder = new GVTBuilder();
final BridgeContext ctx = new BridgeContext(ua);
//Build the GVT tree
final GraphicsNode root;
try {
root = builder.build(ctx, svg.getDocument());
} catch (Exception e) {
throw new ImageException("GVT tree could not be built for SVG graphic", e);
}
//Create the painter
Graphics2DImagePainter painter = new Graphics2DImagePainter() {
public void paint(Graphics2D g2d, Rectangle2D area) {
// If no viewbox is defined in the svg file, a viewbox of 100x100 is
// assumed, as defined in SVGUserAgent.getViewportSize()
float iw = (float) ctx.getDocumentSize().getWidth();
float ih = (float) ctx.getDocumentSize().getHeight();
float w = (float) area.getWidth();
float h = (float) area.getHeight();
g2d.translate(area.getX(), area.getY());
g2d.scale(w / iw, h / ih);
root.paint(g2d);
}
public Dimension getImageSize() {
return new Dimension(svg.getSize().getWidthMpt(), svg.getSize().getHeightMpt());
}
};
ImageGraphics2D g2dImage = new ImageGraphics2D(src.getInfo(), painter);