Can I create JSVGCanvas without svg file?
Looking through the documentation forJSVGCanvas
it looks like I might not be able to do this. However, for this it is very important that it is possible. How can I create JSVGCanvas
from a variable String
instead File
?
My idea is that I can do something like the following:
String svg = "svg data";
JFrame frame = new JFrame();
JSVGCanvas canvas = new JSVGCanvas();
canvas.setContentsFromString(svg);
frame.add(canvas);
frame.setVisible(true);
I know I can always create a temporary file and set the content JSVGCanvas
from the file, but I'd rather avoid that. Can I possibly extend File
and override its methods?
Note. I am using Jython, but I think this also applies to Java, so I am using both tags. I would prefer the solution to be in Java, but Jython's solution will work
source to share
Yes, you can:
String parser = XMLResourceDescriptor.getXMLParserClassName();
SAXSVGDocumentFactory factory = new SAXSVGDocumentFactory(parser);
SVGDocument document = factory.createSVGDocument("", new ByteArrayInputStream(svg.getBytes("UTF-8")));
canvas.setSVGDocument(document);
It works by building SVGDocument
through SAXSVGDocumentFactory
. SAXSVGDocumentFactory
has a method createSVGDocument(String, InputStream)
where the string is assumed to be the URI for the file that represents InputStream
. However, we abuse this and pass it an empty string and make a stream InputStream
from our svg-data string.
Usage ""
may throw a missing protocol exception, depending on the Batik version. If this happens, try "file:///"
, that is, give it a URI, which is false. You can use the actual URI; you will need to find a valid one to give Batik
source to share