XML - Managing Data Exchange/SVG

What is SVG?
Based on XML, Scalable Vector Graphics (SVG) is an open-standard vector graphics file format and Web development language created by the W3C, and has been designed to be compatible with other W3C standards such as DOM, CSS, XML, XSLT, XSL, SMIL, HTML, and XHTML. SVG enables the creation of dynamically generated, high-quality graphics from real-time data. SVG allows you to design high-resolution graphics that can include elements such as gradients, embedded fonts, transparency, animation, and filter effects.

SVG files are different from raster or bitmap formats, such as GIF and JPEG that have to include every pixel needed to display a graphic. Because of this, GIF and JPEG files tend to be bulky, limited to a single resolution, and consume large amounts of bandwidth. SVG files are significantly smaller than their raster counterparts. Additionally, the use of vectors means SVG graphics retain their resolution at any zoom level. SVG allows you to scale your graphics, use any font, and print your designs, all without compromising resolution. SVG is XML-based and written in plain text, meaning SVG code can be edited with any text editor. Additionally, SVG offers important advantages over bitmap or raster formats such as:


 * Zooming: Users can magnify their view of an image without negatively affecting the resolution.
 * Text stays text: Text remains editable and searchable. Additionally, any font may be used.
 * Small file size: SVG files are typically smaller than other Web-graphic formats and can be downloaded more quickly.
 * Display independence: SVG images always appear crisp on your screen, no matter the resolution. You will never experience “pixelated” images.
 * Superior color control: SVG offers a palette of 16 million colors.
 * Interactivity and intelligence: Since SVG is XML-based, it offers dynamic interactivity that can respond to user actions.

Data-driven graphics
Because it is written in XML, SVG content can be linked to back-end business processes, databases, and other sources of information. SVG documents use existing standards such as Cascading Stylesheets (CSS) and Extensible Stylesheet Language (XSL), enabling graphics to be easily customized. This results in:


 * Reduced maintenance costs: Because SVG allows image attributes to be changed dynamically, it eliminates the need for numerous image files. SVG allows you to specify rollover states and behaviors via scriptable attributes. Complex navigation buttons, for example, can be created using only one SVG file where normally this would require multiple raster files.
 * Reduced development time: SVG separates the three elements of traditional Web workflow – content (data), presentation (graphics), and application logic (scripting). With raster files, entire graphics must be completely recreated if changes are made to content.
 * Scalable server solutions: Both the client and the server can render SVG graphics. Because the “client” can be utilized to render the graphic, SVG can reduce server loads. Client-side rendering can enhance the user-experience by allowing users to “zoom in” on an SVG graphic. Additionally, the server can be used to render the graphic if the client has limited processing resources, such as a PDA or cell phone. Either way the file is rendered, the source content is the same.
 * Easily updated: SVG separates design from content, allowing easy updates to either.

Interactive graphics
SVG allows you to create Web-based applications, tools, or user interfaces. Additionally, you can incorporate scripting and programming languages such as JavaScript, Java, and Visual Basic. Any SVG element can be used to modify or control any other SVG or HTML element. Because SVG is text based, the text inside graphics can be translated for other languages quickly, which simplifies localization efforts. Additionally, if there is a connection to a database, SVG allows drill-down functionality for charts and graphs. This results in:


 * Improved end user experience: Users can input their own data, modify data, or even generate new graphics from two or more data sources.
 * In SVG, text is text: As mentioned previously, SVG treats text as text. This makes SVG-based graphics searchable by search engines.
 * SVG can create SVG: Enterprise applications such as an online help feature can be developed.

Personalized graphics
SVG can be targeted to people to overcome issues of culture, accessibility, and aesthetics, and can be customized for many audiences and demographic groups. SVG can also be dynamically generated using information gathered from databases or user interaction. The overall goal is to have one source file, which transforms seamlessly in a wide variety of situations. This results in:


 * One source, customized appearances: SVG makes it possible to change color and other properties based on aesthetics, culture, and accessibility issues. SVG can use stylesheets to customize its appearance for different situations.
 * Internationalization, localization: SVG supports Unicode characters in order to effectively display text in many languages and fashions – vertically, horizontally, and bi-directionally.
 * Utilizing existing standards: SVG works seamlessly with stylesheets in order to control presentation. Cascading Stylesheets (CSS) can be used for typical font characteristics as well as for other SVG graphic elements. For example, you can control the stroke color, fill color, and fill opacity of an element from an external stylesheet.

