WebKit-based SVG rasterizer

Usually you will use QSvgRenderer or QSvgWidget to show the content of SVG (Scalable Vector Graphics) files. So far, QtSvg supports SVG 1.2 Tiny static, without any DOM nor scripting supports. For a much more advanced SVG dancing, one way to do it is by using QtWebKit [1] that is available since Qt 4.4. More detailed information can be obtained by tracking the SVG status support in WebKit.

For the dojo example, here I present less-than-150-lines of code that rasterizes an SVG [2] into an image. The principle is surprisingly simple: we just use QWebView to load the SVG. To rasterize it, we create a QPainter that operates on an image then ask the main web frame to render to the image by using this painter. A little bit complication is on the scaling. To keep the code cleaner and easier to understand, this little SVG rasterizer is made to work only on SVG that has a valid size, i.e. the SVG explicitly specifies both width and height attributes. Since DOM API is not available yet in Qt 4.4, a trick which is employed here to get both attributes is by using QWebFrame::evaluateJavaScript() function [3].

Without further ado, get the code:

svn checkout svn://

As with many other vector graphics-related goodies, here is the obligatory "Tiger" screenshot (click to enlarge). On the left side is the SVG file shown inside Inkscape, on the right side is the rasterized version (using svg2png) displayed with Gwenview. Due to the said restriction (specifying width, height), the SVG is not really the same as the commonly used example, I added both the necessary height and width attributes.

Result of WebKit-based SVG rasterizer

As an exercise to the reader, modify the program so that it works with a remote file, e.g. an URL with http or ftp scheme. Hint: check for guessUrlFromString() function in the Qt 4.4 Demo Browser.

[1] However, filter effects are not fully implemented yet.
[2] .svgz is not supported
[3] Use the JavaScript console in the Web Inspector to check and play with the DOM elements and their attributes.

Blog Topics: