我需要了解apache蜡染如何缩进库产生的SVG文件。
我有以下代码:
DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
String svgNS = "http://www.w3.org/2000/svg";
Document document = domImpl.createDocument(svgNS, "svg", null);
SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(document);
SVGGraphics2D svgGenerator = new SVGGraphics2D(ctx, false);
for(Drawable savedDrawable : cVwDrawLocal.getSavedDrawables()){
if(savedDrawable instanceof GeoDrawable){
savedDrawable.copyToGraphics(svgGenerator);
}
}
boolean useCSS = true; // we want to use CSS style attributes
String svgFile = svgFileName + ".svg";
try {
OutputStream outputStream = new FileOutputStream(svgFile);
Writer outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
svgGenerator.stream(outputStreamWriter, useCSS);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
生成的SVG文件为:
<g
><g style="fill:white; stroke-miterlimit:1; stroke-dasharray:1; stroke-dashoffset:1; stroke:white;"
><line y2="432" style="fill:none;" x1="873" x2="873" y1="432"
/></g
><g style="fill:rgb(0,252,253); stroke-miterlimit:1; stroke-dasharray:0.1,5; stroke-width:2; stroke-dashoffset:1; stroke:rgb(0,252,253);"
><line y2="479" style="fill:none;" x1="901" x2="910" y1="490"
/></g
>
但是我需要这样的东西:
<g>
<g style="fill:white; stroke-miterlimit:1; stroke-dasharray:1; stroke-dashoffset:1; stroke:white;">
<line y2="432" style="fill:none;" x1="873" x2="873" y1="432"/>
</g>
<g style="fill:rgb(0,252,253); stroke-miterlimit:1; stroke-dasharray:0.1,5; stroke-width:2; stroke-dashoffset:1; stroke:rgb(0,252,253);">
<line y2="479" style="fill:none;" x1="901" x2="910" y1="490"/>
</g>
</g>
我该如何获得?
先感谢您!
最佳答案
好。我找到了适合我的解决方案:
public static boolean prettyPrintXml(File newFile) {
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setValidating(false);
documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(newFile);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
StreamResult streamResult = new StreamResult(newFile);
DOMSource domSource = new DOMSource(document);
transformer.transform(domSource, streamResult);
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
谢谢!