Click or drag to resize
AB4D logo

ReaderSvg Class

ReaderSvg is a class library for reading svg and svgz files and converting its elements into WPF elements. For usage in XAML see SvgViewbox and SvgDrawing.
Inheritance Hierarchy
SystemObject
  Ab2dReaderSvg

Namespace:  Ab2d
Assembly:  Ab2d.ReaderSvg (in Ab2d.ReaderSvg.dll) Version: 7.1.7295.1040
Syntax
C#
public class ReaderSvg

The ReaderSvg type exposes the following members.

Constructors
  NameDescription
Public methodReaderSvg
Constructor of ReaderSvg ReaderSvg is a class library for reading svg files and converting its elements into WPF elements
Top
Properties
  NameDescription
Public propertyAddHiddenElements
Gets or sets a Boolean that specifies if hidden elements are read. Default value is true.
Public propertyCode exampleAddNewCanvasForTransformations
If true (default = false) transformations on elements are not set on the element itself but are set to a new canvas and the element is added as its parent. This property is added for backward compatibility with versions 2.3 and older.
Public propertyAutoSize
When AutoSize is false the size of read svg objects is determined by the width and height defined in the svg header. For example when svg header define the size as Letter, than the read svg objects will retain the position within the letter area. When AutoSize is set to true (by default), the size defined in svg header is ignored. Instead the size of the actual svg content is calculated so that the read objects do not have any empty area around them. The calculated or read size of svg elements can be read from SvgBounds property.
Public propertyBitmapImages
Gets list of all bitmap images that are defined in svg file and cannot be converted to vector elements.
Public propertyConvertTransformationsToMatrixTransform
Gets or sets a Boolean that specifies if all transformations are converted to MatrixTransform. Default values is false that preserves the type of transformation defined in svg file.
Public propertyDescription
Description defined in svg file
Public propertyFlattenHierarchies
Gets or sets a Boolean that specifies if all child groups (Canvases or DrawingGroup) are removed and all elements are placed under the root group. The group transformations are added to child objects so that the rendered drawing looks the same. The exception to the removed groups are the groups that define clipping.
Public propertyHasCustomProperties
Gets a Boolean that specifies if the read svg files has some custom properties defined.
Public propertyHeight
Gets or sets the Height of the returned Viewbox element
Public propertyHeightInUnits
Gets a string that represents height of svg element in specified units (for example "2cm" or "2in"). If the read sgv element does not specify units, than this value is null.
Public propertyInnerCanvas
Gets the inner canvas without the Viewbox control. See also SvgBounds.
Public propertyInnerHeight Obsolete.
Gets Height of all read svg elements
Public propertyInnerWidth Obsolete.
Gets the Width of all read svg elements
Public propertyStatic memberCode exampleInstance
Gets static instance of Ab2d.ReaderSvg so you do not need to create your own instance of it.
Public propertyIsCorrectingNamesForWpf
Gets or sets a Boolean that specifies if the names are corrected so that they can be used in XAML. The following rule is applied in this case: name must start with a letter or underscore and can contain only letters, digits, or underscores. If true, then invalid characters are replaced with underscore. If false, then the NamedObjects dictionary contains unchanged names, but the GetXaml method still corrects the names. Default value is true (for backwards compatibility).
Public propertyLastReadImage
Gets the lastly read svg as WPF's Image element (used when ReadGeometry is used, when using Read method see LastReadViewbox)
Public propertyLastReadViewbox
Gets the lastly read svg as WPF's Viewbox element (used when Read is used, when using ReadGeometry method see LastReadImage)
Public propertyStatic memberLicenseInfo
License information
Public propertyMakeNamesUnique
Gets or sets a Boolean that specifies if ReaderSvg adds index text to the names of objects that were already used to make them unique. For example if svg object has a name "SvgObject" and if the second svg object has the same name, the second svg object will be named "SvgObject2". Default value is true.
Public propertyNamedObjects
Dictionary with elements ids as keys and its appropriate objects as values Ids (keys) can be defined in a drawing application
Public propertyNamedObjectsSource
Gets or sets one of the ReaderSvgNamedObjectsSourceType as the source to get the object's name. Default value is NamedObjectsSourceType.Auto.
Public propertyOptimizeObjectGroups
Gets or sets a Boolean that specifies if groups (Canvas or DrawingGroup) are optimized in such a way that they groups that contain only one other group (Canvas or DrawingGroup) are removed. Default value is false which preserves the groups as they are defined in the original svg file.
Public propertyOptimizeStyleProcessing
Gets or sets a Boolean that specifies if ReaderSvg is using an optimized style processing that improves speed of reading svg file (default value is true).
Public propertyOverrideMiterLimit
Gets or sets a value that is used instead of the miter limit specified in the svg file. If value is 0, than the miter limit from svg file is used. Default value is 0.
Public propertyReadForeignObjects
Gets or sets a boolean that specifies if foreignObject elements in svg files are read (currently only Visio metafiles are supported). Default value is true.
Public propertyReadPathAsPathGeometry
If false (default) the path is read as StreamGeometry (better performance). If true the path is read as PathGeometry (worse performance but path can be modified).
Public propertySetNameProperty
Gets or sets a Boolean that determines if the object's Name property is set to the name defined in svg file (default value is true).
Public propertySetSvgNameToParentTransformCanvas
Gets or sets a boolean that specifies if object name is set to the Canvas that is created to contain object's transformation when the object also defines the Canvas.Left and Canvas.Top properties. Default value is false.
Public propertyShowDemoTextInEvaluation Obsolete.
ShowDemoTextInEvaluation is not used any more.
Public propertySvgBounds
Gets the bounds of the svg elements. Note: Usually svg elements does not start at (0,0) but are places in a virtual letter. To work only with svg elements so they can be sized according to the host element (for example StackPanel, Page, etc.) two Canvases and a Viewbox is used. But with SvgBounds property it is possible to get the original bounds of the svg elements. If AutoSize is set to false, the SvgBounds are get from the root svg element. Also this property makes InnerWeight and InnerHeight obsolete.
Public propertySvgCreator
Gets an application that was used to create this svg file.
Public propertySwitchElementProcessingType
Specifies which children of the svg switch element will be imported and shown. Default value is ShowFirstCollapseOthers (imports all switch children but shows only the first one; others are Collapsed).
Public propertyTitle
Title defined in svg file
Public propertyTransformCanvasNameFormatString
Gets or sets a string that specifies how the Transform Canvas that is created to contain object's transformation is named. Default value is "{0}_transform".
Public propertyTransformShapes
Gets or sets a Boolean that specifies if all shape objects (Rectangles, Ellipses, Path, Polygons, etc.) that have simple transformation (only translate or scale) or canvas position are transformed with changing their data with the specified transformation. This can remove RenderTransform, Canvas.Left and Canvas.Top from most of the shapes (exception are shapes that render transform).
Public propertyUseOldSizeMeasurement
If true than size measurement from ReaderSvg v1.2 is used - if your application depends on previous sizes of read elements than use this property. Note: Size measurement is used so svg elements can be used inside other controls - so its size is adjusted regarding to the desired size - set with Width and Height properties or by the parent element. This property will exit only in ReaderSvg v1.3
Public propertyUseOnlyInstalledFontFamilies
When UseOnlyInstalledFontFamilies is false (by default), then FontFamily is created also with font names that are not installed on the system (this preserves the original font family name when exported to XAML). When UseOnlyInstalledFontFamilies is true and font family name in svg file is not installed on the system, then Arial font family is used.
Public propertyUseSimpleText
If true text is always rendered as TextBlock - also if text is using custom strokes and fill patters. If false than in case of custom strokes and fill patterns text is converted into Path elements and the appropriate effects are applied to it. Default value is false;
Public propertyWidth
Gets or sets the Width of the returned Viewbox element
Public propertyWidthInUnits
Gets a string that represents width of svg element in specified units (for example "2cm" or "2in"). If the read sgv element does not specify units, than this value is null.
Top
Methods
  NameDescription
