Click here to Skip to main content
15,885,645 members
Articles / Desktop Programming / Windows Forms

DXF Import .NET: Read and View AutoCAD Format Files

Rate me:
Please Sign up or sign in to vote.
4.81/5 (33 votes)
7 Mar 2011MPL6 min read 271.5K   33K   92   34
C# source to read AutoCAD DXF files

Problem and Solution

Software development in industry, building and many other fields requires working with CAD drawings. The most popular CAD formats are AutoCAD DWG and AutoCAD DXF, the latter being "simplified" dwg - a special format to be used by developers. The problem is that DXF and DWG formats are really complicated. They have dozens of objects with hundreds of interaction tricks and thousands of properties. Official DXF Reference from Autodesk has 256 pages though it fails to describe many important facts. Hence, the development for CAD drawings is often required but is not easy to implement. This article is to tell you how to write the DXF reader in C#, what problems can arise and of course you can find example in C# source code, which is free for use under MPL license.

dxfimportnet.png

DXF Structure

DXF is an open ASCII format from Autodesk and you can easily find documentation on it in the web. Here are some words about it. Below is a very simple example, to show the main parts:

  0 
SECTION
  2
ENTITIES
  0
LINE
 10
39.19953392043317
 20
36.4554281665769
 30
0.0
 11
39.19953392043322
 21
736.4554281665768
 31
0.0
  0
ENDSEC
  0
EOF

0 - introduction of extended symbol names, following the "0"

SECTION, ENDSEC - begin / end of section. Sections can include Header, Entities, Objects. In the above code, you see only Entities section where the entities are.

LINE - begins LINE entity description. Lines:

10 

39.19953392043317 

mean X1 double value. The value after 20 is Y1, after 30 - Z1 (0 in 2D drawings). 11, 21 and 31 codes are consequently for X2, Y2, Z2. So here we see the line with coordinates (39.19.., 36, 45.. - 39,19.., 736,45..) - this is vertical line.

So our aim is to read this ASCII format. We need to load the file to stream and to take lines - even lines (0, 2, 4..) are CODE, odd lines (1, 3, 5...) are VALUE and repeat this procedure step by step till the end of file "EOF".

C#
// take a pair of lines in DXF file, repeat this till "EOF":
public void Next()
{
  FCode = Convert.ToInt32(FStream.ReadLine()); //code
  FValue = FStream.ReadLine(); // value
}
// for code=0 we create entities. Entities here are not only those which visible in AutoCAD.
// Entities can be also names of Sections and many other internal DXF objects.
// This method is called for all FCode == 0
public DXFEntity CreateEntity()
{
  DXFEntity E;
  switch (FValue)
  {
    case "ENDSEC":
      return null;   // here we do not create entity
    case "ENDBLK":
      return null;
    case "ENDTAB":
      return null;
    case "LINE":    // for "LINE" value we create DXFLine object
      E = new DXFLine();
      break;
    case "SECTION": // "SECTION" will be object to store other objects like Line
      E = new DXFSection();
      break;
    case "BLOCK": // create block object
      E = new DXFBlock();
      break;
    case "INSERT": // insert is reference to block.
      E = new DXFInsert();
      break;
    case "TABLE":
      E = new DXFTable();
      break;
    case "CIRCLE":
      E = new DXFCircle();
      break;
    case "LAYER":
      E = new DXFLayer();
      break;
    case "TEXT":
      E = new DXFText();
      break;
    case "MTEXT":
      E = new DXFMText();
      break;
    case "ARC":
      E = new DXFArc();
      break;
    case "ELLIPSE":
      E = new DXFEllipse();
      break;
    default: // there are many other objects are possible. For them we create empty Entity
      E = new DXFEntity();
      break;
  }
  // each Entity will need reference to the Base object Converter, which stores all Entities.
  E.Converter = this;
  return E; // return Entity and after it is added to the array of Entities
}  

The method to read properties of entities is essentially similar to the one described above but it has one important point: different entities have both identical and different properties. For instance, many Entities have "base point" - in DXF, which is described by codes: 10 (x), 20 (y), 30(z):