SVG vs. Macromedia Flash
Macromedia has been the dominant force behind vector-based graphics on the web for the last 10 years. It is apparent, however, that SVG provides alternatives to many of the functions of Flash and incorporates many others. The creation of vector-based graphical elements is the base structure of both SVG and Flash. Much like Flash, SVG also includes the ability to create time-based animations for each element and allows scripting of elements via DOM, JavaScript, or any other scripting language that the SVG viewer supports. Many basic elements are available to the developer, including elements for creating circles, rectangles, lines, ellipses, polygons, and text. Much like HTML, elements are styled with Cascading Stylesheets (CSS2) using a style element or directly on a particular graphical element via the style attribute. Styling properties may also be specified with presentation attributes. For each CSS property applicable to an element, an XML attribute specifying the same styling property can also be used. There is an on going debate about whether Flash or SVG is better for web development There are advantages to both, it usually comes down to the situation.

Flash Advantages:


 * Use Flash if you want to make a Flash-like website – replicating the same effect using SVG is hard.
 * Use Flash if you want complex animations, or complex games (SVG's built in SMIL animation engine is extremely processor intensive).
 * Use Flash if your users will not be so computer literate, for instance a children's site, or a site appealing to a wide audience.
 * Use Flash if sound is important – SVG/SMIL supports sound, but it's pretty basic.
 * Use Flash if you prefer WYSIWYG to script.

SVG advantages:


 * It's fully scriptable, using a DOM1 interface and JavaScript. That means you can start with an empty SVG image, and build it up using JavaScript.
 * SVG can easily be created by ASP, PHP, Perl, etc and extracted from a database.
 * It has a built-in ECMA-script (JavaScript) engine, so you don't have to code per browser, and you don't need to learn Flash's action-script.
 * SVG is XML, meaning it can be read by anything that can read XML . Flash can use XML, but needs to convert it before use.
 * This also allows SVG to be transformed through an XSLT stylesheet/parser.
 * SVG supports standard CSS1 stylesheets.
 * Text used in SVG remains selectable and searchable.
 * You only need a text editor to create SVG, as opposed to buying Flash.
 * SVG is an web real standard (not just “de facto”), supported by various different programs, some of which are free software (and thus available for most free computer operating systems).

Why use SVG?
SVG is emerging through the efforts of the W3C and its members. It is open source and as such does not require the use of proprietary languages and development tools as does Macromedia Flash. Because it is XML-based, it looks familiar to developers and allows them to use existing skills. SVG is text based and can be learned by leveraging the work (or code) of others, which significantly reduces the overall learning curve. Additionally, because SVG can incorporate JavaScript, DOM, and other technologies, developers familiar with these languages can create graphics in much the same way. SVG is also highly compatible because it works with HTML, GIF, JPEG, PNG, SMIL, ASP, JSP, and JavaScript. Finally, graphics created in SVG are scalable and do not result in loss of quality across platforms and devices. SVG can therefore be used for the Web, in print, as well as on portable devices while retaining full quality.

The Adobe SVG Viewer
The Adobe SVG Viewer is available as a downloadable plug–in that allows SVG to be viewed on Windows, Linux and Mac operating systems in all major browsers including Internet Explorer (versions 4.x, 5.x, 6.x), Netscape (versions 4.x, 6.x), and Opera in Internet Explorer and Netscape.

The Adobe SVG Viewer is the most widely deployed SVG Viewer and it supports almost all of the SVG Specification including support for the SVG DOM, animation and scripting.

Features of the Adobe SVG Viewer Click the right mouse button (CTRL-Key + mouse click in Mac) over your SVG image to get a context menu. The context menu gives you several options, which can all be accessed utilizing the menu itself or “hotkeys”:

Table 1: Features of the Adobe SVG Viewer

SMIL
The Synchronized Multimedia Integration Language (SMIL, pronounced “smile”) enables simple authoring of interactive audiovisual presentations. SMIL is typically used for “rich media”/multimedia presentations which integrate streaming audio and video with images, text or any other media type. SMIL is an easy-to-learn HTML-like language, and many SMIL presentations are written using a simple text-editor. SMIL can be used with XML to enable video and sound when viewing a SVG.

Attention Microsoft Windows Mozilla users!
The Seamonkey and Mozilla Firefox browsers have SVG support enabled natively. If desired, the Adobe SVG Viewer plugin will work with Mozilla Firefox, or the Seamonkey browser. Webkit based browsers also have some SVG support natively.

Native SVG (Firefox)
The Mozilla SVG implementation is a native SVG implementation. This is as opposed to plug-in SVG viewers such as the Adobe viewer (which is currently the most popular SVG viewer).

Some of the implications of this are:


 * Mozilla can handle documents that contain SVG, MathML, XHTML, XUL, etc. all mixed together in the same 'compound' document. This is being made possible by using XML namespaces.
 * Mozilla is 'aware' of the SVG content. It can be accessed through the SVG DOM (which is compatible with the XML DOM) and manipulated by Mozilla's script engine.
 * Other Mozilla technologies can be used with SVG. XBL coupled with SVG is a particular interesting combination. It can be used to create graphical widgets (I wonder when we'll see the first SVG-based chrome!) or extend Mozilla to recognize other specialized languages such as e.g. CML (chemical markup language). There are samples of these kinds of more advanced usage patterns on http://croczilla.com/svg/.

rsvg-view
rsvg-view program is a part of the librsvg package. It may be used as the default svg opener. It can resize svgs and export them to png which is often the only thing one needs to do with an svg file.

Example : rsvg-view-3 name.svg

How to do it
One can use 4 groups of programs :


 * general text editors, like Notepad ++ (with XML syntax highlithning)
 * specialized svg editors
 * programs that can exports svg (like gnuplot, Maxima CAS)
 * own programs to create svg files directly thru concatenate of strings

SVG editors
As you can see from the previous example of a path definition, SVG files are written in an extremely abbreviated format to help minimize file size. However, they can be very difficult to write depending on the complexity of your image. There are SVG editor tools that can help make this task easier. Some of these tools are:

Table 3: SVG Editors

C
Here is example in C :

Haskell
Haskel code : lavaurs' algorithm in Haskell with SVG output by Claude Heiland-Allen

Matlab
Based on code by Guillaume JACQUENOT :

Lisp
One can use cl-svg library or your own procedure.

Maxima
BeginSVG(file_name,cm_width,cm_height,i_width,i_height):= block( destination : openw (file_name), printf(destination, "~%"), printf(destination,"~%", cm_width,cm_height,i_width,i_height), return(destination) ); CircleSVG(dest,center_x,center_y,_radius):=printf(dest,"~%", center_x,center_y,_radius); CloseSVG(destination):= ( printf(destination," ~%"), close (destination) ); /* */ cmWidth:10; cmHeight:10; iWidth:800; iHeight:600; radius:200; centerX:400; centerY:300; f_name:"b.svg"; /* --*/ f:BeginSVG(f_name,cmWidth,cmHeight,iWidth,iHeight); CircleSVG(f,centerX,centerY,radius); CloseSVG(f);

Python
One can use a prepared library, or wrap the svg code in single quotes. def svg_page: """ Function to write test code for a stub svg code page The raw code that uses double-quotes is captured by single quotes To become a python text string""" page='\n\n   \n \n' return page

def write_page(page, title): """ Function to write the svg code to disk """ filename = title + ".svg" f = open(filename, "w") f.write(page)

write_page (svg_page, "My svgstub")

Getting started
Because it is based on XML, SVG follows standard XML conventions. Every SVG file is contained within an tag as its parent element. SVG can be embedded within a parent document or used independently. For example, the following shows an independent SVG document:

Exhibit 1: Creating a SVG

The first line declares that the code that follows is XML. Note the “standalone” attribute. This denotes that this particular file does not contain enough processing instructions to function alone. In order to attain the required functionality it needs to display a particular image, the SVG file must reference an external document.

The second line provides a reference to the Document Type Definition, or DTD. As mentioned in Chapter 7: XML Schemas, the DTD is an alternate way to define the data contained within an XML instanced document. Developers familiar with HTML will notice the DTD declaration is similar to that of an HTML document, but it is specific for SVG. For more information about DTDs, visit: http://www.w3schools.com/dtd/dtd_intro.asp

Hint: Many IDEs (ex. NetBeans) do not have SVG “templates” built in to the tool. Therefore, it may be easier to use a simple text editor when creating SVG documents. Once you have an SVG Viewer installed, you should then be able to open and view your SVG document with any browser. When creating your SVG documents, remember to:


 * Declare your document as an XML file
 * Make sure your SVG document elements are between element tags, including the SVG namespace declaration.
 * Save your file with a .svg file extension.
 * It is not necessary do include a DOCTYPE statement, which includes information to identify this as an SVG document (since SVG 1.2 there is also not more such).

The element on the second line defines the SVG document, and can specify, among other things, the user coordinate system, and various CSS unit specifiers. Just like with XHTML documents, the document element must include a namespace declaration to declare the element as being a member of the relevant namespace (in this case, the SVG namespace). Within the element, there can be three types of drawing elements: text, shapes, and paths.

Text
The following is an example of the text element: Exhibit 2: Using text with SVG

The element specifies: 1) that white space within text elements will be retained, 2) the width and height of the SVG document — particularly important for specifying print output size. In this example, the text is positioned in a 5.5 inches wide by .5 inches tall image area. The “y” attribute on line 5 declares that the text element’s baseline is 15 pixels down from the top of the SVG document. An omitted “x” attribute on a text element implies an x coordinate of 0.

