Changing CSS Stylesheet for multiple transcodings

I wanted to recolor a map in several ways, and transcode each into a png. There is little on the web about how to deal with CSS style sheets in SVG. Finally I found a message with a suggestion: as amended by its reply:

The folowing outputs two .pngs with different colors for the United States:

    public void testTranscode()  {
        try {
            // make a Document with the base map 
            String parser = XMLResourceDescriptor.getXMLParserClassName();
            SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);
            String filename = "C:/maps/BlankMap-World6.svg";
            String uri = "file:///" + filename;
            Document doc = f.createDocument(uri, new FileReader(filename));

            // prepare to modify and transcode the document
            SVGDocument sdoc = (SVGDocument)doc;
            Element svgRoot = sdoc.getDocumentElement();
            PNGTranscoder t = new PNGTranscoder();
            TranscoderInput input = new TranscoderInput(doc);

            // find the existing stylesheet in the document
            NodeList stylesList = doc.getElementsByTagName("style");  
            Node styleNode = stylesList.item(0);

            // append another stylesheet after the existing one
            SVGStyleElement style = (SVGStyleElement)
                                doc.createElementNS(SVG_NAMESPACE_URI, "style");
            style.appendChild(doc.createCDATASection(".us {fill: blue;}"));
            // transcode the map
            OutputStream ostream = new FileOutputStream("outblue.jpg");
            TranscoderOutput output = new TranscoderOutput(ostream);
            t.transcode(input, output);

            // replace the appended stylesheet with another
            SVGStyleElement oldStyle = style;
            style = (SVGStyleElement)
                                doc.createElementNS(SVG_NAMESPACE_URI, "style");
            style.appendChild(doc.createCDATASection(".us {fill: green;}"));
            styleNode.getParentNode().replaceChild(style, oldStyle);
            // transcode the revised map
            ostream = new FileOutputStream("outgreen.jpg");
            output = new TranscoderOutput(ostream);
            t.transcode(input, output);
        } catch (Exception ex) {
  • No labels