Hello to all.

I had the problem of painting a SVG to a Graphics2D. But I needed to
do it with out a JSVGCanvas, JSVGComponent, etc. I had a lot of
problems finding documentation, examples, etc, and finally solved the
problem by my self. This is the code, I hope it may help to others:

public static void main(String[] args) throws Exception {
        SVGDocument document = null;

        // Load the document
        String parser = XMLResourceDescriptor.getXMLParserClassName();
        SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);

        File file = new 
File(LaMierdaEsta.class.getResource("test.svg").getFile());
        document = (SVGDocument) f.createDocument(file.toURL().toString());

        // Build the tree and get the document dimensions
        UserAgentAdapter userAgentAdapter = new UserAgentAdapter();
        BridgeContext bridgeContext = new BridgeContext(userAgentAdapter);

        GVTBuilder builder = new GVTBuilder();

        GraphicsNode graphicsNode = builder.build(bridgeContext, document);
        CanvasGraphicsNode canvasGraphicsNode = (CanvasGraphicsNode)
graphicsNode.getRoot().getChildren().get(0);

        Rectangle2D bounds = canvasGraphicsNode.getSensitiveBounds();

        // TODO: This is a workaround to solve the problem
        // of the nodes having a clip of size 1
        GVTTreeWalker treeWalker = new GVTTreeWalker(graphicsNode);
        GraphicsNode currNode;

        while ((currNode = treeWalker.nextGraphicsNode()) != null) {
                currNode.setClip(null);
        }

        // XXX: We want to scale 2 in x and 1.5 in y
        double scaleX = 2;
        double scaleY = 1.5;

        graphicsNode.setTransform(AffineTransform.getScaleInstance(scaleX, 
scaleY));

        // Paint it to a image using a Graphics2D
        BufferedImage bufferedImage = new BufferedImage((int)
(bounds.getWidth() * scaleX), (int) (bounds.getHeight() * scaleY),
BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = (Graphics2D) bufferedImage.getGraphics();

        graphicsNode.paint(g2d);
        g2d.dispose();

        // Write the image to a file
        ImageIO.write(bufferedImage, "png", new File("out.png"));
}

There is a TODO: the problem was that all objects in the tree has
clips with bounds of (0, 0, 1, 1) so the only thing I get first was a
black image only with the pixel at 0, 0 painted. I don't know why all
the clips are this way, y any one knows it please tell me. At least
the workaround works.

Regards, Demi�n Gutierrez.

PS: I',m very new using batik (a few days) so if you have coments or
suggestions about my code, they are welcomed. :-)

---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to