Because SVG documents use a W3C DTD, you can use the W3C Validator to validate your document. Notice that the “style” attribute is used to describe the presentation of the text element. The text could equivalently have been given a red color by use of a presentation attribute fill="red".

Shapes
SVG contains the following basic shape elements:


 * Rectangles
 * Circles
 * Ellipses
 * Lines
 * Polylines
 * Polygons

These basic shapes, along with “paths” which are covered later in the chapter, constitute the graphic shapes of SVG. In this introduction to SVG, we will only cover some of the shapes here.

Rectangles
The element defines a rectangle which is axis-aligned with the current user coordinate system, the coordinate system that is currently active and which is used to define how coordinates and lengths are located and computed on the current canvas. Rounded rectangles can be created by setting values for the rx and ry attributes.

The following example produces a blue rectangle with its top left corner aligning with the top left corner of the image area. This uses the default value of "0" for the x and y attributes.

Exhibit 3: Creating a rectangle in SVG

It will produce this result:



Circles
A circle element requires three attributes: cx, cy, and r. The 'cx’ and 'cy’ values specify the location of the center of the circle while the 'r’ value specifies the radius. If the 'cx’ and 'cy’ attributes are not specified then the circle's center point is assumed to be (0, 0). If the 'r’ attribute is set to zero then the circle will not appear. Unlike 'cx’ and 'cy’, the 'r’ attribute is not optional and must be specified. In addition the keyword stroke creates an outline of the image. Both the width and the color can be changed.

