概观

使用Apache Batik加载和解析SVG文件.该解决方案在将SVG文件转换为MetaPost的初步阶段显示Java代码.这应该提供有关如何使用Java从SVG文件加载,解析和提取内容的一般概念.

图书馆

您将需要以下库:

batik-anim.jar

batik-awt-util.jar

batik-bridge.jar

batik-css.jar

batik-dom.jar

batik-ext.jar

batik-gvt.jar

batik-parser.jar

batik-script.jar

batik-svg-dom.jar

batik-svggen.jar

batik-util.jar

batik-xml.jar

xml-apis-ext.jar

加载SVG文件

主应用程序将SVG文件加载到DOM中,然后将DOM转换为SVG DOM. initSVGDOM()方法调用非常重要.在不调用initSVGDOM()的情况下,从DOM中提取SVG DOM元素的方法将不可用.

import java.io.File;

import java.io.IOException;

import java.net.URI;

import org.apache.batik.bridge.BridgeContext;

import org.apache.batik.bridge.DocumentLoader;

import org.apache.batik.bridge.GVTBuilder;

import org.apache.batik.bridge.UserAgent;

import org.apache.batik.bridge.UserAgentAdapter;

import org.apache.batik.dom.svg.SAXSVGDocumentFactory;

import org.apache.batik.dom.svg.SVGOMSVGElement;

import org.apache.batik.util.XMLResourceDescriptor;

import org.w3c.dom.Document;

import org.w3c.dom.NodeList;

/**

* Responsible for converting all SVG path elements into MetaPost curves.

*/

public class SVGMetaPost {

private static final String PATH_ELEMENT_NAME = "path";

private Document svgDocument;

/**

* Creates an SVG Document given a URI.

*

* @param uri Path to the file.

* @throws Exception Something went wrong parsing the SVG file.

*/

public SVGMetaPost( String uri ) throws IOException {

setSVGDocument( createSVGDocument( uri ) );

}

/**

* Finds all the path nodes and converts them to MetaPost code.

*/

public void run() {

NodeList pathNodes = getPathElements();

int pathNodeCount = pathNodes.getLength();

for( int iPathNode = 0; iPathNode < pathNodeCount; iPathNode++ ) {

MetaPostPath mpp = new MetaPostPath( pathNodes.item( iPathNode ) );

System.out.println( mpp.toCode() );

}

}

/**

* Returns a list of elements in the SVG document with names that

* match PATH_ELEMENT_NAME.

*

* @return The list of "path" elements in the SVG document.

*/

private NodeList getPathElements() {

return getSVGDocumentRoot().getElementsByTagName( PATH_ELEMENT_NAME );

}

/**

* Returns an SVGOMSVGElement that is the document's root element.

*

* @return The SVG document typecast into an SVGOMSVGElement.

*/

private SVGOMSVGElement getSVGDocumentRoot() {

return (SVGOMSVGElement)getSVGDocument().getDocumentElement();

}

/**

* This will set the document to parse. This method also initializes

* the SVG DOM enhancements, which are necessary to perform SVG and CSS

* manipulations. The initialization is also required to extract information

* from the SVG path elements.

*

* @param document The document that contains SVG content.

*/

public void setSVGDocument( Document document ) {

initSVGDOM( document );

this.svgDocument = document;

}

/**

* Returns the SVG document parsed upon instantiating this class.

*

* @return A valid, parsed, non-null SVG document instance.

*/

public Document getSVGDocument() {

return this.svgDocument;

}

/**

* Enhance the SVG DOM for the given document to provide CSS- and SVG-specific

* DOM interfaces.

*

* @param document The document to enhance.

* @link http://wiki.apache.org/xmlgraphics-batik/BootSvgAndCssDom

*/

private void initSVGDOM( Document document ) {

UserAgent userAgent = new UserAgentAdapter();

DocumentLoader loader = new DocumentLoader( userAgent );

BridgeContext bridgeContext = new BridgeContext( userAgent, loader );

bridgeContext.setDynamicState( BridgeContext.DYNAMIC );

// Enable CSS- and SVG-specific enhancements.

(new GVTBuilder()).build( bridgeContext, document );

}

/**

* Use the SAXSVGDocumentFactory to parse the given URI into a DOM.

*

* @param uri The path to the SVG file to read.

* @return A Document instance that represents the SVG file.

* @throws Exception The file could not be read.

*/

private Document createSVGDocument( String uri ) throws IOException {

String parser = XMLResourceDescriptor.getXMLParserClassName();

SAXSVGDocumentFactory factory = new SAXSVGDocumentFactory( parser );

return factory.createDocument( uri );

}

/**

* Reads a file and parses the path elements.

*

* @param args args[0] - Filename to parse.

* @throws IOException Error reading the SVG file.

*/

public static void main( String args[] ) throws IOException {

URI uri = new File( args[0] ).toURI();

SVGMetaPost converter = new SVGMetaPost( uri.toString() );

converter.run();

}

}

