XML Europe 2001 logo21-25 May 2001
Internationales Congress Centrum (ICC)
Berlin, Germany

Leveraging SVG on the Java platform with Batik

Vincent J. Hardy <vhardy@apache.org>
Thierry Kormann <tkormann@apache.org>
 PDF version    Latest version   

ABSTRACT

Scalable Vector Graphics (SVG) is an XML grammar for describing rich 2D graphics and is a work of the W3C. The Java platform(TM) is now commonly used for all kinds of applications, both server-side and client-side, and it is especially appropriate for web applications. The Batik Apache project (see http://xml.apache.org/batik) is an open source, Java language based toolkit for generating, manipulating and viewing SVG content. This paper shows how developers can leverage the various Batik modules in their client side and/or server side applications.

Table of Contents

1. Abstract

Scalable Vector Graphics (SVG) is an XML grammar for describing rich 2D graphics and is a work of the W3C. The Java platform(TM) is now commonly used for all kinds of applications, both server-side and client-side, and it is especially appropriate for web applications. The Batik Apache project (see http://xml.apache.org/batik) is an open source, Java language based toolkit for generating, manipulating and viewing SVG content. This paper shows how developers can leverage the various Batik modules in their client side and/or server side applications.

2. INTRODUCTION

This paper first introduces SVG and discusses its key qualities and features. Then it presents the Batik project, its goal and status. Finally, this paper explains how to leverage SVG on the Java platform with Batik.

3. PART I: SVG & BATIK

SVG, Scalable Vector Graphics is a upcoming recommendation from the W3C which has been in the works for over two years. The Batik project is an open-source implementation of the SVG specification that helps developers add support for SVG in their applications. This part introduces the SVG format, discusses its features and strengths, and gives some background on the Batik project.

3.1. What is SVG?

3.1.1. Origins

SVG stands for Scalable Vector Graphics. SVG is a language for describing rich 2D graphics in XML. It was created by the World Wide Web consortium (W3C), the non-profit, industry-wide, open-standards consortium that created HTML and XML among other important works. Over twenty organizations, including Sun Microsystems, ILOG, Adobe, Apple, IBM, and Kodak, have been involved in defining SVG. SVG is currently (as of February 25, 2001) in Candidate Recommendation status, but it is expected to move soon to Proposed Recommendation before becoming a Recommendation.

3.1.2. Example

The above figure shows a simple graphic specified in SVG format. It illustrates some of SVG's static capabilities and will give the reader a flavor of the SVG syntax. Refer to the SVG specification [1] and to the the paper paper in reference [3] for details on the various tags and their parameters. The example shows some of the features we mentioned earlier: sophisticated graphics (with gradient paints for the background, nose and eyes, simple or arbitrary geometry for the various graphical elements, rich text formatting and filter effects for the drop shadow).

Code for the Example:

 
<svg width="700" height="700" viewBox="0 0 300 300"> <defs> <!-- Nose Paint -->
<radialGradient id="s21-1nosePaint" 
  gradientUnits="userSpaceOnUse" cx="5" cy="5" fx="4" fy="4" r="2">
<stop offset="0%" stop-color="white" />
<stop offset="20%" stop-color="#ccccff" />
<stop offset="100%" stop-color="#222255" />
</radialGradient>
<!-- Eye Paint -->
<radialGradient id="s21-1eyeBallPaint"
  gradientUnits="userSpaceOnUse" cx="3" cy="3" fx="2.6" fy="2.6" r="1">
<stop offset="0%" stop-color="white" />
<stop offset="20%" stop-color="#ccccff" />
<stop offset="100%" stop-color="#222255" />
</radialGradient>
<radialGradient id="s21-1backgroundPaint" r="1.1">
<stop offset="0%" stop-color="white" />
<stop offset="30%" stop-color="#ccccff" />
<stop offset="65%" stop-color="#222255" />
<stop offset="100%" stop-color="black" />
</radialGradient>
<filter id="s21-1dropShadow" width="1.3" height="1.3" >
<feGaussianBlur in="SourceAlpha" stdDeviation="0.1 0.1"/>
<feOffset dx="0.1" dy="0.1" />
<feColorMatrix type="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0.5 0" />
<feMerge>
<feMergeNode />
<feMergeNode in="SourceGraphic" />
</feMerge>
</filter>
</defs>
<rect x="0" y="0" width="300" height="330"
  fill="url(#backgroundPaint)" stroke="none" />
<g id="s21-1happyFace" transform="scale(30, 30)" filter="url(#dropShadow)" >
<!-- Left eye -->
<circle cx="3" cy="3" r="1" fill="url(#eyeBallPaint)"/>
<circle cx="3.5" cy="3.5" r=".5" fill="black" stroke="none" />
<!-- Right eye -->
<circle transform="translate(4, 0)" cx="3" cy="3" r="1" fill="url(#eyeBallPaint)"/>
<circle cx="6.5" cy="3.5" r=".5" fill="black" stroke="none" />
<!-- Nose -->
<circle cx="5" cy="5" r="2" fill="url(#nosePaint)" />
<!-- Smile -->
<path d="M 2,6 C 2,9.5 8,9.5 8, 6"
  fill="none" stroke="#222255" stroke-width="1" stroke-linecap="round"/>
<!-- Text -->
<g text-anchor="middle" font-family="SunSans-Heavy"
  font-size="1" font-weight="bold" fill="white">
<text x="5" y="5">
<tspan>Java</tspan>
<tspan x="5" dy="1" font-style="italic" fill="#ff0000">SVG</tspan>
</text>
</g>
</g>
</svg>

3.1.3. What does SVG allow?

SVG is language for sophisticated, interactive, and dynamic 2D graphics. SVG defines three types of graphical elements:

  1. Vector graphic shapes: SVG defines standard shapes as a convenience for common graphical operations such as arbitrary path, circle, ellipse, line, polyline, polygon, and rectangle.

  2. Images: Images in SVG can be either raster image such as JPEG or PNG, or SVG documents.

  3. Text: SVG provides powerful text capabilities. You can use SVG to define a simple line of text or to define very complex text that uses rich formatting properties or to laid out on arbitrary paths.

The figure above illustrates some of the these features: the waves on the left are created with SVG <path> elements which can describe arbitrary geometry. The text in the image in described with <text> elements and makes it possible to search for text content in the image. In addition to graphical elements, SVG defines a set of elements to include powerful rendering effects to your SVG content. Gradients and filter effects are an example of SVG elements that can be applied to graphic elements. For example, filters can be used to create drop shadows (as in the example above) or lighting effects.

At last, because the Web is a dynamic medium, SVG allows sophisticated interactive and dynamic 2D graphics. SVG content can be animated through the following ways:

  1. Using SMIL animations that are defined and triggered with embedding SVG animation elements in your SVG content.

  2. Via scripting and the Document Object Model (DOM) API. SVG content can be manipulated by a scripting language such as ECMAScript.

  3. Using the linking feature of SVG which is similar to the one defined in HTML.

3.1.4. SVG Key Qualities

SVG has many advantages over other images formats, and particularly over JPEG and GIF, the most common graphic formats used on the Web today. Specifically:

  1. Open standard. SVG is an open recommendation developed by a cross-industry consortium. Unlike several other graphics formats, SVG is not proprietary or controlled by a single company.

  2. XML syntax. As an XML grammar, SVG offers all the advantages of XML such as interoperability, internationalization (Unicode support), wide tool support, an easy manipulation through the standard Document Object Model API (DOM, W3C), and easy transformation through XML Stylesheet Language (XSLT, W3C).

  3. Scalable. Unlike bitmapped GIF and JPEG formats, SVG is a vector format, which means SVG images can be printed with high quality at any resolution, without the "staircase" effects you see when printing bitmapped images.

  4. Zoomable. You can zoom in on any portion of an SVG image and not see any degradation.

  5. Wide industry support. With over twenty organizations involved in the specification of SVG, many tools such as Adobe Illustrator(TM), ILOG JViews component suite(TM), or CorelDraw(TM) already support SVG as at least an exchange format.

  6. Plain text. SVG files can be read and modified by a range of tools and are usually much smaller and more compressible than comparable JPEG or GIF images

  7. Stylable. Using the Cascading Stylesheets (CSS) to add style informations to SVG elements, SVG is flexible, faster to download and easier to maintain.

3.2. Java and SVG

The Java(TM) programming language provides portable code. Since the JDK 1.2, the Java platform provides the Java 2D API which brings a large number of feature such as: rich rendering capabilities (stroking, gradients, transparency, compositing), font and text manipulation, imaging capabilities (filtering, rendering of various image formats), affine transforms, and color management. By combining both, SVG provides a graphics meta-file format for the Java platform and the Java 2D API and the Java platform in general provide a powerful environment for creating and manipulating SVG content.

Both technologies complement each other, SVG offers portable 2D graphics data and the Java platform lets the developers create portable code and applications involving SVG and XML in general.

Many applications and tools involving XML already exist. There are multiple XSL Transformation engines, XML parsers or DOM implementations written in the Java language. Consequently, as SVG is XML, the Java platform offers great opportunities and solutions to manage XML and more specifically SVG documents.

3.3. What is Batik?

3.3.1. Origins

Batik is an Apache open-source project. Under the umbrella of the Apache project, companies such as Sun Microsystems, ILOG, and Kodak decided to provide a Java based toolkit that let developers create, manipulate, transform, or view SVG content both on client and server side.

3.3.2. Status

Batik is currently (as of February 25, 2001) in beta version but supports most of the static features described in the SVG specification. In addition, at this time of writing, Batik integrates some dynamic features such as hyperlinks (similar to the 'a' element of HTML), the access to the SVG tree through an implementation of the Document Object Model API, and event propagation to script handler in response to mouse movements.

3.3.3. What does Batik allow

Batik provides a set of core modules which can be used together or individually to support specific SVG solutions. As part of the code modules, the toolkit already provides:

  1. SVG viewing capabilities to all Java applications by providing a swing component which renders SVG document fragment.

  2. An easy way for all Java applications to generate SVG content through the Java 2D API with almost no code changes.

  3. SVG client and server side solutions to create and manipulate SVG documents. Batik includes a full DOM Level 2 implementation for SVG.

  4. Transcoding capabilities to convert SVG documents to various output format such as JPEG or PNG.

3.3.4. Applications of Batik

Several modules of Batik can be used both on client side and server side. From creating to viewing SVG documents, Batik can be used at any step of the web content publishing pipeline.

In a nutshell, Batik provides building blocks that developers can assemble in various ways in their Java technology applications to generate, parse, view or convert SVG content. For example, Batik contains a Swing component that can add SVG viewing capability to all Java technology applications. Batik can also be used to generate SVG on a client or on a server, and Batik can convert SVG content into other formats such as JPEG or PNG. Batik's goal is to make it easy for application developers to handle SVG content for various purposes, client-side or server-side, as illustrated in the above diagram.

4. Part II: Leveraging Batik

4.1. DOM API

Batik provides a full implementation of the Document Object Model (DOM) Level 2 API (W3C) including a Cascading Stylesheets (CSS) engine. The Document Object Model Level 2 is a platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content and structure of documents.

Using this standard API which is a W3C Recommendation since November 2000, developers can create and manipulate SVG content in a standard and flexible way, as illustrated in the following code fragment:

 
import org.w3c.dom.*;

DOMImplementation impl = ...; // Depends on DOM implementation
String svgNS = ...; 

Document doc =
 impl.createDocument(svgNS, "svg", null);

Element svgRoot = doc.getDocumentElement();
svgRoot.setAttributeNS(null, "width", "500");
svgRoot.setAttributeNS(null, "height", "500");
...
Element rect = doc.createElementNS(svgNS, "rect");
rect.setAttributeNS(null, "fill", "red");

svgRoot.appendChild(rect);
...

4.2. SVG Generator

The SVG Generator is another core module of Batik. By combining the Java 2D API and SVG, the SVG generator offers to all Java graphic applications, an easy way to create SVG documents.

On the Java platform, all rendering goes through the Graphics2D class. By taking advantage of the extensible design of the 2D API, the SVG generator main class (the SVGGraphics2D) is an implementation, dedicated to SVG, of the Graphics2D class. Instead of drawing to the screen or printing, the SVGGraphics2D class creates a SVG DOM tree which can then be manipulated or serialized to produce an SVG document.

Usage of the SVGGraphics2D class is illustrated in the following code fragment:

 
 
import org.apache.batik.svggen.SVGGraphics2D;

// Create an instance of HelloSVG
HelloSVG helloSVG = new HelloSVG(...);

// SVGGraphics2D extends Graphics2D
SVGGraphics2D svgGenerator = ...;

// Now, ask helloSVG to render into our
// custom Graphics2D implementation
helloSVG.paint(svgGenerator);

// Finally, stream out SVG to the standard output
Writer outWriter = new OutputStreamWriter(System.out, "UTF-8");
svgGenerator.stream(outWriter);

The SVG generator allows Java technology applications to export their graphics into SVG format in a very simple way. This way, the Java 2D API can also be considered by developers as an authoring tool to generate SVG.

4.3. SVG and Swing

Batik provides client side modules for applications that want to add SVG viewing capabilities. The first module is the JSVGCanvas which enables all Java applications using swing to view SVG content. An an example, the viewer available in Batik relies on this component.

Batik also provides an applet which adds SVG viewing capabilities to web browsers that don't support SVG natively. Even though the Java plug-in is required, the applet technology provides an alternative to display at the same time, a SVG and a HTML document.

4.4. Java Server Pages

Servlet and Java Server Pages (JSP) offer a very good platform to generate SVG content dynamically.

The following figure illustrates how a JSP can analyze a client's request (1), query a data base as a result (2), generate a graphic such as a statistical graphic from the data (3) and then send the resulting graphic to the client (4), directly in the SVG format or after conversion to another format (such as JPEG)

Batik provides a high level transcoding API. The transcoder API brings the opportunity to create SVG document from other formats such WMF or XML, and convert SVG documents to other formats such as JPEG or PNG.

5. Conclusion

In this paper we have discussed the Scalable Vector Graphics XML grammar and the Batik project. We have seen how the first one is an open specification for describing rich 2D graphics and how the second one is a powerful, platform independent SVG toolkit.

With so many advantages (feature rich, XML syntax, dynamic behavior...) compared to raster images, many believe that SVG will be a successful standard on the web, and also in other environments, such as a format to exchange all kind of graphical data.

Finally and more importantly, a standard is a success when it has been accepted by companies and integrated in applications. The Batik project is free, open-source and compliant SVG toolkit which provides a wide range of solutions for both client side and server side applications that would like to take advantage of SVG nowadays.

Biography

Vincent J. Hardy
Senior Staff Engineer
Batik project, Apache
Sun Microsystems, Inc.
Palo Alto
California
USA
Email: vhardy@apache.org Web: xml.apache.org/batik

Vincent Hardy - Vincent is one of the founders of the SVG Batik project at Apache and he represents Sun in the W3C's SVG Working Group (his daytime job is to be a member of Sun's XML Technology Center). Vincent is the author of papers and a book on the Java 2D API.

Thierry Kormann
Software Engineer
Apache Batik
ILOG
Sophia Antipolis
France
Email: tkormann@apache.org Web: xml.apache.org/batik

Thierry Kormann - Thierry is a software engineer, at the Koala project of ILOG located at INRIA Sophia Antipolis,France. Thierry has contributed to most of the Koala's projects involving Java and XML. Since then, he co-founded the Apache Batik project. His daytime job is focused on Graphics and XML related technologies.