I have an SVG file that contains several elements (like path, circles, rectangles, etc.).
I'd like to convert that SVG file to an SVG with embedded base64 data instead of multiple elements. is it possible to do that with Batik?
The project I'm working on requires I use Java libraries only.
There's a technique which I've used to embed SVG images in Blogger posts which might work for this. Basically, it's a two-step process:
Here's a working example that I've tested with Batik. Say that you want to embed the following SVG document, circle.svg:
You can URL-encode it by passing its path to the following small Rhino script:
Of-course, if you want to do this programmatically in Java, then you'll need a Java-specific method of serializing the SVG document and URL-encoding the string.
This gives you the document as a URL-encoded string:
You can then embed this document by using it in a data URI, which looks like this:
For example, the following HTML document uses an object tag and the data URI to embed the SVG document:
You can do the same thing with the xlink:href attribute of an SVG 'use' element, with one caveat: it's illegal to reference a full document. Instead, you need to reference an element in the document by its id, and that element will be deep-cloned into the SVG host document. In this example, the SVG document root element is reference by its id "the_svg" (note the hash tag at the end of URI).
FYI, this works well in Batik 1.7 (tested in the Squiggle browser), but not Chromium or Firefox.