LINE
 10
39.19953392043317
 20
36.4554281665769
 30
0.0 

These codes are the same for LINE, CIRCLE, ELLIPSE, TEXT and for many others. So we can make Object-Oriented structure to read and to store the properties in order to avoid double-coding. We will store Layer and Base Point in entity "DXFVisibleEntity" which will be ancestor for all visible entities. Look at the code to read these properties:

C#
//base class for all visible entities
public class DXFVisibleEntity : DXFEntity
{
//Base point (x, y, z) for all entities
  public DXFImport.SFPoint Point1 = new SFPoint();
  // virtual function ReadProperty() is overridden in all descendants of Entity to read
  //specific properties
  public override void ReadProperty()
  {
  // for the different codes we read values
    switch (Converter.FCode)
    {
        //read Layer
      case 8:
        layer = Converter.LayerByName(Converter.FValue);
        break;
        //read Coordinates
      case 10: //X
        Point1.X = Convert.ToSingle(Converter.FValue, Converter.N);
        break;
      case 20: //Y
        Point1.Y = Convert.ToSingle(Converter.FValue, Converter.N);
        break;
        //read Color
      case 62:
        FColor = CADImage.IntToColor(Convert.ToInt32(Converter.FValue, Converter.N));
        break;
    }
  }
} 

We use the same approach to read the second coordinate in LINE, radius in Circle and so on.

DXF File and DXF Import .NET Structure

dxfimportnetstructure.png

This scheme shows main parts of DXF file and the way they are connected with the C# source code in the project. The dash lines stand for associations between DXF file objects and objects, programmed in C#.

CADImage is a class for loading from DXF file and drawing to Graphics. It stores the DXF Entities in field:

C#
public DXFSection FEntities;  

In the scheme, it is DXFSection.

DXFEntity is base class for all Entities classes. Classes DXFBlocks and DXFSection are not visible. Class DXFVisibleEntity is the ancestor for all visible Entities.

By the way, the scheme above is made in DXF format:) in ABViewer software.

CAD Tricks

If you are not familiar with AutoCAD, please pay attention to the structure of DXF entities. There is a special entity "Block" which may have many "inserts" in the CAD drawing. Block is just set of entities (including nested blocks) which can be inserted many times.

Note

Block changes many properties of element when showing it. 
So if you want to know the color of entity, it is not enough to read  
"Entity.Color"  - it is necessary to see all the Inserts and Blocks, 
in which this entity can be included. To get the correct color in DXF Import 
.NET project we made the following function: EntColor(DXFEntity E, DXFInsert Ins).

Please use EntColor() function get the correct Color type even if you do not have Blocks in the file. Pay attention that the most common color is "ByLayer" and in order to read the correct color, we need to read the color from Layer entity. This functionality is also provided in this function.

Below is the EntColor function. It has many tricks, for instance checking the layer.name == "0" - in DXF layer "0" is special and elements with color "ByLayer" get the color from Block if they are on "0" layer.

C#
//Use this func to know the color of Entity, DXFInsert is Insert entity or null. 
public static Color EntColor(DXFEntity E, DXFInsert Ins)
{
  DXFInsert vIns = Ins;
  DXFEntity Ent = E;
  Color Result = DXFConst.clNone;
  if(Ent is DXFVisibleEntity) Result = E.FColor;
  /*if(Ent is Polyline)
    Result = ((Polyline)Ent).Pen.Pen.Color;*/
  if(E.layer == null) return  Result; 
/* algorithm is rather difficult here. This is the way, how AutoCAD works with the colors,
if you try to create entities in AutoCAD, you will see how they use Colors */ 
  if((Result ==  clByLayer)||(Result == clByBlock))
  {
    if((vIns == null)||((Result == clByLayer)&&(Ent.layer.name != "0")))
    {
      if(Result == clByLayer)
      {
        if(Ent.layer.color != clNone)
          Result = Ent.layer.color;
        else Result = Color.Black;
      }
    }
    else
    {
      while(vIns != null)
      {
        Result = vIns.color;
        if((Result !=  clByBlock) && !((Result ==  clByLayer) &&
          (vIns.layer.name == "0")))
        {
          if(Result ==  clByLayer)
            Result = vIns.layer.color;
          break;
        }
        if((vIns.owner == null)&&(Result == clByLayer))
          Result = vIns.layer.color;
        vIns = vIns.owner;
      }
    }
  }
  if((Result == clByLayer)||(Result == clByBlock))
    Result = clNone;
  return Result;
}