Exhibit 4: Creating a circle in SVG

It will produce this result:



Polygons
A polygon is any geometric shape consisting of three or more sides. The 'points' attributes describes the (x,y) coordinates that specify the corners points of the polygon. For this specific example, there are three points which indicate that a triangle will be produced.

Exhibit 5: Creating a Polygon in SVG

It will produce this result:



Paths
Paths are used to draw your own shapes in SVG, and are described using the following data attributes:

Table 2: SVG Paths

The following example produces the shape of a triangle. The “M” indicates a “moveto” to set the first point. The “L” indicates “lineto” to draw a line from “M” to the “L” coordinates. The “Z” indicates a “closepath”, which draws a line from the last set of L coordinates back to the M starting point.

Exhibit 6: Creating paths in SVG

It produces this result:



Validation
After creating file check its code with the W3C Validatior

Optimisation
Even code without errors can be improved. For example grouping elements makes code shorter.

Including SVG in HTML
There are three methods to include SVG in an HTML document. Basically, the SVG document is first created as a stand-alone file. It is then referenced in the HTML document using one of the following commands:

Table 4: Including SVG in HTML

Embed
The syntax is as follows: Exhibit 7: Embedding SVG into HTML using keyword embed

An additional attribute, “pluginspage”, can be set to the URL where the plug-in can be downloaded:

