@[JAVA解析cad图纸DXF文件]
下载依赖
- 在https://kabeja.sourceforge.net/index.html ,下载对应的包,下载解压后找到lib文件夹里面的kabeja-0.4.jar,如果需要其他模块也可以引入其他包
- kabeja-0.4.jar包 链接:https://pan.baidu.com/s/1VmKejTbLn3np7-NvPhroFw?pwd=dg65
提取码:dg65 - maven依赖
<dependency>
<groupId>org.kabeja</groupId>
<artifactId>kabeja</artifactId>
<version>0.4</version>
</dependency>
代码测试
将cad图纸dxf格式中的TEXT提取出来
import org.kabeja.dxf.*;
import org.kabeja.parser.ParseException;
import org.kabeja.parser.Parser;
import org.kabeja.parser.ParserBuilder;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Iterator;
import java.util.List;
public class ReadDxf{
StringBuffer sb = new StringBuffer();
/**
* 读取DXF文件图层
* @param filePath
* @return
* @throws FileNotFoundException
* @throws ParseException
*/
public String parser(String filePath) throws FileNotFoundException, ParseException {
Parser dxfParser = ParserBuilder.createDefaultParser();
dxfParser.parse(new FileInputStream(filePath), "GBK");//需要转换的dxf
DXFDocument doc = dxfParser.getDocument();
//遍历图层
Iterator iter= doc.getDXFLayerIterator();
while (iter.hasNext()){
DXFLayer dxfLayer = (DXFLayer)iter.next();
String layerName=dxfLayer.getName();
// System.out.println("读取图层"+layerName);
readEntity(dxfLayer);
}
return sb.toString();
}
/**
* 读取图层下都有哪些类型的实体
* @param layer
*/
public static void readEntity(DXFLayer layer){
Iterator iter= layer.getDXFEntityTypeIterator();
ReadDxf readDxf = new ReadDxf();
while (iter.hasNext()){
String s=(String) iter.next();
readDxf.getEntity(layer,s);
}
}
/**
* 读取图层下的TEXT实体
* @param layer
* @param type
*/
public void getEntity(DXFLayer layer, String type) {
if (!type.equals("TEXT")) {
List<DXFEntity> entities = layer.getDXFEntities(type);
for (int i = 0; i < entities.size(); i++) {
if ((entities.get(i) instanceof DXFText)) {
DXFText dxfText = (DXFText) entities.get(i);
String text = dxfText.getText();
sb.append(text).append("\n");
}
}
}
}
}