Flying Saucer XML/CSS2 Renderer
SVG via Replaced ElementsFlying Saucer allows you to replace any XML element with a ReplacedElement, which is a component that knows how to draw itself on the given user agent canvas (e.g. screen, PDF). You can use this functionality to extend Flying Saucer to include elements, such as SVG, rendered by a third-party library. To keep the core Flying Saucer as small as possible, we don't ourselves include these extensions, but this demo shows that it is not difficult to do.
There are several libraries for rendering SVG in Java; we've chosen to use the SVGSalamander project hosted on java.net at https://svgsalamander.dev.java.net. There are other SVG libraries for Java available, notably Batik.
In this XHTML page, we are using a standard <object>
tag to reference SVG files
available on the classpath for this sample application. The object tag used here looks like this in its
simplest form:
<object type="image/svg+xml" data="/svg/dat/system-users.svg" />
This references a file, go-home.svg
, which is rendered as the small home icon shown
at the beginning of this page. In this use of the object tag, the size of the rendered SVG is determined
by the SVG file itself (minimum size needed to render). One of the nice things about SVG, however, is
that it is written to allow for smooth, proportional scaling. We can scale the exact same file by
using either CSS (via id
, class
, or style
attributes) or via
width
and height
attributes on the object
tag. For example, the following
tag will scale the same icon using the CSS defined by the class "normal_icon", which defines the width and height
as 48px each
<object class="med_icon" type="image/svg+xml" data="/svg/dat/system-users.svg" />
And here's what how that renders
But we can make it large, too--just by changing the CSS width and height properties:
Even better, we can apply other CSS styling to our SVG, including positioning. Note that by default, the object elements are declared as block-level elements, not inline. Thus we can float the following icons left, with a small margin added to the right, using just CSS:
Pretty nice, huh? You can embed SVG in your pages just as you would normal images--and they scale nicely!
SVG is a complex standard, and the Java libraries for rendering SVG are not always completely up-to-spec. You should test the SVG rendering outside of Flying Saucer first before adding it to a web page.
Note: the SVGSalamander library is distributed under the terms of the GNU Lesser General Public License. The icon(s) shown on this page are from the Tango Icon Gallery, located at http://tango.freedesktop.org, and distributed under the Creative Commons Attribution-ShareAlike 2.5 License Agreement. We thank the folks in the Salamander and Tango communities for sharing these high-quality libraries with others.