Object
The syntax is as follows and conforms to the HTML 4 Strict specification: Exhibit 8: Embedding SVG into HTML using keyword object

Between the opening and the closing &lt;object> tags, information for browsers that do not support objects can be added:

Unfortunately some browsers such as Netscape Navigator 4 do not show this alternative content if the type attribute has been set to something other than text/html.

Iframe
The syntax is as follows and conforms to the HTML 4 Transitional specification: Exhibit 9: Embedding SVG into HTML using keyword iframe

Between the opening and the closing &lt;iframe> tags, information for browsers that do not support iframes can be added:

Creating 3D SVG images
Section by Charles Gunti, UGA Master of Internet Technology Program, Class of 2007

Sometime we may want to view an SVG image in three dimensions. For this we will need to change the viewpoint of the graphic. So far we have created two dimensional graphics, such as circles and squares. Those exist on a simple x, y plane. If we want to look at something in three dimensions we have to add the z coordinate plane. The z plane is already there, but we are looking at it straight on, so if data is changed on z it doesn't look any different to the viewer. We need to add another parameter to the data file, the z parameter.

Once we have the data we will use XSLT to create the SVG file. The SVG stylesheet is the same as other stylesheets, but we need to ensure an SVG file is created during the transformation. We call the SVG namespace with this line in the declarations:

xmlns="http://www.w3.org/2000/svg

Another change we should make from previous examples is to change the origin of (0, 0). We change the origin in this example because some of our data is negative. The default origin is at the upper left corner of the SVG graphic. Negative values are not displayed because, unlike traditional coordinate planes, negative values are above positive values. To move the origin we simply add a line of code to the stylesheet. Before going over that line, let's look at The g element. The container element, g, is used for grouping related graphics elements. Here, we'll use g to group together our graphical elements and then we can apply the transform. Here is how we declare g and change the origin to a point 300 pixels to the right and 300 pixels down:

graphical elements

SVG transformations are pretty simple, until it comes to changing the viewpoint. SVG has features such as rotating and skewing the image in two dimensions, but it cannot rotate the coordinate system in three dimensions. For that we will need to use some math and a little Java. When rotating in three dimensions two rotations need to be made, one around the y axis, and another around the x axis. The first rotation will be around the y axis and the formula will look like this:

$$z' = z \cdot \cos(-Az) - x \cdot \sin(-Az)$$ Az is the angle the z axis will be rotated

$$x' = z \cdot \sin(-Az) - x \cdot \cos(-Az)$$

$$y' = y \,$$ y will not change because we are rotating around the y axis

The second rotation will be around the x axis. Keep in mind that one rotation has already been made, so instead of using x, y, and z values we need to use x', y', and z' (x-prime, y-prime and z-prime) found in the last rotation. The formula will look like this:

z" = z'*cos(Ay) – y'*sin(Ay) Ay is the angle of rotation on the y axis

y" = z'*sin(Ay) + y'*cos(Ay)

x" = x' Remember we are rotating around the x axis, so this does not change

Remember from trig class the old acronym SOH CAH TOA? This means

Sin = Opposite/Hypotenuse Cos = Adjacent/Hypotenuse Tan = Opposite/Adjacent

