I am post-processing an SVG with embedded WOFF fonts (some custom) to make it compatible to insert as a Microsoft Word image and retain fonts.
I am encountering a problem where I cannot remove the parent style element containing the embedded font as I get a NullReferenceException. I can remove the CSS rule from the stylesheet but I cannot remove the now empty stylesheet.
I am probably going about this in the wrong way, any guidance is appreciated.
Using Aspose.SVG 21.10 with .NET 5.0
In the most basic scenario to reproduce,
- Load SVG.
- Replace elements containing “font-family” attribute with “Arial” value.
- Remove elements. The “Tahoma” font-face is no longer used by any elements.
This causes a NullReferenceException with stack trace:
at ..(Node )
at Aspose.Svg.Dom.Node.(Node , Node , Boolean )
at Aspose.Svg.Dom.Node.(Node , Node )
at Aspose.Svg.Dom.Node.RemoveChild(Node child)
at Aspose.Svg.Dom.Element.Remove()
Code to reproduce using example SVG file in attached example example.zip (497.0 KB)
solution.
// 1. Load SVG
var document = new SVGDocument(fileName);
// 2. Replace elements containing "font-family" attribute with "Arial" value
using (var iterator = document.CreateNodeIterator(document))
{
Node node;
while ((node = iterator.NextNode()) != null)
{
if (node is SVGElement element &&
element.HasAttribute("font-family"))
{
element.SetAttribute("font-family", "Arial");
}
}
}
// 3. Remove <style> elements
var elements = new List<SVGStyleElement>();
using (var iterator = document.CreateNodeIterator(document))
{
Node node;
while ((node = iterator.NextNode()) != null)
{
if (node is SVGStyleElement styleElement)
{
elements.Add(styleElement);
}
}
}
foreach (var element in elements)
{
// Raise NullReferenceException: Object reference not set to an instance of an object.
element.Remove();
}