How to Use the Software

The main code is in DXFImport.cs. You can just use this file in your project or see to it as an example of reading and visualization of DXF files.

Sample code to use DXFImport.cs is Form1.cs.

How to View Entities

In Form1.cs, we use the Form1_Paint event:

C#
private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
 //FCADImage - base class to reference to DXF
  if (FCADImage == null)
    return;
  FCADImage.Draw(e.Graphics); // CADImage.Draw() accepts Graphics to draw to
}

We can use FCADImage.Draw() for drawing to any Graphics - for instance, to printer. FCADImage.Draw() function should use a special algorithm, when each entity is drawn with the use of block/insert/layer parameters.

C#
public void Draw(Graphics e)
{
  if (FMain == null)
    return;
  FGraphics = e;
  // Iterate begins to  over the entities to draw all of them
  FEntities.Iterate(new CADEntityProc(DrawEntity), FParams);
}

Pay attention to FEntities.Iterate() func, it allows accessing all entities including their being inside the blocks. This is how it works: There is a class DXFGroup which is an ancestor of Entity and which can store array of Entities. For instance, Block is ancestor of DXFGroup and can store many entities like LINE. For better unification, we can use ONE BASE GROUP ENTITY object for all the drawing, this Entity will have array of all entities, each of them can also be the Group - the classic "Tree".

Iterate method finally should call Draw() for each Entity in order to draw it to the Graphics:

C#
protected static void DrawEntity(DXFEntity Ent)
    {
        Ent.Draw(FGraphics);
    }

Draw() method is overridden in descendants of Entity to draw particular entities. Let us see in detail how it is implemented in DXFLine:

C#
// draw line
public override void Draw(System.Drawing.Graphics G)
  {
    // points P1  (x1, y1) and P2 (x2, y2) of Line
    SFPoint P1, P2;
    // read color via EntColor to get real color
    Color RealColor = DXFConst.EntColor(this, Converter.FParams.Insert);
    // Read point 1 -convert global coordinates to the screen coordinates:
    P1 = Converter.GetPoint(Point1);
    //read point 2
    P2 = Converter.GetPoint(Point2);
    if (FVisible)
      G.DrawLine(new Pen(RealColor, 1),  P1.X, P1.Y, P2.X, P2.Y);
  } 
  1. We get the Real Color via DXFConst.EntColor(this, Converter.FParams.Insert); as I described before.
  2. Points are converted from Global Coordinates to screen coordinates in function GetPoint(). GetPoint not only converts global-to-screen but also uses Block offsets and block scale inside. Thus it facilitates the development work, eliminating the need to "see" what block is being drawn at the moment - Block changes "FParams.matrix" to draw itself. And all entities coordinates use this "FParams.matrix".
  3. Entity is drawn to the given Graphics G:

So you can draw to printer, to raster image or to other Graphics.

DXF Import .NET Reference

C#
public class DXFConst 

Stores constants and base functions.

C#
public class DXFMatrix 

Class to work with coordinates.

C#
public struct FRect 

Description of 3D space where the CAD drawing is situated in global coordinates.

C#
public struct CADIterate

Stores all needed parameters for entities when processing "Iterate" function.

C#
public class CADImage 

Class to draw CAD drawing.

C#
public class DXFEntity 

Base class for all DXF Entities.

C#
public class DXFGroup : DXFEntity

Base class for all group entities.

C#
public class DXFTable : DXFGroup 

Class to read from DXF "Table" section - here it reads only Layers.

C#
public class DXFVisibleEntity : DXFEntity

Base class for all visible entities (invisible - are "DXFTable", "DXFLayer", etc.)

C#
public class DXFCustomVertex: DXFVisibleEntity 

Special class for 3D point in DXF.