And we use those functions to find the angles needed for our rotations. Based of the previous two formulas we can make the following statements about Az and Ay:

tan(Az) = Xv/Zv

sin(Ay) = Yv/sqrt(Xv2 + Yv2 + Zv2)

With so many steps to take to make the rotation we should drop all of this information into a Java class, then call the class in the stylesheet. The Java class should have methods for doing all of the calculations for determining where the new data points will go once the rotation is made. Creating that java class is beyond the scope of this section, but for this example I'll call it ViewCalc.class.

Now that we can rotate the image, we need to integrate that capability into the transformation. We will use parameters to pass viewpoints into the stylesheet during the transformation. The default viewpoint will be (0, 0, 0) and is specified on the stylesheet like so:

Exhibit 10: 3D images with SVG

Java now needs to be added to the stylesheet so the processor will know what methods to call. Two lines are added to the namespace declarations:

Notice the exclude-result-prefixes="java" line. That line is added so things in the stylesheet with the java: prefix will be processed, not output. Be sure to have the ViewCalc class in the CLASSPATH or the transformation will not run.

The final step is to call the methods in the ViewCalc class from the stylesheet. For example:

Finally we pass new parameters and run the XSL transformation to create the SVG file with a different viewpoint.

Demos
The following table provides a sampling of SVG documents that demonstrate varying degrees of functionality and complexity:

Table 5: SVG Demos

The Basic demo demonstrates the effects of zooming, panning, and anti-aliasing (high quality).

The Fills demo demonstrates the effects of colors and transparency. The black circle is drag-able. Simply click and drag the circle within the square to see the changes.

The HTML, JS, Java Servlet demo describes an interactive, database-driven, seating diagram, where chairs represent available seats for a performance. If the user moves the mouse pointer over a seat, it changes color, and the seat detail (section, row, and seat number) and pricing are displayed. On the client side of the application, SVG renders the seating diagram and works with JavaScript to provide user interactivity. The SVG application is integrated with a server-side database, which maintains ticket and event availability information and processes ticket purchases. The Java Servlet handles form submission and updates the database with seat purchases.

The HTML, JS, DOM demo shows how SVG manages and displays data, generating SVG code from data on the fly. Although this kind of application can be written in a variety of different ways, SVG provides client-side processing to maintain and display the data, reducing the load on the server as well as overall latency. Using the DOM, developers can build documents, navigate their structure, and add, modify, or delete elements and content.

The PHP, MySQL demo shows the use of database driven SVG generation utilizing MySQL. It randomly generates a map of a European country. Each time you reload the page you will see a different country.

The HTML5, ANGULARJS, PostGreSQL demo shows how to create a SVG, then integrate variable data into the SVG & spool a variable data pdf.

Exercises

 * 1) Download and install the Adobe SVG Viewer. Once the Adobe SVG Viewer has been installed, go to this page to test that the install was successful: http://www.adobe.com/svg/viewer/install/svgtest.html
 * 2) * If your primary browser is Internet Explorer, you can download version 3.0 which is fully supported by Adobe and can be accessed at http://www.adobe.com/svg/viewer/install/main.html
 * 3) * If your primary browser is Mozilla-based, you must download the 6.0 version at http://download.adobe.com/pub/adobe/magic/svgviewer/win/6.x/6.0x38363/en/SVGView.exe
 * 4) ** After it has been installed you must copy the NPSVG6.dll and NPSVG6.zip files to your browser's plug-ins folder. These files are normally located in C:\Program Files\Common Files\Adobe\SVG Viewer 6.0\Plugins\.
 * 5) Create your own stand-alone SVG file to produce an image containing a circle within a rectangle.
 * 6) Create your own stand-alone SVG file. Use 3 circles and 1 path element to create a yellow smiley face with black eyes and a black mouth. Use a text element so that the message “Have a nice day!” appears below the smiley face.
 * 7) * Hint: Because elements can be difficult to write, here is a sample path you can utilize:
 * 8) * 