Public methodCode exampleGetCustomProperties(Object)
Returns a Dictionary of custom properties defined for the object with objectName (only custom properties defined in Microsoft Visio are supported).
Public methodCode exampleGetCustomProperties(String)
Returns a Dictionary of custom properties defined for the object with objectName (only custom properties defined in Microsoft Visio are supported).
Public methodCode exampleGetCustomPropertiesDataTable
Returns a System.Data.DataTable with all custom properties defined in svg file (only custom properties defined in Microsoft Visio are supported).
Public methodCode exampleGetElementsForLayerName
Returns a List of UIElements that are assigned to the layer with layerName (layers can be only defined in Microsoft Visio).
Public methodGetElementSvgText
GetElementSvgText can be called after the svg file has been read. It returns svg text of the element with with the specified elementName and elementNameType. If the element is not found, null is returned.
Public methodCode exampleGetLayerNames
Returns a List of layer names that were defined in Microsoft Visio.
Public methodGetObjectName
Gets the name of the object read with ReadSvg. This is the opposite as using NamedObjects dictionary. Returns null if object is not found or it does not have a name defined.
Public methodCode exampleGetObjectsWithCustomProperties
Returns List of objects that have custom properties defined (only custom properties defined in Microsoft Visio are supported).
Public methodCode exampleGetXaml
Gets xaml of the last read svg or svgz file with the default setting for WPF.
Public methodCode exampleGetXaml(BaseXamlWriterSettings)
Gets xaml of the last read svg or svgz.
Public methodCode exampleRead(Stream)
Reads svg file from stream - useful for reading svg files from resources. The file is read as Shapes (Canvas, Path, Ellipse, etc.).
Public methodCode exampleRead(String)
Reads svg or svgz file from file system or from online source. The file is read as Shapes (Canvas, Path, Ellipse, etc.).
Public methodCode exampleReadGeometry(Stream)
Reads svg or svgz file and returns System.Windows.Controls.Image with elements as Drawings (DrawingGeometry, EllipseGeometry, GlyphRunDrawing etc.) with no optimization.
Public methodCode exampleReadGeometry(String)
Reads svg or svgz file and returns System.Windows.Controls.Image with elements as Drawings (DrawingGeometry, EllipseGeometry, GlyphRunDrawing etc.) with no optimization.
Public methodCode exampleReadGeometry(Stream, GeometrySettings)
Reads svg or svgz file and returns System.Windows.Controls.Image with elements as Drawings (DrawingGeometry, EllipseGeometry, GlyphRunDrawing etc.).
Public methodCode exampleReadGeometry(String, GeometrySettings)
Reads svg or svgz file and returns System.Windows.Controls.Image with elements as Drawings (DrawingGeometry, EllipseGeometry, GlyphRunDrawing etc.).
Public methodCode exampleRenderToBitmap(Brush)
Renders the read svg objects into bitmap. Bitmap will have the same size as read svg object and will be rendered at 96 dpi.
Public methodCode exampleRenderToBitmap(Brush, Int32)
Renders the read svg objects into bitmap. Bitmap will have the same size as read svg object and will be rendered at dpi specified in the parameter.
Public methodCode exampleRenderToBitmap(Int32, Int32, Brush)
Renders the read svg objects into bitmap with custom width and height and at 96 dpi.
Public methodCode exampleRenderToBitmap(Int32, Int32, Int32, Brush)
Renders the read svg objects into bitmap with custom width and height and at dpi specified with parameter to the method.
Public methodTransform
Transform method transforms all the coordinates, sizes and other values in the last read Viewbox with using transformation.
Public methodTransformFromPixelsToMM
TransformFromPixelsToMM method transforms all the coordinates, sizes and other values in the last read Viewbox in such a way that it converts all units in pixels into millimeters with using specified dpi setting.
Top
Events
  NameDescription
