Search code examples
javabatik

Batik load SVG file in SVGGraphics2D


I use batik for drawing svg, and save it. That work.

But now i try to load my svg file and add somthing.

I use this fonction for load my svg file

private static SVGDocument loadSVGDocument(String uri) {
    String parser = XMLResourceDescriptor.getXMLParserClassName();
    SAXSVGDocumentFactory factory = new SAXSVGDocumentFactory(parser);
    SVGDocument svgDocument = null;
    try {
        //svgDocument = factory.createSVGDocument(IMAGE_SVG);
        svgDocument = factory.createSVGDocument(uri);
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
    return svgDocument;
}

and this for have SVGGraphics2D

SVGDocument svgDocument = loadSVGDocument(TEST_SVG);
SVGGraphics2D g = new SVGGraphics2D(svgDocument);

When i debug my SVGDocument have all children and attribut null And when i generate image, is empty and size is 400x400

Where is problem when i load my SVG file?


Solution

  • I every body I find a solution for my case

    I compare my generation and my file. First think i have svg root and one child g only. svg root don t have with and height

    I go search width and height

            Element elSVG = svgDocument.getRootElement();
        String width = elSVG.getAttribute("width");
        String height = elSVG.getAttribute("height");
    

    and after root

    NodeList nodes = elSVG.getElementsByTagName("g");
        Node node = nodes.item(0);
        Element el = null;
        if(Node.ELEMENT_NODE == node.getNodeType()) {
            el = (Element)node;
        }
    

    and for the end add everything to graphics

            SVGGraphics2D g = new SVGGraphics2D(svgDocument);
        g.setTopLevelGroup(el);
        g.setSVGCanvasSize(new Dimension(Integer.parseInt(width), Integer.parseInt(height)));
    

    And that works for only one child to svg. For me is OK for now.

    And i try to add an other think like rectangle and that work to.