C#
public class DXFText: DXFCustomVertex

Stores and Draws "Text" DXF entity.

The following classes are for particular DXF entities:

C#
public class DXFLine : DXFVisibleEntity
public class DXFArc: DXFCircle
public class DXFEllipse: DXFArc
public class DXFLayer: DXFEntity
C#
public class DXFBlock : DXFGroup

Class to work with DXF Block.

C#
public class DXFInsert : DXFVisibleEntity  

Class to work with "Insert" in DXF, for AutoCAD users this is "Block reference". Blocks are not visible, Inserts are visible.

Conclusion

The purpose of the article is to give some advice how to write DXF readers. DXF file structure is not so difficult as its logical presentation. The article looks through the base DXF format problems and shows how to find solution for them. The example source is written in C# and may be helpful for all who need to have access to DXF files.

Other Projects on The Code Project

On The Code Project, you can already find another DXF reader:

The main advantages of our project as compared to the project above are:

  1. Block / Inserts
  2. Layers
  3. Text

which are not presented in that DXF reader.

History

This is the first open source version of DXF Import .NET.

License

This article, along with any associated source code and files, is licensed under The Mozilla Public License 1.1 (MPL 1.1)


Written By
Web Developer CADSoftTools
Russian Federation Russian Federation
CADSoftTools is specialized in CAD software development. The SDKs for reading AutoCAD DWG, DXF and HPGL formats are used in tens of countries by thousands of customers.
Codde Project developers can be interested in
CAD Import .NET SDK to read AutoCAD DWG and DXF, HPGL and CGM in managed code with C# and VB.NET examples
CADSoftTools provides DLL libraries for MS Visual C++, MS Visual Basic, MS .NET, Borland Delphi and Borland C++Builder.
Choose the proper SDK for reading AutoCAD DWG, DXF, HPGL PLT, CGM and SVG files
Plugins for IrfanView and XNView are a cheap and fast solution for viewing and managing DXF, DWG and HPGL files.
ABViewer is a professional CAD Viewer with a very competitive price.
The software specialists at CADSoftTools are currently engaged in developing the next generation of CAD software products.

Comments and Discussions

 
GeneralMy vote of 5 Pin
TheGEZ11-Dec-18 4:02
TheGEZ11-Dec-18 4:02 
QuestionSplines Pin
Mosi_627-Jul-18 1:09
professionalMosi_627-Jul-18 1:09 
QuestionHow to Scale drawings Pin
gunduzcagri9-Jan-17 11:42
gunduzcagri9-Jan-17 11:42 
QuestionTHANKS Pin
S.R.H28-Jan-16 7:45
S.R.H28-Jan-16 7:45 
QuestionError import file dxf with size large (9MB) Pin
nltd17-Dec-15 19:47
nltd17-Dec-15 19:47 
QuestionDXF rotate Pin
Member 1102584429-Sep-15 18:32
Member 1102584429-Sep-15 18:32 
QuestionCan only draw to form background Pin
Member 1102584430-Jun-15 17:41
Member 1102584430-Jun-15 17:41 
GeneralMy vote of 5 Pin
PierSilvio13-May-15 6:58
PierSilvio13-May-15 6:58 
SuggestionNice Pin
Arex_CE19-Nov-14 17:27
Arex_CE19-Nov-14 17:27 
Questioni want using Entity list data Pin
Member 1110520924-Sep-14 16:07
Member 1110520924-Sep-14 16:07 
Questionmirrored display of ARC included in INSERT Pin
hoerst18-Mar-14 1:11
hoerst18-Mar-14 1:11 
QuestionNeed SOLID, SPLINE Pin
sprezzatura8-Sep-13 15:22
sprezzatura8-Sep-13 15:22 
AnswerRe: Need SOLID, SPLINE Pin
Member 1061966323-Feb-14 19:22
Member 1061966323-Feb-14 19:22 
QuestionNeed Polyline Pin
prasad@123429-Apr-13 21:00
prasad@123429-Apr-13 21:00 
SuggestionCould you provide an example on how to use the DXFimport.cs on Console Programme? Pin
zweigoh17-Nov-12 16:50
zweigoh17-Nov-12 16:50 
QuestionDXF-Reader Pin
Member 870363624-Apr-12 4:54
Member 870363624-Apr-12 4:54 
Questionany suggestions Pin
MikeBi14-Oct-11 7:13
MikeBi14-Oct-11 7:13 
Good project.
But here are a couple of points I had to change.
I've converted the project in VB. The above facts are the suggestions for improvement in VB.