注意:除非另有说明,否则调用initSVGDOM()应该是Batik的默认行为.唉,它不是,发现这个宝石意味着在他们的网站上阅读documentation buried.

解析SVG DOM

解析SVG DOM是相对微不足道的. toCode()方法是该类的主力:

import org.apache.batik.dom.svg.SVGItem;

import org.apache.batik.dom.svg.SVGOMPathElement;

import org.w3c.dom.Node;

import org.w3c.dom.svg.SVGPathSegList;

/**

* Responsible for converting an SVG path element to MetaPost. This

* will convert just the bezier curve portion of the path element, not

* its style. Typically the SVG path data is provided from the "d" attribute

* of an SVG path node.

*/

public class MetaPostPath extends MetaPost {

private SVGOMPathElement pathElement;

/**

* Use to create an instance of a class that can parse an SVG path

* element to produce MetaPost code.

*

* @param pathNode The path node containing a "d" attribute (output as MetaPost code).

*/

public MetaPostPath( Node pathNode ) {

setPathNode( pathNode );

}

/**

* Converts this object's SVG path to a MetaPost draw statement.

*

* @return A string that represents the MetaPost code for a path element.

*/

public String toCode() {

StringBuilder sb = new StringBuilder( 16384 );

SVGOMPathElement pathElement = getPathElement();

SVGPathSegList pathList = pathElement.getNormalizedPathSegList();

int pathObjects = pathList.getNumberOfItems();

sb.append( ( new MetaPostComment( getId() ) ).toString() );

for( int i = 0; i < pathObjects; i++ ) {

SVGItem item = (SVGItem)pathList.getItem( i );

sb.append( String.format( "%s%n", item.getValueAsString() ) );

}

return sb.toString();

}

/**

* Returns the value for the id attribute of the path element. If the

* id isn't present, this will probably throw a NullPointerException.

*

* @return A non-null, but possibly empty String.

*/

private String getId() {

return getPathElement().getAttributes().getNamedItem( "id" ).getNodeValue();

}

/**

* Typecasts the given pathNode to an SVGOMPathElement for later analysis.

*

* @param pathNode The path element that contains curves, lines, and other

* SVG instructions.

*/

private void setPathNode( Node pathNode ) {

this.pathElement = (SVGOMPathElement)pathNode;

}

/**

* Returns an SVG document element that contains path instructions (usually

* for drawing on a canvas).

*

* @return An object that contains a list of items representing pen

* movements.

*/

private SVGOMPathElement getPathElement() {

return this.pathElement;

}

}

建立

编译因环境而异.类似于以下的脚本应该有所帮助:

#!/bin/bash

mkdir -p ./build

