I am trying to write/find some code in Java which reads dxf files and stores geometry from the \"Entities\" section into arrays so that I can later import that information i
I have used Kabeja in my project and I noticed that it is a very good choice because it is a free and powerful tool.
A autocad line is represented by two extremities (the start and the end point)
Each point has 3 coordinates : X, Y and Z
Below is a 2D method (working on both X and Y) that takes a dxf file as parameter, parse it and then extracts the lines inside it.
The autocad lines will be readed using kabeja functions, then we can build our own Java Lines
public class ReadAutocadFile {
public static ArrayList getAutocadFile(String filePath) throws ParseException {
ArrayList lines = new ArrayList<>();
Parser parser = ParserBuilder.createDefaultParser();
parser.parse(filePath, DXFParser.DEFAULT_ENCODING);
DXFDocument doc = parser.getDocument();
List lst = doc.getDXFLayer("layername ... whatever").getDXFEntities(DXFConstants.ENTITY_TYPE_LINE);
for (int index = 0; index < lst.size(); index++) {
Bounds bounds = lst.get(index).getBounds();
Line line = new Line(
new Point(new Double(bounds.getMinimumX()).intValue(),
new Double(bounds.getMinimumY()).intValue()),
new Point(new Double(bounds.getMaximumX()).intValue(),
new Double(bounds.getMaximumY()).intValue())
);
lines.add(line);
}
return lines;
}
}
Where each Line is about two Points in Java
public class Line {
private Point p1;
private Point p2;
public Line (Point p1, Point p2){
this.p1 = p1;
this.p2 = p2;
}
public Point getP1() {
return p1;
}
public void setP1(Point p1) {
this.p1 = p1;
}
public Point getP2() {
return p2;
}
public void setP2(Point p2) {
this.p2 = p2;
}
}
Demo:
public class ReadAutocadFileTest {
public static void main(String[] args) {
try {
File file = new File("testFile.dxf");
ArrayList lines = ReadAutocadFile.getAutocadFile(file.getAbsolutePath());
for(int index = 0 ; index < lines.size() ; index++){
System.out.println("Line " + (index +1));
System.out.print("(" + lines.get(index).getP1().getX() + "," + lines.get(index).getP1().getY()+ ")");
System.out.print(" to (" + lines.get(index).getP2().getX() + "," + lines.get(index).getP2().getY()+ ")\n");
}
} catch (Exception e) {
}
}
}
The ArrayList of Lines contains all the lines of the autocad file, we can per example draw this arraylist on a JPanel so in this way we are migrating completely from autocad to Java.