private void OnWindowLoaded(object sender, RoutedEventArgs e) { // 1. Create conversion options WpfDrawingSettings settings = new WpfDrawingSettings(); settings.IncludeRuntime = true; settings.TextAsGeometry = false; // 2. Select a file to be converted string svgTestFile = "Test.svg"; // 3. Create a file reader StreamSvgConverter converter = new StreamSvgConverter(settings); // 4. convert the SVG file MemoryStream memStream = new MemoryStream(); if (converter.Convert(svgTestFile, memStream)) { BitmapImage bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.StreamSource = memStream; bitmap.EndInit(); // Set the image source. svgImage.Source = bitmap; } memStream.Close(); }
/// <summary> /// Initializes a new instance of the <see cref="FileSvgConverter"/> class /// with the specified drawing or rendering settings and the saving options. /// </summary> /// <param name="saveXaml"> /// This specifies whether to save result object tree in XAML file. /// </param> /// <param name="saveZaml"> /// This specifies whether to save result object tree in ZAML file. The /// ZAML is simply a G-Zip compressed XAML format, similar to the SVGZ. /// </param> /// <param name="settings"> /// This specifies the settings used by the rendering or drawing engine. /// If this is <see langword="null"/>, the default settings is used. /// </param> public FileSvgConverter(bool saveXaml, bool saveZaml, WpfDrawingSettings settings) : base(saveXaml, saveZaml, settings) { _wpfRenderer = new WpfDrawingRenderer(this.DrawingSettings); _wpfWindow = new WpfSvgWindow(640, 480, _wpfRenderer); }
/// <summary> /// Initializes a new instance of the <see cref="SvgConverter"/> class /// with the specified drawing or rendering settings and the saving options. /// </summary> /// <param name="saveXaml"> /// This specifies whether to save result object tree in XAML file. /// </param> /// <param name="saveZaml"> /// This specifies whether to save result object tree in ZAML file. The /// ZAML is simply a G-Zip compressed XAML format, similar to the SVGZ. /// </param> /// <param name="settings"> /// This specifies the settings used by the rendering or drawing engine. /// If this is <see langword="null"/>, the default settings is used. /// </param> protected SvgConverter(bool saveXaml, bool saveZaml, WpfDrawingSettings settings) : this(settings) { _saveXaml = saveXaml; _saveZaml = SaveZaml; }
public WpfDrawingContext(bool isFragment) { _isFragment = isFragment; _drawStack = new Stack <DrawingGroup>(); _registeredIds = new HashSet <string>(StringComparer.OrdinalIgnoreCase); _settings = new WpfDrawingSettings(); }
static void Main(string[] args) { // 1. Create conversion options WpfDrawingSettings settings = new WpfDrawingSettings(); settings.IncludeRuntime = true; settings.TextAsGeometry = false; // 2. Select a file to be converted string svgTestFile = "Test.svg"; // 3. Create a file converter ImageSvgConverter converter = new ImageSvgConverter(settings); // 4. Perform the conversion to image converter.EncoderType = ImageEncoderType.BmpBitmap; converter.Convert(svgTestFile); converter.EncoderType = ImageEncoderType.GifBitmap; converter.Convert(svgTestFile); converter.EncoderType = ImageEncoderType.JpegBitmap; converter.Convert(svgTestFile); converter.EncoderType = ImageEncoderType.PngBitmap; converter.Convert(svgTestFile); converter.EncoderType = ImageEncoderType.TiffBitmap; converter.Convert(svgTestFile); converter.EncoderType = ImageEncoderType.WmpBitmap; converter.Convert(svgTestFile); }
/// <overloads> /// This creates a new settings object that is a deep copy of the current /// instance. /// </overloads> /// <summary> /// This creates a new settings object that is a deep copy of the current /// instance. /// </summary> /// <returns> /// A new settings object that is a deep copy of this instance. /// </returns> /// <remarks> /// This is deep cloning of the members of this settings object. If you /// need just a copy, use the copy constructor to create a new instance. /// </remarks> public WpfDrawingSettings Clone() { WpfDrawingSettings clonedSettings = new WpfDrawingSettings(this); if (!string.IsNullOrWhiteSpace(_defaultFontName)) { clonedSettings._defaultFontName = new string(_defaultFontName.ToCharArray()); } if (!string.IsNullOrWhiteSpace(_userCssFilePath)) { clonedSettings._userCssFilePath = new string(_userCssFilePath.ToCharArray()); } if (!string.IsNullOrWhiteSpace(_userAgentCssFilePath)) { clonedSettings._userAgentCssFilePath = new string(_userAgentCssFilePath.ToCharArray()); } if (_culture != null) { clonedSettings._culture = (CultureInfo)_culture.Clone(); } if (_neutralCulture != null) { clonedSettings._neutralCulture = (CultureInfo)_neutralCulture.Clone(); } return(clonedSettings); }
/// <summary> /// Initializes a new instance of the <see cref="WpfDrawingSettings"/> class /// with the specified initial drawing or rendering settings, a copy constructor. /// </summary> /// <param name="settings"> /// This specifies the initial options for the rendering or drawing engine. /// </param> public WpfDrawingSettings(WpfDrawingSettings settings) { if (settings == null) { return; } _defaultFontName = settings._defaultFontName; _textAsGeometry = settings._textAsGeometry; _optimizePath = settings._optimizePath; _includeRuntime = settings._includeRuntime; _neutralCulture = settings._neutralCulture; _culture = settings._culture; _pixelWidth = settings._pixelWidth; _pixelHeight = settings._pixelHeight; _ensureViewboxSize = settings._ensureViewboxSize; _ensureViewboxPosition = settings._ensureViewboxPosition; _ignoreRootViewbox = settings._ignoreRootViewbox; _wpfVisitors = settings._wpfVisitors; _userCssFilePath = settings._userCssFilePath; _userAgentCssFilePath = settings._userAgentCssFilePath; _properties = settings._properties; _fontSynch = settings._fontSynch; _fontLocations = settings._fontLocations; _fontFamilyNames = settings._fontFamilyNames; _fontFamilyMap = settings._fontFamilyMap; }
private Drawing GetImage(WpfDrawingContext context) { WpfDrawingRenderer renderer = new WpfDrawingRenderer(); renderer.Window = _patternElement.OwnerDocument.Window as SvgWindow; WpfDrawingSettings settings = context.Settings.Clone(); settings.TextAsGeometry = true; WpfDrawingContext patternContext = new WpfDrawingContext(true, settings); patternContext.Initialize(null, context.FontFamilyVisitor, null); SvgSvgElement elm = MoveIntoSvgElement(); renderer.Render(elm, patternContext); DrawingGroup rootGroup = renderer.Drawing; MoveOutOfSvgElement(elm); if (rootGroup.Children.Count == 1) { return(rootGroup.Children[0]); } return(rootGroup); }
private void OnWindowLoaded(object sender, RoutedEventArgs e) { // 1. Create conversion options WpfDrawingSettings settings = new WpfDrawingSettings(); settings.IncludeRuntime = true; settings.TextAsGeometry = false; // 2. Select a file to be converted string svgTestFile = "Test.svg"; // 3. Create a file reader FileSvgReader converter = new FileSvgReader(settings); // 4. Read the SVG file DrawingGroup drawing = converter.Read(svgTestFile); if (drawing != null) { svgImage.Source = new DrawingImage(drawing); using (StringWriter textWriter = new StringWriter()) { if (converter.Save(textWriter)) { svgBox.Text = textWriter.ToString(); } } } }
private GeometryCollection GetTextClippingRegion(SvgStyleableElement element, WpfDrawingContext context) { GeometryCollection geomColl = new GeometryCollection(); WpfDrawingRenderer renderer = new WpfDrawingRenderer(); renderer.Window = _svgElement.OwnerDocument.Window as SvgWindow; WpfDrawingSettings settings = context.Settings.Clone(); settings.TextAsGeometry = true; WpfDrawingContext clipContext = new WpfDrawingContext(true, settings); clipContext.RenderingClipRegion = true; clipContext.Initialize(null, context.FontFamilyVisitor, null); renderer.Render(element, clipContext); DrawingGroup rootGroup = renderer.Drawing as DrawingGroup; if (rootGroup != null && rootGroup.Children.Count == 1) { DrawingGroup textGroup = rootGroup.Children[0] as DrawingGroup; if (textGroup != null) { ExtractGeometry(textGroup, geomColl); } } return(geomColl); }
public WpfDrawingContext(bool isFragment, WpfDrawingSettings settings) { var sysParam = typeof(SystemParameters); var dpiXProperty = sysParam.GetProperty("DpiX", BindingFlags.NonPublic | BindingFlags.Static); var dpiYProperty = sysParam.GetProperty("Dpi", BindingFlags.NonPublic | BindingFlags.Static); _dpiX = (int)dpiXProperty.GetValue(null, null); _dpiY = (int)dpiYProperty.GetValue(null, null); if (settings == null) { settings = new WpfDrawingSettings(); } _quickBounds = Rect.Empty; _isFragment = isFragment; _settings = settings; _drawStack = new Stack <DrawingGroup>(); _paintContexts = new Dictionary <string, WpfSvgPaintContext>(StringComparer.Ordinal); _baseUrls = new HashSet <string>(StringComparer.OrdinalIgnoreCase); _registeredIds = settings[RegisteredIdKey] as HashSet <string>; if (_registeredIds == null) { _registeredIds = new HashSet <string>(StringComparer.OrdinalIgnoreCase); settings[RegisteredIdKey] = _registeredIds; } var visitors = settings.Visitors; if (visitors != null) { WpfLinkVisitor linkVisitor = visitors.LinkVisitor; if (linkVisitor != null) { _linkVisitor = linkVisitor; } WpfFontFamilyVisitor fontFamilyVisitor = visitors.FontFamilyVisitor; if (fontFamilyVisitor != null) { _fontFamilyVisitor = fontFamilyVisitor; } WpfEmbeddedImageVisitor imageVisitor = visitors.ImageVisitor; if (imageVisitor != null) { _imageVisitor = imageVisitor; } WpfIDVisitor idVisitor = visitors.IDVisitor; if (idVisitor != null) { _idVisitor = idVisitor; } WpfClassVisitor classVisitor = visitors.ClassVisitor; if (classVisitor != null) { _classVisitor = classVisitor; } } }
public WpfDrawingRenderer(WpfDrawingSettings settings, bool isEmbedded) { _isEmbedded = isEmbedded; _svgRenderer = new WpfRenderingHelper(this); _settings = settings; _interactiveMode = isEmbedded ? SvgInteractiveModes.None : settings.InteractiveMode; }
public WpfDrawingContext(bool isFragment, WpfDrawingSettings settings) : this(isFragment) { if (settings != null) { _settings = settings; } }
/// <summary> /// Initializes a new instance of the <see cref="WpfDrawingSettings"/> class /// with the specified initial drawing or rendering settings, a copy constructor. /// </summary> /// <param name="settings"> /// This specifies the initial options for the rendering or drawing engine. /// </param> public WpfDrawingSettings(WpfDrawingSettings settings) { _defaultFontName = settings._defaultFontName; _textAsGeometry = settings._textAsGeometry; _optimizePath = settings._optimizePath; _includeRuntime = settings._includeRuntime; _neutralCulture = settings._neutralCulture; _culture = settings._culture; }
public WpfDrawingContext(bool isFragment) { _quickBounds = Rect.Empty; _isFragment = isFragment; _settings = new WpfDrawingSettings(); _drawStack = new Stack <DrawingGroup>(); _registeredIds = new HashSet <string>(StringComparer.OrdinalIgnoreCase); _paintContexts = new Dictionary <Guid, WpfSvgPaintContext>(); }
/// <summary> /// Initializes a new instance of the <see cref="SvgConverter"/> class /// with the specified drawing or rendering settings. /// </summary> /// <param name="settings"> /// This specifies the settings used by the rendering or drawing engine. /// If this is <see langword="null"/>, the default settings is used. /// </param> protected SvgConverter(WpfDrawingSettings settings) { _saveXaml = true; _saveZaml = false; _wpfSettings = settings; if (_wpfSettings == null) { _wpfSettings = new WpfDrawingSettings(); } }
public void ConvertFileToDrawingImage(string filename) { var settings = new WpfDrawingSettings { IncludeRuntime = false, TextAsGeometry = false, OptimizePath = true, }; var xaml = ConverterLogic.SvgFileToXaml(filename, ResultMode.DrawingImage , settings); Console.WriteLine(xaml); }
public DrawingPage() { InitializeComponent(); _wpfSettings = new WpfDrawingSettings(); _fileReader = new FileSvgReader(_wpfSettings); _fileReader.SaveXaml = false; _fileReader.SaveZaml = false; this.Loaded += new RoutedEventHandler(OnPageLoaded); }
public void ConvertFileToDrawingGroupWithRuntime(string filename) { var settings = new WpfDrawingSettings { IncludeRuntime = true, TextAsGeometry = false, OptimizePath = true, }; var resKeyInfo = new ResKeyInfo { Prefix = "Prefix" }; var xaml = ConverterLogic.SvgFileToXaml(filename, ResultMode.DrawingGroup, resKeyInfo, settings); Console.WriteLine(xaml); }
public void ConvertFileToDrawingGroup2() { var settings = new WpfDrawingSettings { IncludeRuntime = false, TextAsGeometry = false, OptimizePath = true, }; var xaml = ConverterLogic.SvgFileToXaml("..\\..\\TestFiles\\3d-view-icon.svg", ResultMode.DrawingGroup , settings); Console.WriteLine(xaml); string expected = File.ReadAllText("..\\..\\TestFiles\\3d-view-icon_expected.txt"); xaml.Should().Be(expected); }
public LayoutPartPropertyImagePageViewModel(LayoutPartImageViewModel layoutPartImageViewModel) { _layoutPartImageViewModel = layoutPartImageViewModel; _settings = new WpfDrawingSettings() { IncludeRuntime = false, TextAsGeometry = true, OptimizePath = true, }; StretchTypes = new ObservableCollection<Stretch>(Enum.GetValues(typeof(Stretch)).Cast<Stretch>()); UpdateLayoutPart(); SelectPictureCommand = new RelayCommand(OnSelectPicture); RemovePictureCommand = new RelayCommand(OnRemovePicture, CanRemovePicture); }
public WpfDrawingContext(bool isFragment, WpfDrawingSettings settings) { if (settings == null) { settings = new WpfDrawingSettings(); } _quickBounds = Rect.Empty; _isFragment = isFragment; _settings = settings; _drawStack = new Stack <DrawingGroup>(); _paintContexts = new Dictionary <string, WpfSvgPaintContext>(StringComparer.Ordinal); _registeredIds = settings[RegisteredIdKey] as HashSet <string>; if (_registeredIds == null) { _registeredIds = new HashSet <string>(StringComparer.OrdinalIgnoreCase); settings[RegisteredIdKey] = _registeredIds; } var visitors = settings.Visitors; if (visitors != null) { WpfLinkVisitor linkVisitor = visitors.LinkVisitor; if (linkVisitor != null) { _linkVisitor = linkVisitor; } WpfFontFamilyVisitor fontFamilyVisitor = visitors.FontFamilyVisitor; if (fontFamilyVisitor != null) { _fontFamilyVisitor = fontFamilyVisitor; } WpfEmbeddedImageVisitor imageVisitor = visitors.ImageVisitor; if (imageVisitor != null) { _imageVisitor = imageVisitor; } WpfIDVisitor idVisitor = visitors.IDVisitor; if (idVisitor != null) { _idVisitor = idVisitor; } WpfClassVisitor classVisitor = visitors.ClassVisitor; if (classVisitor != null) { _classVisitor = classVisitor; } } }
public static object ConvertSvgToObject(string filepath, ResultMode resultMode, WpfDrawingSettings wpfDrawingSettings, out string name) { var dg = ConvertFileToDrawingGroup(filepath, wpfDrawingSettings); switch (resultMode) { case ResultMode.DrawingGroup: name = BuildDrawingGroupName(filepath); return dg; case ResultMode.DrawingImage: name = BuildDrawingImageName(filepath); return DrawingToImage(dg); default: throw new ArgumentOutOfRangeException("resultMode"); } }
static void Main(string[] args) { // 1. Create conversion options WpfDrawingSettings settings = new WpfDrawingSettings(); settings.IncludeRuntime = false; settings.TextAsGeometry = true; // 2. Select a file to be converted string svgTestFile = "Test.svg"; // 3. Create a file converter FileSvgConverter converter = new FileSvgConverter(settings); // 4. Perform the conversion to XAML converter.Convert(svgTestFile); }
/// <summary> /// Initializes a new instance of the <see cref="XmlXamlWriter"/> class /// with the specified settings. /// </summary> /// <param name="settings"> /// An instance of <see cref="WpfDrawingSettings"/> specifying the /// rendering options. /// </param> public XmlXamlWriter(WpfDrawingSettings settings) { _culture = CultureInfo.InvariantCulture; _nullType = typeof(NullExtension); _namespaceCache = new NamespaceCache(_culture); _dicNamespaceMap = new Dictionary<string, NamespaceMap>(StringComparer.OrdinalIgnoreCase); _contentProperties = new Dictionary<Type, string>(); _windowsPath = "%WINDIR%"; _windowsDir = Environment.ExpandEnvironmentVariables(_windowsPath).ToLower(); _windowsDir = _windowsDir.Replace(@"\", "/"); _wpfSettings = settings; }
static void Main(string[] args) { // Reference WindowsBase // 1. Create conversion options WpfDrawingSettings settings = new WpfDrawingSettings(); settings.IncludeRuntime = true; settings.TextAsGeometry = false; // 2. Select a file to be converted string svgTestFile = @"C:\Users\Administrator\Desktop\svg\chart.svg"; string imgfilename = @"C:\Users\Administrator\Desktop\svg\chart.jpg"; // 3. Create a file converter ImageSvgConverter converter = new ImageSvgConverter(settings); // 4. Perform the conversion to image converter.EncoderType = ImageEncoderType.JpegBitmap; converter.Convert(svgTestFile, imgfilename); }
/// <summary> /// Initializes a new instance of the <see cref="FileSvgConverter"/> class /// with the specified drawing or rendering settings, the saving options /// and the working directory. /// </summary> /// <param name="saveXaml"> /// This specifies whether to save result object tree in XAML file. /// </param> /// <param name="saveZaml"> /// This specifies whether to save result object tree in ZAML file. The /// ZAML is simply a G-Zip compressed XAML format, similar to the SVGZ. /// </param> /// <param name="workingDir"> /// The working directory, where converted outputs are saved. /// </param> /// <param name="settings"> /// This specifies the settings used by the rendering or drawing engine. /// If this is <see langword="null"/>, the default settings is used. /// </param> public FileSvgReader(bool saveXaml, bool saveZaml, DirectoryInfo workingDir, WpfDrawingSettings settings) : base(saveXaml, saveZaml, settings) { _wpfRenderer = new WpfDrawingRenderer(this.DrawingSettings); _wpfWindow = new WpfSvgWindow(640, 480, _wpfRenderer); _workingDir = workingDir; if (_workingDir != null) { if (!_workingDir.Exists) { _workingDir.Create(); } } }
public ImagePropertiesViewModel(IElementBackground element) { _drawing = null; _newImage = false; _element = element; _sourceName = _element.BackgroundSourceName; _imageSource = _element.BackgroundImageSource; _isVectorImage = _element.IsVectorImage; _settings = new WpfDrawingSettings() { IncludeRuntime = false, TextAsGeometry = true, OptimizePath = true, }; SelectPictureCommand = new RelayCommand(OnSelectPicture); RemovePictureCommand = new RelayCommand(OnRemovePicture, CanRemovePicture); UpdateImage(); }
public ConsoleFileConverter(string sourceFile) { _sourceFile = sourceFile; _wpfSettings = new WpfDrawingSettings(); _wpfSettings.CultureInfo = _wpfSettings.NeutralCultureInfo; _fileReader = new FileSvgReader(_wpfSettings); _fileReader.SaveXaml = false; _fileReader.SaveZaml = false; _worker = new ConsoleWorker(); //_worker.WorkerReportsProgress = true; //_worker.WorkerSupportsCancellation = true; _worker.DoWork += new DoWorkEventHandler(OnWorkerDoWork); _worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(OnWorkerCompleted); _worker.ProgressChanged += new ProgressChangedEventHandler(OnWorkerProgressChanged); }
static void Main(string[] args) { // 1. Create conversion options WpfDrawingSettings settings = new WpfDrawingSettings(); settings.IncludeRuntime = true; settings.TextAsGeometry = false; // 2. Specify the source and destination directories DirectoryInfo svgDir = new DirectoryInfo( Path.GetFullPath("Samples")); DirectoryInfo xamlDir = new DirectoryInfo( Path.GetFullPath("SamplesXaml")); // 3. Create a directory converter DirectorySvgConverter converter = new DirectorySvgConverter(settings); // 4. Perform the conversion to XAML converter.Convert(svgDir, xamlDir); }
public DrawingPage() { InitializeComponent(); _saveXaml = true; _wpfSettings = new WpfDrawingSettings(); _wpfSettings.CultureInfo = _wpfSettings.NeutralCultureInfo; _fileReader = new FileSvgReader(_wpfSettings); _fileReader.SaveXaml = _saveXaml; _fileReader.SaveZaml = false; mouseHandlingMode = MouseHandlingMode.None; string workDir = Path.Combine(Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().Location), "XamlDrawings"); _workingDir = new DirectoryInfo(workDir); this.Loaded += new RoutedEventHandler(OnPageLoaded); }
public FileListConverterOutput() { InitializeComponent(); _wpfSettings = new WpfDrawingSettings(); _wpfSettings.CultureInfo = _wpfSettings.NeutralCultureInfo; _fileReader = new FileSvgReader(_wpfSettings); _fileReader.SaveXaml = false; _fileReader.SaveZaml = false; _worker = new BackgroundWorker(); _worker.WorkerReportsProgress = true; _worker.WorkerSupportsCancellation = true; _worker.DoWork += new DoWorkEventHandler(OnWorkerDoWork); _worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(OnWorkerCompleted); _worker.ProgressChanged += new ProgressChangedEventHandler(OnWorkerProgressChanged); _continueOnError = true; }
public static async Task<DrawingImage> Retrieve(DcrGraph graph) { var body = "src=" + graph.ExportToXml(); var tempFilePath = Path.Combine(Path.GetTempPath(), "SaveFile.svg"); using (WebClient wc = new WebClient()) { wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; //var encodedBody = SharpVectors.HttpUtility.UrlEncode(body); //if (encodedBody == null) //{ // return null; //} var encodedBody = Regex.Replace(body, @"[^\w\s<>/""=]", ""); //var encodedBody = body.Replace(" & ", "and"); // TODO: Replace all illegal characters...? if (encodedBody.Contains("_")) encodedBody = encodedBody.Replace("_", ""); var result = await wc.UploadStringTaskAsync("http://dcr.itu.dk:8023/trace/dcr", encodedBody); //TODO: don't save it as a file System.IO.File.WriteAllText(tempFilePath, result); } //conversion options WpfDrawingSettings settings = new WpfDrawingSettings(); settings.IncludeRuntime = true; settings.TextAsGeometry = true; FileSvgReader converter = new FileSvgReader(settings); var xamlFile = converter.Read(tempFilePath); return new DrawingImage(xamlFile); }
/// <summary> /// Initializes a new instance of the <see cref="WpfDrawingSettings"/> class /// with the specified initial drawing or rendering settings, a copy constructor. /// </summary> /// <param name="settings"> /// This specifies the initial options for the rendering or drawing engine. /// </param> public WpfDrawingSettings(WpfDrawingSettings settings) { if (settings == null) { return; } _defaultFontName = settings._defaultFontName; _textAsGeometry = settings._textAsGeometry; _optimizePath = settings._optimizePath; _includeRuntime = settings._includeRuntime; _neutralCulture = settings._neutralCulture; _culture = settings._culture; _pixelWidth = settings._pixelWidth; _pixelHeight = settings._pixelHeight; _ensureViewboxSize = settings._ensureViewboxSize; _ensureViewboxPosition = settings._ensureViewboxPosition; _ignoreRootViewbox = settings._ignoreRootViewbox; }
public ConsoleDirectoryConverter(string sourceDir) { _sourceDir = sourceDir; _wpfSettings = new WpfDrawingSettings(); _wpfSettings.CultureInfo = _wpfSettings.NeutralCultureInfo; _fileReader = new FileSvgReader(_wpfSettings); _fileReader.SaveXaml = false; _fileReader.SaveZaml = false; _worker = new ConsoleWorker(); //_worker.WorkerReportsProgress = true; //_worker.WorkerSupportsCancellation = true; _worker.DoWork += new DoWorkEventHandler(OnWorkerDoWork); _worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(OnWorkerCompleted); _worker.ProgressChanged += new ProgressChangedEventHandler(OnWorkerProgressChanged); _isOverwrite = true; _isRecursive = true; _continueOnError = true; }
internal static DrawingGroup SvgFileToWpfObject(string filepath, WpfDrawingSettings wpfDrawingSettings) { if (wpfDrawingSettings == null) //use defaults if null wpfDrawingSettings = new WpfDrawingSettings { IncludeRuntime = false, TextAsGeometry = false, OptimizePath = true }; var reader = new FileSvgReader(wpfDrawingSettings); //this is straight forward, but in this version of the dlls there is an error when name starts with a digit //var uri = new Uri(Path.GetFullPath(filepath)); //reader.Read(uri); //accessing using the filename results is problems with the uri (if the dlls are packed in ressources) //return reader.Drawing; //this should be faster, but using CreateReader will loose text items like "JOG" ?! //using (var stream = File.OpenRead(Path.GetFullPath(filepath))) //{ // //workaround: error when Id starts with a number // var doc = XDocument.Load(stream); // ReplaceIdsWithNumbers(doc.Root); //id="3d-view-icon" -> id="_3d-view-icon" // using (var xmlReader = doc.CreateReader()) // { // reader.Read(xmlReader); // return reader.Drawing; // } //} //workaround: error when Id starts with a number var doc = XDocument.Load(Path.GetFullPath(filepath)); ReplaceIdsWithNumbers(doc.Root); //id="3d-view-icon" -> id="_3d-view-icon" using (var ms = new MemoryStream()) { doc.Save(ms); ms.Position = 0; reader.Read(ms); return reader.Drawing; } }
public static string SvgFileToXaml(string filepath, ResultMode resultMode, WpfDrawingSettings wpfDrawingSettings = null) { string name; var obj = ConvertSvgToObject(filepath, resultMode, wpfDrawingSettings, out name); return SvgObjectToXaml(obj, wpfDrawingSettings != null ? wpfDrawingSettings.IncludeRuntime : false, name); }
internal static ResourceDictionary ConvertFilesToResourceDictionary(IEnumerable<string> files, WpfDrawingSettings wpfDrawingSettings) { var dict = new ResourceDictionary(); foreach (var file in files) { var drawingGroup = ConvertFileToDrawingGroup(file, wpfDrawingSettings); var keyDg = BuildDrawingGroupName(file); dict[keyDg] = drawingGroup; } return dict; }
public WpfDrawingRenderer(WpfDrawingSettings settings, bool isEmbedded) { _isEmbedded = isEmbedded; _svgRenderer = new WpfRenderingHelper(this); _settings = settings; }
public static string SvgDirToXaml(string folder, string xamlName, WpfDrawingSettings wpfDrawingSettings) { var files = SvgFilesFromFolder(folder); var dict = ConvertFilesToResourceDictionary(files, wpfDrawingSettings); var xamlUntidy = WpfObjToXaml(dict, wpfDrawingSettings != null ? wpfDrawingSettings.IncludeRuntime : false); var doc = XDocument.Parse(xamlUntidy); RemoveResDictEntries(doc.Root); var drawingGroupElements = doc.Root.XPathSelectElements("defns:DrawingGroup", _nsManager).ToList(); foreach (var drawingGroupElement in drawingGroupElements) { BeautifyDrawingElement(drawingGroupElement, null); ExtractGeometries(drawingGroupElement); } ReplaceBrushesInDrawingGroups(doc.Root, xamlName); AddDrawingImagesToDrawingGroups(doc.Root); return doc.ToString(); }
public WpfDrawingRenderer(WpfDrawingSettings settings) : this(settings, false) { }
protected void SetMask(WpfDrawingContext context) { _maskUnits = SvgUnitType.UserSpaceOnUse; _maskContentUnits = SvgUnitType.UserSpaceOnUse; CssPrimitiveValue maskPath = _svgElement.GetComputedCssValue("mask", string.Empty) as CssPrimitiveValue; SvgMaskElement maskElement = null; if (maskPath != null && maskPath.PrimitiveType == CssPrimitiveType.Uri) { string absoluteUri = _svgElement.ResolveUri(maskPath.GetStringValue()); maskElement = _svgElement.OwnerDocument.GetNodeByUri(absoluteUri) as SvgMaskElement; } else if (string.Equals(_svgElement.ParentNode.LocalName, "use")) { var parentElement = _svgElement.ParentNode as SvgElement; maskPath = parentElement.GetComputedCssValue("mask", string.Empty) as CssPrimitiveValue; if (maskPath != null && maskPath.PrimitiveType == CssPrimitiveType.Uri) { string absoluteUri = _svgElement.ResolveUri(maskPath.GetStringValue()); maskElement = _svgElement.OwnerDocument.GetNodeByUri(absoluteUri) as SvgMaskElement; } } if (maskElement != null) { WpfDrawingRenderer renderer = new WpfDrawingRenderer(); renderer.Window = _svgElement.OwnerDocument.Window as SvgWindow; WpfDrawingSettings settings = context.Settings.Clone(); settings.TextAsGeometry = true; WpfDrawingContext maskContext = new WpfDrawingContext(true, settings); //maskContext.Initialize(null, context.FontFamilyVisitor, null); maskContext.Initialize(context.LinkVisitor, context.FontFamilyVisitor, context.ImageVisitor); renderer.RenderMask(maskElement, maskContext); DrawingGroup maskDrawing = renderer.Drawing; Rect bounds = new Rect(0, 0, 1, 1); //Rect destRect = GetMaskDestRect(maskElement, bounds); //destRect = bounds; //DrawingImage drawImage = new DrawingImage(image); //DrawingVisual drawingVisual = new DrawingVisual(); //DrawingContext drawingContext = drawingVisual.RenderOpen(); //drawingContext.DrawDrawing(image); //drawingContext.Close(); //RenderTargetBitmap drawImage = new RenderTargetBitmap((int)200, // (int)200, 96, 96, PixelFormats.Pbgra32); //drawImage.Render(drawingVisual); //ImageBrush imageBrush = new ImageBrush(drawImage); //imageBrush.Viewbox = image.Bounds; //imageBrush.Viewport = image.Bounds; //imageBrush.ViewboxUnits = BrushMappingMode.Absolute; //imageBrush.ViewportUnits = BrushMappingMode.Absolute; //imageBrush.TileMode = TileMode.None; //imageBrush.Stretch = Stretch.None; //this.Masking = imageBrush; DrawingBrush maskBrush = new DrawingBrush(maskDrawing); //tb.Viewbox = new Rect(0, 0, destRect.Width, destRect.Height); //tb.Viewport = new Rect(0, 0, destRect.Width, destRect.Height); maskBrush.Viewbox = maskDrawing.Bounds; maskBrush.Viewport = maskDrawing.Bounds; maskBrush.ViewboxUnits = BrushMappingMode.Absolute; maskBrush.ViewportUnits = BrushMappingMode.Absolute; maskBrush.TileMode = TileMode.None; maskBrush.Stretch = Stretch.Uniform; ////maskBrush.AlignmentX = AlignmentX.Center; ////maskBrush.AlignmentY = AlignmentY.Center; this.Masking = maskBrush; _maskUnits = (SvgUnitType)maskElement.MaskUnits.AnimVal; _maskContentUnits = (SvgUnitType)maskElement.MaskContentUnits.AnimVal; } }
/// <summary> /// Performs the conversion of a valid SVG source file to the /// <see cref="DrawingImage"/> that is set as the value of the target /// property for this markup extension. /// </summary> /// <param name="serviceProvider"> /// Object that can provide services for the markup extension. /// </param> /// <returns> /// This returns <see cref="DrawingImage"/> if successful; otherwise, it /// returns <see langword="null"/>. /// </returns> public override object ProvideValue(IServiceProvider serviceProvider) { Uri svgSource = this.GetUri(serviceProvider); if (svgSource == null) { return null; } try { string scheme = svgSource.Scheme; if (String.IsNullOrEmpty(scheme)) { return null; } WpfDrawingSettings settings = new WpfDrawingSettings(); settings.IncludeRuntime = _includeRuntime; settings.TextAsGeometry = _textAsGeometry; settings.OptimizePath = _optimizePath; if (_culture != null) { settings.CultureInfo = _culture; } switch (scheme) { case "file": //case "ftp": //case "https": case "http": using (FileSvgReader reader = new FileSvgReader(settings)) { DrawingGroup drawGroup = reader.Read(svgSource); if (drawGroup != null) { return new DrawingImage(drawGroup); } } break; case "pack": StreamResourceInfo svgStreamInfo = null; if (svgSource.ToString().IndexOf("siteoforigin", StringComparison.OrdinalIgnoreCase) >= 0) { svgStreamInfo = Application.GetRemoteStream(svgSource); } else { svgStreamInfo = Application.GetResourceStream(svgSource); } Stream svgStream = (svgStreamInfo != null) ? svgStreamInfo.Stream : null; if (svgStream != null) { string fileExt = Path.GetExtension(svgSource.ToString()); bool isCompressed = !String.IsNullOrEmpty(fileExt) && String.Equals(fileExt, ".svgz", StringComparison.OrdinalIgnoreCase); if (isCompressed) { using (svgStream) { using (GZipStream zipStream = new GZipStream(svgStream, CompressionMode.Decompress)) { using (FileSvgReader reader = new FileSvgReader(settings)) { DrawingGroup drawGroup = reader.Read( zipStream); if (drawGroup != null) { return new DrawingImage(drawGroup); } } } } } else { using (svgStreamInfo.Stream) { using (FileSvgReader reader = new FileSvgReader(settings)) { DrawingGroup drawGroup = reader.Read( svgStreamInfo.Stream); if (drawGroup != null) { return new DrawingImage(drawGroup); } } } } } break; } } catch { if (DesignerProperties.GetIsInDesignMode(new DependencyObject()) || LicenseManager.UsageMode == LicenseUsageMode.Designtime) { return null; } throw; } return null; }
public WpfDrawingRenderer(WpfDrawingSettings settings) { _svgRenderer = new WpfRenderingHelper(this); _renderingSettings = settings; }
private static DrawingGroup ConvertFileToDrawingGroup(string filepath, WpfDrawingSettings wpfDrawingSettings) { var dg = SvgFileToWpfObject(filepath, wpfDrawingSettings); SetSizeToGeometries(dg); RemoveObjectNames(dg); return dg; }
/// <overloads> /// This creates a new settings object that is a deep copy of the current /// instance. /// </overloads> /// <summary> /// This creates a new settings object that is a deep copy of the current /// instance. /// </summary> /// <returns> /// A new settings object that is a deep copy of this instance. /// </returns> /// <remarks> /// This is deep cloning of the members of this settings object. If you /// need just a copy, use the copy constructor to create a new instance. /// </remarks> public WpfDrawingSettings Clone() { WpfDrawingSettings settings = new WpfDrawingSettings(this); return(settings); }
private DrawingGroup GetImage(WpfDrawingContext context, Rect bounds) { PrepareTargetPattern(); _renderedElement.PatternBounds = new SvgRect(bounds.X, bounds.Y, bounds.Width, bounds.Height); WpfDrawingRenderer renderer = new WpfDrawingRenderer(); renderer.Window = _renderedElement.OwnerDocument.Window as SvgWindow; // WpfDrawingSettings settings = context.Settings.Clone(); WpfDrawingSettings settings = context.Settings; bool isTextAsGeometry = settings.TextAsGeometry; settings.TextAsGeometry = true; WpfDrawingContext patternContext = new WpfDrawingContext(true, settings); patternContext.Name = "Pattern"; patternContext.Initialize(null, context.FontFamilyVisitor, null); if (_renderedElement.PatternContentUnits.AnimVal.Equals((ushort)SvgUnitType.ObjectBoundingBox)) { // svgElm.SetAttribute("viewBox", "0 0 1 1"); } else { _isUserSpace = true; } //SvgSvgElement elm = MoveIntoSvgElement(); //renderer.Render(elm, patternContext); //SvgPatternElement patternElement = _patternElement.ReferencedElement; //if (patternElement != null) //{ // if (patternElement.ReferencedElement != null) // { // _renderedElement = patternElement.ReferencedElement; // renderer.RenderAs(patternElement.ReferencedElement, patternContext); // } // else // { // _renderedElement = patternElement; // renderer.RenderAs(patternElement, patternContext); // } //} //else //{ // _renderedElement = _patternElement; // renderer.RenderAs(_patternElement, patternContext); //} renderer.RenderAs(_renderedElement, patternContext); DrawingGroup rootGroup = renderer.Drawing; //MoveOutOfSvgElement(elm); if (_renderedElement != null && _renderedElement != _patternElement) { _patternElement.RemoveChild(_renderedElement); } settings.TextAsGeometry = isTextAsGeometry; if (rootGroup.Children.Count == 1) { var childGroup = rootGroup.Children[0] as DrawingGroup; if (childGroup != null) { return(childGroup); } } return(rootGroup); }