javac -cp ./lib/* -d ./build ./source/*.java

确保将所有.jar文件放入./lib目录中.将源文件放入./source目录.

创建一个脚本(或批处理文件)来执行该程序:

#!/bin/bash

java -cp ./lib/*:./build SVGMetaPost $1

产量

对包含有效SVG路径的文件运行时,会产生:

$./run.sh stripe/trigon.svg

% path8078-6

M 864.1712 779.3069

C 864.1712 779.3069 868.04065 815.6211 871.4032 833.4621

C 873.4048 844.08203 874.91724 855.0544 879.0846 864.82227

C 884.24023 876.9065 895.2377 887.9899 900.0184 897.3661

C 904.7991 906.7422 907.3466 918.3257 907.3466 918.3257

C 907.3466 918.3257 892.80817 887.6536 864.1712 887.3086

C 835.53424 886.9637 820.9958 918.3257 820.9958 918.3257

C 820.9958 918.3257 823.6176 906.59644 828.32404 897.3661

C 833.0304 888.1356 844.10223 876.9065 849.2578 864.82227

C 853.4252 855.05444 854.9376 844.08203 856.93915 833.4621

C 860.3017 815.6211 864.17114 779.3069 864.17114 779.3069

z

从这里开始,应该清楚如何使用Java将SVG路径数据读入相应的SVG对象.

附录

请注意,从SVG转换为MetaPost的最简单方法是:

>将SVG转换为PDF(例如,使用Inkscape或rsvg-convert).

>使用pstoedit将PDF转换为MetaPost.

java 解析 svg文件_java – 如何加载和解析SVG文档相关推荐

  1. Visual Studio点击之前创建的Form提示“由于从未加载设计器的文档,因此无法显示设计器”

    现象 打开之前创建的工程,点击其中一个Form后,提示"由于从未加载设计器的文档,因此无法显示设计器",打不开界面,点击其他Form可以正常打开,就这个打开不了. 解决方法 把工程 ...

  2. plsql 无法解析指定的连接标识符_Java方法加载、解析、存储、调用

    方法调用在项目中是数不胜数,除了一些常量类其他的类都会定义方法并调用,那你有想过他是怎么从一个java语言写的方法到计算机执行的吗,下面我们就来学习Class字节码文件中保存java中的方法.方法加载 ...

  3. java加载字体文件_Java的加载自定义字体文件(.TTF)

    我在下面这段代码中使用,并将其与该堆栈跟踪出现:Java的加载自定义字体文件(.TTF) java.io.FileNotFoundException: font.ttf (No such file o ...

  4. android中读取svg文件,Android如何加载SVG格式的矢量图

    为何要加载SVG图片 相对于.JPG和.PNG甚至.webp的图片来说,SVG的图片有两个优点,第一:省空间,APK瘦身有一个方面就是从图片瘦身,使用SVG图片可以大量减轻程序的大小.第二:省时间,切 ...

  5. python解析json文件案例_Python加载带有注释的Json文件实例

    由于json文件不支持注释,所以如果在json文件中标记了注释,则使用python中的json.dump()无法加载该json文件. 本文旨在解决当定义"//"为json注释时,如 ...

  6. java 静态初始化 调用_java JVM-类加载静态初始化块调用顺序

    测试类加载的全过程 public class Have { static { System.out.println("加载Have");//先加载Have再调用main方法 } p ...

  7. java imageio删除图片_Java 提取、替换、删除PDF文档中的图片

    在一篇文章里,配有与文本信息相得益彰的图片,不仅能够活跃与美化版面,同时也有利于提高文章的可读性和阅读效果,从而增强其吸引力.同时,对文档中已存在图片的处理也尤为重要.本文将通过使用Java程序来演示 ...

  8. java 导出word换行_Java 导出数据库表信息生成Word文档

    一.前言 最近看见朋友写了一个导出数据库生成word文档的业务,感觉很有意思,研究了一下,这里也拿出来与大家分享一波~ 先来看看生成的word文档效果吧 下面我们也来一起简单的实现吧 二.Java 导 ...

  9. scala 加载与保存xml文档

    1 package scala_enhance.xml 2 3 import scala.xml.XML 4 import scala.io.Source 5 import jdk.internal. ...

最新文章

  1. exist not exist 分析
  2. golang goroutine 协程原理
  3. 电商:流量不再重要,渠道终将为王
  4. 腾讯与 TTN 宣布战略合作,共同推进全球及中国物联网开发生态
  5. Pretty girl,你一定要去旅行
  6. 如何在Android Studio里关掉instant run
  7. JS笔记:检测客户端(引擎、浏览器、平台、操作系统)
  8. 检测到目标url存在框架注入漏洞_HOST注入攻击剖析
  9. 微信小程序----全局变量
  10. VIM之Project 项目管理工具
  11. 什么是java dom_java web--DOM
  12. python中reload作用_import reload __import__在python中的区别
  13. 德力西双电源自动转换开关说明书_聊聊双电源转换的那点事。
  14. 2010年度十大杰出IT博客大赛奖品展示
  15. c语言检测数独是否正确,会数独的大佬请进。这是个判断九宫格数独是否正确的程序。...
  16. [前端网站毕业设计源码]基于html的大学校园官网(jQuery)(静态网页)
  17. GBIT51233-2016装配式木结构建筑技术标准
  18. ThinkPHP中IP地址定位,包括IP地址库文件
  19. MySQL:Impossible WHERE noticed after reading const tables
  20. AD16如何添加禁止区域

热门文章

  1. 如何将整个网页变成灰色
  2. 曹云金回应公式相声_疑砸挂曹云金?阎鹤祥封箱大典开玩笑要退社,郭德纲回复亮了!...
  3. Cytoskeleton——SiR-肌动蛋白相关工具推荐
  4. [个人学习]透视画法的一点记录
  5. 通过无线串口ATK-LoRa-01发送陀螺仪MPU6050三种维度信息---数值处理代码分享(小成就^V^)
  6. 人们从诗人的字句里选取自己心爱的意义但诗句的最终意义是指向你
  7. php语言开始和结束分别为,PHP语言参考
  8. 基础商务谈判培训技巧
  9. Java并发编程的艺术(推荐指数:☆☆☆☆☆☆)
  10. R-2R梯形网络 DAC简易的电路