Debian Codegraph @

documentation-sources/content/xdocs/using/svg-generator.xml

raw
1 <?xml version="1.0"?>
2
3 <!--
4
5 Licensed to the Apache Software Foundation (ASF) under one or more
6 contributor license agreements. See the NOTICE file distributed with
7 this work for additional information regarding copyright ownership.
8 The ASF licenses this file to You under the Apache License, Version 2.0
9 (the "License"); you may not use this file except in compliance with
10 the License. You may obtain a copy of the License at
11
12 http://www.apache.org/licenses/LICENSE-2.0
13
14 Unless required by applicable law or agreed to in writing, software
15 distributed under the License is distributed on an "AS IS" BASIS,
16 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 See the License for the specific language governing permissions and
18 limitations under the License.
19
20 -->
21
22 <!-- ========================================================================= -->
23 <!-- author [email protected] -->
24 <!-- author [email protected] -->
25 <!-- version $Id$ -->
26 <!-- ========================================================================= -->
27
28 <!DOCTYPE document PUBLIC "-//APACHE//DTD Documentation V2.0//EN" "http://forrest.apache.org/dtd/document-v20.dtd">
29 <document>
30 <header>
31 <title>SVG Generator: SVGGraphics2D</title>
32 </header>
33
34 <body>
35 <div class="figure"><img src="images/svggen.jpg" alt="Flow diagram illustrating that Java programs can have their graphics converted to SVG and then viewed in any SVG viewer"/>
36 </div>
37 <p>
38 As SVG is emerging as a promising graphics format for a wide range of
39 domains and applications, bridging it with Java becomes important. This
40 page explains how Batik’s
41 <a class="class" href="../javadoc/org/apache/batik/svggen/SVGGraphics2D.html">SVGGraphics2D</a>,
42 referred to as the SVG Generator, makes this possible.
43 </p>
44
45 <section id="whatIsIt">
46 <title>The <code>SVGGraphics2D</code> class</title>
47 <p>
48 On the Java platform, all rendering goes through the
49 <a class="class" href="http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Graphics2D.html">Graphics2D</a>
50 abstract class, which offers methods such as <code>drawRect</code>,
51 <code>fillRect</code>, and <code>drawString</code>. There are
52 specialized implementations of this abstract class for each type of
53 output, such as a screen or a printer. <code>SVGGraphics2D</code> is
54 a new implementation of that interface that generates SVG content
55 instead of drawing to a screen or a printer.
56 </p>
57
58 <p>
59 <code>SVGGraphics2D</code> has the following features:
60 </p>
61 <ul>
62 <li>
63 it allows applications to export their graphics into SVG format,
64 </li>
65 <li>
66 it does not require any modification of the graphics code to export
67 to SVG, and
68 </li>
69 <li>
70 it offers the user the ability to use the DOM API to manipulate the
71 generated document.
72 </li>
73 </ul>
74
75 <div class="figure"><img src="images/svggenHighLevelArchi.jpg" alt="Diagram illustrating how the SVGGraphics2D inherits from Graphics2D, and uses Document to generate a DOM tree"/>
76 </div>
77
78 <p>
79 The above figure shows how the generator works with the DOM API. The W3C
80 has defined an API for representing XML content with a Java object.
81 That API allows programmers to manipulate, create, and/or modify XML
82 content in memory. The DOM API contains interfaces such as
83 <a class="class" href="http://java.sun.com/j2se/1.5.0/docs/api/org/w3c/dom/Document.html">Document</a>,
84 <a class="class" href="http://java.sun.com/j2se/1.5.0/docs/api/org/w3c/dom/Element.html">Element</a>,
85 and
86 <a class="class" href="http://java.sun.com/j2se/1.5.0/docs/api/org/w3c/dom/Attr.html">Attr</a>,
87 which model the Java programming language equivalent of XML documents,
88 elements and attributes.
89 </p>
90 <p>
91 The generator manages a tree of DOM objects that represent the SVG
92 content corresponding to the rendering calls made on the
93 <code>SVGGraphics2D</code> instance. In other words, every time a
94 program invokes a rendering method, such as <code>fillRect</code>, on a
95 <code>SVGGraphics2D</code> instance, a new DOM object,
96 representing the SVG equivalent, is appended to the DOM tree. For
97 example, a <code>rect</code> element will be appended after the
98 <code>fillRect</code> method has been invoked).
99 </p>
100 <p>
101 The programmer, using this generator, can then access the DOM tree to
102 further manipulate it or can directly write the content to an output
103 stream, as we see in the following section.
104 </p>
105
106 </section>
107
108 <section id="howToUse">
109 <title>How to use SVGGraphics2D</title>
110 <p>
111 From the figure in the previous section we can see that in order for an
112 instance of <code>SVGGraphics2D</code> to build the SVG content (the
113 DOM tree), an instance of a <code>Document</code> class is needed. The
114 DOM tree is an in-memory representation of the SVG document, which can
115 be further manipulated by the user using DOM API or be streamed
116 out by a
117 <a class="class" href="http://java.sun.com/j2se/1.5.0/docs/api/java/io/Writer.html">Writer</a>
118 object.
119 </p>
120
121 <p>
122 The following example program demonstrates how to generate SVG content
123 from Java graphics.
124 </p>
125
126 <source><![CDATA[import java.awt.Rectangle;
127 import java.awt.Graphics2D;
128 import java.awt.Color;
129 import java.io.Writer;
130 import java.io.OutputStreamWriter;
131 import java.io.IOException;
132
133 import org.apache.batik.svggen.SVGGraphics2D;
134 import org.apache.batik.dom.GenericDOMImplementation;
135
136 import org.w3c.dom.Document;
137 import org.w3c.dom.DOMImplementation;
138
139 public class TestSVGGen {
140
141 public void paint(Graphics2D g2d) {
142 g2d.setPaint(Color.red);
143 g2d.fill(new Rectangle(10, 10, 100, 100));
144 }
145
146 public static void main(String[] args) throws IOException {
147
148 // Get a DOMImplementation.
149 DOMImplementation domImpl =
150 GenericDOMImplementation.getDOMImplementation();
151
152 // Create an instance of org.w3c.dom.Document.
153 String svgNS = "http://www.w3.org/2000/svg";
154 Document document = domImpl.createDocument(svgNS, "svg", null);
155
156 // Create an instance of the SVG Generator.
157 SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
158
159 // Ask the test to render into the SVG Graphics2D implementation.
160 TestSVGGen test = new TestSVGGen();
161 test.paint(svgGenerator);
162
163 // Finally, stream out SVG to the standard output using
164 // UTF-8 encoding.
165 boolean useCSS = true; // we want to use CSS style attributes
166 Writer out = new OutputStreamWriter(System.out, "UTF-8");
167 svgGenerator.stream(out, useCSS);
168 }
169 }]]></source>
170
171 <p>
172 We can see that generating SVG content from our <code>TestSVGGen</code>
173 instance is a three step process:
174 </p>
175 <ol>
176 <li>
177 <p>
178 Create an instance of <code>org.w3c.dom.Document</code> that the
179 generator will use to build its XML content, and create an SVG generator
180 using the <code>Document</code> instance.
181 </p>
182 <source> // Get a DOMImplementation.
183 DOMImplementation domImpl =
184 GenericDOMImplementation.getDOMImplementation();
185
186 // Create an instance of org.w3c.dom.Document.
187 String svgNS = "http://www.w3.org/2000/svg";
188 Document document = domImpl.createDocument(svgNS, "svg", null);
189
190 // Create an instance of the SVG Generator.
191 SVGGraphics2D svgGenerator = new SVGGraphics2D(document);</source>
192 </li>
193 <li>
194 <p>
195 Invoke the rendering code on our SVG generator. In our example, we
196 invoke <code>TestSVGGen</code>‘s <code>paint</code> method:
197 </p>
198 <source> // Ask the test to render into the SVG Graphics2D implementation.
199 TestSVGGen test = new TestSVGGen();
200 test.paint(svgGenerator);</source>
201 </li>
202 <li>
203 <p>
204 Stream out the SVG content. The SVG generator can stream its content
205 into any <code>java.io.Writer</code>. In our example, we stream the
206 content to the standard output stream:
207 </p>
208 <source> // Finally, stream out SVG to the standard output using
209 // UTF-8 encoding.
210 boolean useCSS = true; // we want to use CSS style attributes
211 Writer out = new OutputStreamWriter(System.out, "UTF-8");
212 svgGenerator.stream(out, useCSS);</source>
213 </li>
214 </ol>
215 <p>
216 SVG has
217 <a href="http://www.w3.org/TR/SVG11/styling.html#AlternativesForStyling">two
218 ways to specify styling properties</a>, such as the fill color:
219 presentation attributes (one XML attribute per property) or the CSS
220 <code>style</code> attribute (any number of properties in one CSS
221 inline stylesheet). The <code>useCss</code> parameter allows the user
222 to control that option.
223 </p>
224 </section>
225
226 <section id="custom">
227 <title>SVG Generator customization</title>
228 <p>
229 In the previous section, we have just seen that the SVG generation
230 process can be customized to output SVG styling properties as
231 presentation attributes or CSS inline stylesheets. In this section we
232 will talk about some examples of more advanced customizations.
233 </p>
234 <p>
235 Instead of creating the <code>SVGGraphics2D</code> just by using the
236 <code>Document</code> that will be used as a factory for creating the
237 SVG elements, we can use the constructor that uses an
238 <a class="class" href="../javadoc/org/apache/batik/svggen/SVGGeneratorContext.html">SVGGeneratorContext</a>
239 instance. By providing your own <code>SVGGeneratorContext</code>
240 instance, you will be able to do advanced customization. You will find
241 below several examples of possible customizations.
242 </p>
243 <section>
244 <title>Have your own comment in the generated SVG file</title>
245 <p>
246 We begin with the simplest possible example. If you integrate the
247 Batik SVG generator in your own Java application, you may want to
248 specialize the comment generated in the XML code.
249 </p>
250
251 <source>DOMImplementation impl =
252 GenericDOMImplementation.getDOMImplementation();
253 String svgNS = "http://www.w3.org/2000/svg";
254 Document myFactory = impl.createDocument(svgNS, "svg", null);
255
256 SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(myFactory);
257 <strong>ctx.setComment("Generated by FooApplication with Batik SVG Generator");</strong>
258 SVGGraphics2D g2d = new SVGGraphics2D(ctx, false);</source>
259 </section>
260
261 <section>
262 <title>Use embedded SVG Fonts in the generated SVG file</title>
263 <p>
264 In order to have a self-contained SVG file that doesn't have to use
265 system fonts to be displayed, you can embed the fonts you used for
266 drawing strings in the SVG file through the SVG fonts facility.
267 </p>
268
269 <source>DOMImplementation impl =
270 GenericDOMImplementation.getDOMImplementation();
271 String svgNS = "http://www.w3.org/2000/svg";
272 Document myFactory = impl.createDocument(svgNS, "svg", null);
273
274 SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(myFactory);
275 <strong>ctx.setEmbeddedFontsOn(true);</strong>
276 SVGGraphics2D g2d = new SVGGraphics2D(ctx, <strong>true</strong>);</source>
277 </section>
278
279 <section>
280 <title>Customizing the way images are stored</title>
281 <p>
282 Every time you call one of the <code>drawImage</code> methods
283 provided by the <code>Graphics2D</code> interface, a default
284 representation of your image is created in a location and put in a
285 default file. For instance, a base64 encoding is created and embedded
286 in the SVG file by default. Alternatively, you can choose to have your
287 images written to separate files in a predefined directory, in one of
288 the two raster formats required by the SVG specification: JPEG or PNG.
289 </p>
290 <p>
291 You can change the default behavior by explicitly providing the
292 image handler to be used by the SVG generator. Once again, you use
293 the <code>SVGGeneratorContext</code> for this. In the example below,
294 all images are converted to PNG format and written to directory
295 <code>res/images</code>.
296 </p>
297 <source>DOMImplementation impl =
298 GenericDOMImplementation.getDOMImplementation();
299 String svgNS = "http://www.w3.org/2000/svg";
300 Document myFactory = impl.createDocument(svgNS, "svg", null);
301
302 SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(myFactory);
303 <strong>GenericImageHandler ihandler = new ImageHandlerPNGEncoder("res/images", null);
304 ctx.setImageHandler(ihandler);</strong>
305 SVGGraphics2D g2d = new SVGGraphics2D(ctx, false);</source>
306 <p>
307 Using the default image handlers results in a new copy of the image
308 data being written to the SVG file or an external file, for every
309 single <code>drawImage</code> call. If you use the same images over
310 and over again, then this may result in an SVG file containing a lot
311 of redundant data. At the price of a slight performance penalty
312 during initial generation of the SVG DOM tree, you can choose to
313 have your image data reused. For this you use a specialized image
314 handler, as shown below.
315 </p>
316 <source>DOMImplementation impl =
317 GenericDOMImplementation.getDOMImplementation();
318 String svgNS = "http://www.w3.org/2000/svg";
319 Document myFactory = impl.createDocument(svgNS, "svg", null);
320
321 SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(myFactory);
322
323 // Reuse our embedded base64-encoded image data.
324 <strong>GenericImageHandler ihandler = new CachedImageHandlerBase64Encoder();
325 ctx.setGenericImageHandler(ihandler);</strong>
326
327 SVGGraphics2D g2d = new SVGGraphics2D(ctx, false);</source>
328 <p>
329 With the caching image handlers, it is even possible to reuse the
330 same copy of your image data across several different SVG documents.
331 Just keep a reference to the image handler, and pass it to the
332 <code>SVGGraphics2D</code> instance used for generating the SVG DOM
333 tree. The following simplified example shows how different SVG trees
334 might be created by separate SVG generators, efficiently storing any
335 common images just once.
336 </p>
337 <source>class MySVGGenerator {
338
339 // The image handler will write all images files to "res/images".
340 <strong> private static ImageHandler ihandler =
341 new CachedImageHandlerPNGEncoder("res/images", null);</strong>
342
343 public void generateSVG(JPanel myCanvas, OutputStream outStream) {
344 DOMImplementation domImpl =
345 GenericDOMImplementation.getDOMImplementation();
346 Document myFactory = domImpl.createDocument(svgNS, "svg", null);
347 SVGGeneratorContext ctx =
348 SVGGeneratorContext.createDefault(myFactory);
349 <strong>ctx.setGenericImageHandler(ihandler);</strong>
350
351 SVGGraphics2D svgGenerator = new SVGGraphics2D(ctx, false);
352
353 // Create the SVG DOM tree.
354 myCanvas.paintComponent(svgGenerator);
355
356 Writer out = new OutputStreamWriter(outStream, "UTF-8");
357 svgGenerator.stream(out, true);
358 }
359 }</source>
360
361 </section>
362
363 <section>
364 <title>Customizing the generated SVG style</title>
365 <p>
366 Your needs in matter of styling may be different from the two
367 provided options (XML presentation attributes or CSS inline
368 stylesheets). For example, you may want to put the CSS properties in
369 a SVG <code>style</code> element section and reference them through
370 the class attribute. In this case you will need to define a new
371 <a class="class" href="../javadoc/org/apache/batik/svggen/StyleHandler.html">StyleHandler</a>
372 as below.
373 </p>
374 <source>public class StyleSheetStyleHandler implements StyleHandler {
375
376 // The CDATA section that holds the CSS stylesheet.
377 private CDATASection styleSheet;
378
379 // Build the handler with a reference to the stylesheet section.
380 public StyleSheetStyleHandler(CDATASection styleSheet) {
381 this.styleSheet = styleSheet;
382 }
383
384 public void setStyle(Element element, Map styleMap,
385 SVGGeneratorContext generatorContext) {
386 Iterator iter = styleMap.keySet().iterator();
387
388 // Create a new class in the style sheet.
389 String id = generatorContext.getIDGenerator().generateID("C");
390 styleSheet.appendData("."+ id +" {");
391
392 // Append each key/value pair.
393 while (iter.hasNext()) {
394 String key = (String) iter.next();
395 String value = (String) styleMap.get(key);
396 styleSheet.appendData(key + ":" + value + ";");
397 }
398
399 styleSheet.appendData("}\n");
400
401 // Reference the stylesheet class on the element to be styled.
402 element.setAttributeNS(null, "class", id);
403 }
404 }</source>
405 <p>
406 Then you can create and use an <code>SVGGraphics2D</code> with a
407 correctly configured <code>SVGGeneratorContext</code>.
408 </p>
409 <source>
410 // Configure the SVGGraphics2D for a given Document myFactory.
411 SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(myFactory);
412 CDATASection styleSheet = myFactory.createCDATASection("");
413 ctx.setStyleHandler(new StyleSheetStyleHandler(styleSheet));
414 SVGGraphics2D g2d = new SVGGraphics2D(ctx, false);
415
416 // Use the g2d to draw (e.g., component.paint(g2d)).
417
418 // Add a stylesheet to the definition section.
419 SVGSVGElement root = (SVGSVGElement) g2d.getRoot();
420 Element defs = root.getElementById(SVGSyntax.ID_PREFIX_GENERIC_DEFS);
421 Element style = myFactory.createElementNS
422 (SVGSyntax.SVG_NAMESPACE_URI, SVGSyntax.SVG_STYLE_TAG);
423 style.setAttributeNS(null, SVGSyntax.SVG_TYPE_ATTRIBUTE, "text/css");
424 style.appendChild(styleSheet);
425 defs.appendChild(style);
426
427 // Dump the root content to a given Writer myWriter.
428 g2d.stream(root, myWriter);</source>
429 </section>
430
431 <section>
432 <title>Extending Paint object to SVG element translation</title>
433 <p>
434 The <code>SVGGraphics2D</code> is able to generate SVG elements for
435 generic Java 2D objects, but you sometimes have your own classes such
436 as implementations of the Java 2D
437 <a class="class" href="http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Paint.html">Paint</a>
438 interface. In this case, you will need to write an
439 <a class="class" href="../javadoc/org/apache/batik/svggen/ExtensionHandler.html">ExtensionHandler</a>
440 that you will set on your <code>SVGGeneratorContext</code>.
441 </p>
442 <p>
443 In the following example we define the first draft of an
444 <code>ExtensionHandler</code> allowing to translate a Batik
445 implementation of the <code>Paint</code> interface named
446 <a class="class" href="../javadoc/org/apache/batik/ext/awt/LinearGradientPaint.html">LinearGradientPaint</a>.
447 </p>
448 <source>class MyExtensionHandler extends DefaultExtensionHandler {
449
450 public SVGPaintDescriptor handlePaint(Paint paint,
451 SVGGeneratorContext generatorCtx) {
452 if (paint instanceof LinearGradientPaint) {
453 LinearGradientPaint gradient = (LinearGradientPaint) paint;
454
455 // Create a new SVG 'linearGradient' element to represent the
456 // LinearGradientPaint being used.
457 String id = generatorCtx.getIDGenerator().generateID("gradient");
458 Document doc = generatorCtx.getDOMFactory();
459 Element grad = doc.createElementNS
460 (SVGSyntax.SVG_NAMESPACE_URI,
461 SVGSyntax.SVG_LINEAR_GRADIENT_TAG);
462
463 // Set the relevant attributes on the 'linearGradient' element.
464 grad.setAttributeNS(null, SVGSyntax.SVG_ID_ATTRIBUTE, id);
465 grad.setAttributeNS(null, SVGSyntax.SVG_GRADIENT_UNITS_ATTRIBUTE,
466 SVGSyntax.SVG_USER_SPACE_ON_USE_VALUE);
467 Point2D pt = gradient.getStartPoint();
468 grad.setAttributeNS(null, "x1", pt.getX());
469 grad.setAttributeNS(null, "y1", pt.getY());
470 pt = gradient.getEndPoint();
471 grad.setAttributeNS(null, "x2", pt.getX());
472 grad.setAttributeNS(null, "y2", pt.getY());
473
474 switch (gradient.getCycleMethod()) {
475 case MultipleGradientPaint.REFLECT:
476 grad.setAttributeNS
477 (null, SVGSyntax.SVG_SPREAD_METHOD_ATTRIBUTE,
478 SVGSyntax.SVG_REFLECT_VALUE);
479 break;
480 case MultipleGradientPaint.REPEAT:
481 grad.setAttributeNS
482 (null, SVGSyntax.SVG_SPREAD_METHOD_ATTRIBUTE,
483 SVGSyntax.SVG_REPEAT_VALUE);
484 break;
485 // 'pad' is the default...
486 }
487
488 // Here we should write the transform of the gradient
489 // in the transform attribute...
490
491 // Here we should write the stops of the gradients as
492 // children elements...
493
494 return new SVGPaintDescriptor
495 ("url(#" + ref + ")", SVGSyntax.SVG_OPAQUE_VALUE, grad);
496 } else {
497 // Let the default mechanism do its job.
498 return null;
499 }
500 }
501 }</source>
502 <p>
503 You should then set it on the <code>SVGGeneratorContext</code> by
504 using the <code>setExtensionHandler</code> method.
505 </p>
506 <source>SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(myFactory);
507 ctx.setExtensionHandler(new MyExtensionHandler());
508 SVGGraphics2D g2d = new SVGGraphics2D(ctx, false);</source>
509 </section>
510 </section>
511
512 <section id="view">
513 <title>How to view the generated SVG document</title>
514
515 <p>
516 The following code example illustrates how to view the SVG content
517 generated
518 by an <code>SVGGraphics2D</code> object.</p>
519
520 <source>import java.awt.*;
521 import java.awt.geom.*;
522
523 import javax.swing.*;
524
525 import org.apache.batik.swing.*;
526 import org.apache.batik.svggen.*;
527 import org.apache.batik.dom.svg.SVGDOMImplementation;
528
529 import org.w3c.dom.*;
530 import org.w3c.dom.svg.*;
531
532 public class ViewGeneratedSVGDemo {
533
534 public static void main(String[] args) {
535 // Create an SVG document.
536 DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
537 String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
538 SVGDocument doc = (SVGDocument) impl.createDocument(svgNS, "svg", null);
539
540 // Create a converter for this document.
541 SVGGraphics2D g = new SVGGraphics2D(doc);
542
543 // Do some drawing.
544 Shape circle = new Ellipse2D.Double(0, 0, 50, 50);
545 g.setPaint(Color.red);
546 g.fill(circle);
547 g.translate(60, 0);
548 g.setPaint(Color.green);
549 g.fill(circle);
550 g.translate(60, 0);
551 g.setPaint(Color.blue);
552 g.fill(circle);
553 g.setSVGCanvasSize(new Dimension(180, 50));
554
555 // Populate the document root with the generated SVG content.
556 Element root = doc.getDocumentElement();
557 g.getRoot(root);
558
559 // Display the document.
560 JSVGCanvas canvas = new JSVGCanvas();
561 JFrame f = new JFrame();
562 f.getContentPane().add(canvas);
563 canvas.setSVGDocument(doc);
564 f.pack();
565 f.setVisible(true);
566 }
567 }</source>
568 </section>
569 </body>
570 </document>