Public eventProgressChanged
ProgressChanged event can be used to get notifications of how much the svg file has been read.
Top
Fields
  NameDescription
Public fieldAfterWpfObjectCreatedCallback
AfterWpfObjectCreatedCallback can be used to provide a way to customize WPF objects that are created with ReaderSvg from svg elements. See remarks for more info.
Public fieldBeforeWpfObjectCreatedCallback
BeforeWpfObjectCreatedCallback can be used to provide a way to create custom WPF objects from svg elements. See remarks for more info.
Public fieldGetCustomSvgElementNameCallback
GetCustomSvgElementNameCallback can be used to provide custom naming of WPF objects created from svg elements. The object names are written into NamedObjects dictionary. Note that when IsCorrectingNamesForWpf or MakeNamesUnique are true, the name can be corrected after calling the GetCustomSvgElementNameCallback. Also names used for XAML are always corrected.
Top
Remarks

Ab2d.ReaderSvg class can be used to read svg and svgz files from the code.

They can be read as Shapes with Read(String) method or as Drawing objects with ReadGeometry(String).

After the file has been read, it is possible to get the xaml of the read Viewbox or Image with GetXaml method.

If your application needs images and shapes from many svg and svgz files, it is recommended that they are stored in a ResourceDictionary. To simplify creating ResourceDictionaries a ResourceDictionaryWriter class can be used. There is also a sample Ab2d.ReaderSvg.ResourceDictionaryWriter application available to simplify this process.

