| New file |
| | |
| | | package org.springblade.common.utils; |
| | | |
| | | import com.aspose.cad.Image; |
| | | import org.kabeja.dxf.DXFDocument; |
| | | import org.kabeja.dxf.DXFEntity; |
| | | import org.kabeja.dxf.DXFLayer; |
| | | import org.kabeja.dxf.DXFText; |
| | | import org.kabeja.parser.ParseException; |
| | | import org.kabeja.parser.Parser; |
| | | import org.kabeja.parser.ParserBuilder; |
| | | import java.io.*; |
| | | import java.util.Iterator; |
| | | import java.util.List; |
| | | |
| | | public class CADParserUtil { |
| | | |
| | | /** |
| | | * 读取DXF文件图层 |
| | | * @param filePath |
| | | * @return |
| | | * @throws FileNotFoundException |
| | | * @throws ParseException |
| | | */ |
| | | public static String parser(String filePath) throws FileNotFoundException, ParseException { |
| | | Parser dxfParser = ParserBuilder.createDefaultParser(); |
| | | dxfParser.parse(new FileInputStream(filePath), "UTF-8");//需要转换的dxf |
| | | DXFDocument doc = dxfParser.getDocument(); |
| | | StringBuffer sb = new StringBuffer(); |
| | | //遍历图层 |
| | | Iterator iter= doc.getDXFLayerIterator(); |
| | | |
| | | while (iter.hasNext()){ |
| | | DXFLayer dxfLayer = (DXFLayer)iter.next(); |
| | | String layerName=dxfLayer.getName(); |
| | | System.out.println("读取图层"+layerName); |
| | | readEntity(dxfLayer,sb); |
| | | |
| | | } |
| | | System.out.println("最终数据 = " + sb); |
| | | return sb.toString(); |
| | | } |
| | | |
| | | /** |
| | | * 读取图层下都有哪些类型的实体 |
| | | * @param layer |
| | | */ |
| | | public static void readEntity(DXFLayer layer,StringBuffer sb){ |
| | | Iterator iter= layer.getDXFEntityTypeIterator(); |
| | | while (iter.hasNext()){ |
| | | String s=(String) iter.next(); |
| | | System.out.println("类型 = " + s); |
| | | getEntity(layer,s,sb); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 读取图层下的TEXT实体 |
| | | * @param layer |
| | | * @param type |
| | | */ |
| | | public static void getEntity(DXFLayer layer, String type,StringBuffer sb) { |
| | | if (type.equals("LWPOLYLINE")) { |
| | | 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"); |
| | | } |
| | | } |
| | | } |
| | | } |
| | | |
| | | public static void main(String[] args) { |
| | | try { |
| | | // 指定输入和输出文件的路径。 |
| | | String inputDWG = "F:\\test4jdata\\cad\\tdsyqk.dwg"; |
| | | String outputDXF = "F:\\test4jdata\\cad\\tdsyqk.dxf"; |
| | | |
| | | // 加载输入 DWG 文件 |
| | | Image cadImage = Image.load(inputDWG); |
| | | // 保存输出 DXF 文件 |
| | | cadImage.save(outputDXF); |
| | | String text = parser(outputDXF); |
| | | System.out.println(text); |
| | | } catch (IOException | ParseException e) { |
| | | e.printStackTrace(); |
| | | } |
| | | } |
| | | } |