I needed the polyline
VB
Public Function CreateEntity() As DXFEntity
   Dim E As DXFEntity
   Select Case FValue
...
    Case "SEQEND"
        Return Nothing

    Case "POLYLINE"
        E = New DXFPolyLine()
    Case "VERTEX"
        E = New DXFLine()
...
End Function
	
Public Class DXFPolyLine
    Inherits DXFBlock

  Public Overrides Sub Loaded()
      Dim i As Integer
  
      For i = 0 To Entities.Count - 2
          If (TypeOf Entities(i) Is DXFLine) And (TypeOf Entities(i + 1) Is DXFLine) Then
              CType(Entities(i), DXFLine).Point2 = CType(Entities(i + 1), DXFLine).Point1
              CType(Entities(i), DXFLine).layer = Me.layer
              CType(Entities(i), DXFLine).FColor = Me.FColor
          End If
      Next
      If closed And Entities.Count > 2 Then
          If (TypeOf Entities(Entities.Count - 1) Is DXFLine) And (TypeOf Entities(0) Is DXFLine) Then
              CType(Entities(Entities.Count - 1), DXFLine).Point2 = CType(Entities(0), DXFLine).Point1
              CType(Entities(Entities.Count - 1), DXFLine).layer = Me.layer
              CType(Entities(Entities.Count - 1), DXFLine).FColor = Me.FColor
          End If
      ElseIf Not closed And Entities.Count > 2 Then
          Entities.RemoveAt(Entities.Count - 1)
      End If
  End Sub
    Public Overrides Sub Draw(ByVal G As System.Drawing.Graphics)
        For Each Ent As DXFEntity In Entities
            Ent.Draw(G)
        Next
    End Sub
End Class


I needed that because a block was nested in another block.
VB
Public Class DXFInsert

Public Overrides Sub Invoke(Proc As CADEntityProc, Params As CADIterate)
....
  Params.matrix = DXFMatrix.MatXMat(m_matrix, Params.matrix)
  Params.Scale.X = CSng(Scale.X * Params.Scale.X)
  Params.Scale.Y = CSng(Scale.Y * Params.Scale.Y)
...
End Sub


The scaling was also not so good. When the matrix is activ, you must use this also in the Draw function. Wink | ;)
One Example.
VB
Public Class DXFText

Public Overrides Sub Draw(ByVal G As Graphics)
   ...
   Dim h1 As Single = height * Converter.FScale
   If Converter.FParams.matrix IsNot Nothing Then
       h1 *= Converter.FParams.matrix.data(0, 0)
   End If
   ....
End Sub


Thank you

Mike
AnswerRe: any suggestions Pin
Member 205749824-Jul-13 9:25
Member 205749824-Jul-13 9:25 
QuestionDXF LAYERS Pin
mk148a23-Aug-11 15:55
mk148a23-Aug-11 15:55 
Questionthis softwere does not work well Pin
v.naeimabadi21-Apr-11 5:09
v.naeimabadi21-Apr-11 5:09 
AnswerRe: this softwere does not work well Pin
Chuzhakin21-Apr-11 22:07
Chuzhakin21-Apr-11 22:07 
GeneralMy vote of 3 Pin
ARon_14-Mar-11 10:48
ARon_14-Mar-11 10:48 
GeneralMy vote of 4 Pin
StewBob8-Mar-11 8:25
StewBob8-Mar-11 8:25 
GeneralWriting DXF Pin
hairy_hats7-Mar-11 1:25
hairy_hats7-Mar-11 1:25 
GeneralRe: Writing DXF Pin
Chuzhakin7-Mar-11 2:02
Chuzhakin7-Mar-11 2:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.