When svg file was created with Microsoft Visio, than the ReaderSvg can also read custom properties and layers data from the svg file. To read more about reading custom properties see GetCustomProperties(String) method. To read more about accessing layers data see GetLayerNames method.

Examples

The following example shows the most simple use of ReaderSvg. It loads the mySample.svg file and adds it to the myStackPanel.

Viewbox sampleViewbox = Ab2d.ReaderSvg.Instance.Read(@"c:\mySample.svg");
myStackPanel.Children.Add(sampleViewbox);

The following sample shows how to read svg from Application's Resource. The ReadGeometry(String, GeometrySettings) reads svg file into Drawing objects and fully optimizes it for best performance.

Image clipartFromResource;
Ab2d.Common.ReaderSvg.GeometrySettings settings;

// gets Drawing objects optimized for best performance
// NOTE: Because of heavy optimization it is possible that some anomalies appear on the image
settings = Ab2d.Common.ReaderSvg.GeometrySettings.FullOptimization;

Uri uri = new Uri("/cliparts/mySample.svg", UriKind.Relative);
using (Stream svgStream = Application.GetResourceStream(uri).Stream)
{
    clipartFromResource = Ab2d.ReaderSvg.Instance.ReadGeometry(svgStream, settings);
}

myStackPanel.Children.Add(clipartFromResource);

The following sample reads the mySample.svg file, gets its xaml for Silverlight and saves it into a file.

var myReader = new Ab2d.ReaderSvg();

Viewbox sampleViewbox = myReader.Read(@"c:\mySample.svg");
string xaml = myReader.GetXaml(new Ab2d.Common.ReaderSvg.SilverlightXamlWriterSettings());

System.IO.File.WriteAllText(@"c:\mySample_for_Silverlight.xaml", xaml);

The next example uses the RenderToBitmap(Int32, Int32, Brush) method to render the read svg file to image with custom size and saves it to disk:

var readerSvg = new Ab2d.ReaderSvg();
readerSvg.Read(@"c:\mySample.svg");

// Render to bitmap with 1024 width - height will be set automatically so that the
// Image aspect ratio is preserved
var wpfBitmap = readerSvg.RenderToBitmap(1024, 0, Brushes.White);

var encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();
// Uncomment to save to jpg
//var encoder = new JpegBitmapEncoder();
//encoder.QualityLevel = 85;

encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(wpfBitmap));

using (var stream = System.IO.File.OpenWrite("c:\\svgImage.png"))
{
    encoder.Save(stream);
}
See Also