简体   繁体   English

在 Java 中使用 Batik 检查和删除 SVG 中的属性

[英]Checking and deleting attributes in SVG using Batik in Java

The question basically says it all.这个问题基本上说明了一切。 How can I check if SVG has a viewBox attribute?如何检查 SVG 是否具有 viewBox 属性? I am using Batik lib.我正在使用蜡染库。 I need this because I need to (at least) notify the user that there is a viewBox attribute.我需要这个,因为我需要(至少)通知用户有一个 viewBox 属性。

Can I delete it?我可以删除它吗?

Using org.w3c.dom classes you'd do something along these lines...使用 org.w3c.dom 类你会沿着这些方向做一些事情......

        String parser = XMLResourceDescriptor.getXMLParserClassName();
        SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);
        URL url = new URL(getCodeBase(), "fileName.svg");
        Document doc = f.createDocument(url.toString());

        Element svg = doc.getDocumentElement();

        if (svg.hasAttribute("viewBox")) {
          // notify the user somehow
        }

to delete call删除通话

        svg.removeAttribute("viewBox")

I am using a slightly different approach to the same:我对相同的方法使用了稍微不同的方法:

/**
 * Main getViewBoxRect method
 * 
 * Returns the TopLeft point and width and height of the viewBox
 * 
 * @param doc -- the SVGDocument
 * 
 * @return
 */
public static double[] getViewBoxRect(SVGDocument doc)
{
    if (doc == null)
    {
        System.err.printf("\ngetViewBoxRect: null document\n\n");
        return null;
    }
    
    SVGSVGElement el = doc.getRootElement();
    
    if (el == null)
    {
        System.err.printf("\ngetViewBoxRect: null rootElement\n\n");
        return null;
    }

    String viewBoxStr = el.getAttributeNS(null,
            SVGConstants.SVG_VIEW_BOX_ATTRIBUTE);
    
    if (viewBoxStr.length() != 0)
    {
        float[] rect = ViewBox.parseViewBoxAttribute(el, viewBoxStr, null);
        
        return new double[]
        {
                rect[0], rect[1],
                rect[2], rect[3]
        };
    }

    System.err.printf("\ngetViewBoxRect: null viewBox received\n\n");
    return null;
}

Of course, if you get a null value, no viewBox has been set.当然,如果你得到一个null的值,说明还没有设置viewBox。 If you want to reset the viewBox, you can use如果你想重置 viewBox,你可以使用

doc.removeAttribute("viewBox"); doc.removeAttribute("viewBox");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM