|
The Document Object Model (DOM)
is an API for XML documents. It defines the logical structure of documents and
the way a document is accessed and manipulated. This paper shows how to create
an SVG document using the DOM API.
|
Finally, using the Document object, we are now able to
construct SVG content. Note that the document created before supports both
generic XML and SVG. Though the DOM implementation of Batik is an SVG DOM
implementation, the SVG part is not fully implemented yet so only the DOM Level
2 core functions should be used. The following example shows how to create a red
rectangle located at (10, 20), with a size of (100, 50) placed in a (400, 450)
SVG canvas.
| | | |
import org.apache.batik.dom.svg.SVGDOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
Document doc = impl.createDocument(svgNS, "svg", null);
// get the root element (the svg element)
Element svgRoot = doc.getDocumentElement();
// set the width and height attribute on the root svg element
svgRoot.setAttributeNS(null, "width", "400");
svgRoot.setAttributeNS(null, "height", "450");
// create the rectangle
Element rectangle = doc.createElementNS(svgNS, "rect");
rectangle.setAttributeNS(null, "x", "10");
rectangle.setAttributeNS(null, "y", "20");
rectangle.setAttributeNS(null, "width", "100");
rectangle.setAttributeNS(null, "height", "50");
rectangle.setAttributeNS(null, "style", "fill:red");
// attach the rectangle to the svg root element
svgRoot.appendChild(rectangle);
| | | | |
The example given has the following equivalent SVG.
| | | |
<svg width="400" height="450">
<rect x="10" y="20" width="100" height="50" style="fill:red"/>
</svg>
| | | | |
|
| | | | Creating a Document from an SVG file | | | | |
Batik provides several ways to use an SVG DOM tree. Two modules can be
immediately used to render your SVG document.
JSVGCanvas -
The JSVGCanvas is a swing component that can display SVG
document. A SVG document can be specified using a URI or an SVG DOM tree (using
the setSVGDocument method). For futher informations about the
JSVGCanvas , see the JSVGCanvas tutorial.
ImageTranscoder -
The ImageTranscoder is a transcoder which can take a URI, an
InputStream or an SVG DOM tree and produces a raster image (such JPEG, PNG or Tiff).
By creating a TranscoderInput with the SVG DOM tree, you will
be able to transform your SVG content to a raster image. For futher
informations, see the Transcoder
tutorial.
|
|
|