Thursday, July 3, 2008

Converting SVG to Xaml

It seemed to me that it makes no sense to be required to convert svg files in tools like that from the folk at http://www.wpf-graphics.com/ in order to import them directly into a wpf App. Now they do have a library that you can call but it isn't exactly open. I say the same comments from Jon Galloway from almost a year ago. Fortunately one of the commenter's on Jon's post provided a link to a xslt file that would convert between the two. From there is is a simple xslt transform away. I did end up with one catch. the xslt that was posted used another external file [color.xml] to do color mapping.




     
static System.Windows.UIElement LoadFromSVG(string fileUri)
{
// Create a transform
System.Xml.Xsl.XslCompiledTransform processor
= new System.Xml.Xsl.XslCompiledTransform();

// Creates a resolver
System.Xml.XmlResolver resolver
= new System.Xml.XmlUrlResolver();

// load the transform into the processor
System.Xml.XmlReader reader
= new System.Xml.XmlTextReader("svg2xaml.xsl");
processor.Load(
reader,
new System.Xml.Xsl.XsltSettings(true, true),
resolver);

// get the source file
System.Xml.XmlReader sourceXml
= new System.Xml.XmlTextReader(fileUri);

// get the results of the transform
StringWriter xamlFile = new StringWriter();
System.Xml.Xsl.XsltSettings.Default.EnableDocumentFunction
= true;
processor.Transform(
sourceXml,
null,
new System.Xml.XmlTextWriter(xamlFile),
resolver);

return System.Windows.Markup.XamlReader.Load(
new XmlTextReader(
new StringReader(xamlFile.ToString())))
as
System.Windows.UIElement;
}