Click here to Skip to main content
11,644,286 members (72,114 online)
Click here to Skip to main content

A DXF Reader Solution and a Simple DXF Viewer

, 31 May 2011 CPOL 205.1K 19.1K 124
Rate this:
Please Sign up or sign in to vote.
This project gets a DXF file, extracts and interprets data and draws it on screen.
screenshot.jpg

Introduction

This project mainly deals with reading a DXF file, but in order to demonstrate the reader is working I also included a viewer, which interprets the data and draw it on the screen. In fact, at the beginning my sole purpose was to extract data from a DXF file but later on interpretation and drawing of the data on the screen started to take much more time and shaded the priority of the data extraction. After all of these, here is the result.

Background

There are a couple of DXF writer projects here in CodeProject (one is from Omid Shahabi, the other is from Claude Gagnon), but I couldn't find a DXF reader which reads DXF files. After various scans through the net, I came across the DXF specification of the AutoCAD and I decided to make my own reader. But then I found out that a reader by itself will have no value, there should also be a viewer. And the project become partially a DXF reader and mainly a viewer program, and I also made a drawing editor. However, the only interaction that the editor presents to the user is to highlight the shapes (to highlight keep shift button pressed while moving the cursor)... all drawings are made by the software. (I'll try to provide details later on.)

General Structure

DXF File DXF Reader + Interpretation Viewer Screen

Well, as you can see, the structure is as above. The data is extracted from the DXF file and interpreted and then necessary methods of the viewer are called and the result is shown on the screen.

Although the intended structure is as above, the code itself is not separated this much.

The application is an MDI application. You can open multiple DXF files for viewing.

There is a Canvas class for drawing and a Shape class for defining objects. Currently Line, Polyline, Circle and Arc shapes of the AutoCAD can be recognized. In the near future, I'm planning to add B-Spline too.

DXF Interpretation methods are included in the canvas class. Separating these methods from the drawing methods would be much better but for now this is all I can present.

Methods

When you click File/Open, the following method will be called:

private void menuItem2_Click(object sender, System.EventArgs e) //Opens openfile
						//dialog to select a DXF file
{
    inputFileTxt = "";

    openFileDialog1.InitialDirectory = "c:\\ "; //sets the initial directory of the
					//openfile dialog
    openFileDialog1.Filter = "DXF files (*.dxf)|*.dxf|All files (*.*)|*.*" ; //filters the
								//visible files...
    openFileDialog1.FilterIndex = 1 ;

    if (openFileDialog1.ShowDialog() ==
		System.Windows.Forms.DialogResult.OK) //open file dialog is shown here...
                                                         //if "cancel" button is clicked then
                                                         //nothing will be done...
    {
        inputFileTxt = openFileDialog1.FileName; //filename is taken
					//(file path is also included to this
                                                //name example: c:\windows\system\blabla.dxf

        int ino = inputFileTxt.LastIndexOf("\\ "); 	//index no. of the last "\"
						//(that is before the filename)
                                                  	//is found here

        newCanvas = new Canvas(); //a new canvas is created...
        newCanvas.MdiParent = this; //...its mdiparent is set...
        newCanvas.Text = inputFileTxt.Substring
		(ino+1, inputFileTxt.Length - ino - 1); //...filename is
                                                   //extracted from the text.(blabla.dxf).
        newCanvas.MinimumSize = new Size (500, 400); //...canvas minimum size is set...

        if(inputFileTxt.Length > 0)
        {
            newCanvas.ReadFromFile(inputFileTxt); //the filename is sent to the method
					//for data extraction and interpretation...
        }

        newCanvas.Show(); //the canvas is displayed...
        newCanvas.Activate();
        newCanvas.Focus();
    }

    openFileDialog1.Dispose();
}

As mentioned above, DXF interpretation is made in the Canvas class. Canvas class is a Windows Form. In addition to the standard namespaces, the following namespaces are included:

using System.IO;
using System.Drawing.Drawing2D;
using System.Data;

The ReadFromFile(string filename) method of the Canvas deals with extracting data from the DXF file and forwarding data to the necessary drawing methods:

public void ReadFromFile (string textFile) 	//Reads a text file
                                           	//(in fact a DXF file) for importing an
					//Autocad drawing.
{
    string line1, line2; //these line1 and line2 is used for getting the a/m data groups...

    line1 = "0"; //line1 and line2 are initialized here...
    line2 = "0";
    long position = 0;

    theSourceFile = new FileInfo (textFile); 	//the source file is set.
    StreamReader reader = null; 		//a reader is prepared...

    try
    {
        reader = theSourceFile.OpenText(); 	//the reader is set ...
    }
    catch (FileNotFoundException e)
    {
        MessageBox.Show(e.FileName.ToString() + " cannot be found");
    }
    catch
    {
        MessageBox.Show("An error occurred while opening the DXF file");
        return;
    }

    ////////////////////////////////////////////////////////////////////
    //This part interprets the drawing objects found in the DXF file...
    ////////////////////////////////////////////////////////////////////

    do
    {
        if (line1 == "0" && line2 == "LINE")
            LineModule(reader);
        else if (line1 == "0" && line2 == "LWPOLYLINE")
            PolylineModule(reader);
        else if (line1 == "0" && line2 == "CIRCLE")
            CircleModule(reader);
        else if (line1 == "0" && line2 == "ARC")
            ArcModule(reader);

        GetLineCouple (reader, out line1, out line2); //the related method is called
                                                      //for iterating through the text file
                                                 //and assigning values to line1 and line2...
    } while (line2 != "EOF");

    ////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////

    reader.DiscardBufferedData(); 	//reader is cleared...
    theSourceFile = null;
    reader.Close(); 		//...and closed.
}

Let me explain a little bit about the structure of a DXF file. In DXF files (they can be opened in Notepad), the data is stored in two-line (bi-line, dual, coupling, whatever you call it) structures. The first line contains a kind of an identifier (or a Tag) and the second line contains the data value. So in order to interpret a DXF file, we must interpret lines two-by-two.

Depending on this dual structure, we can interpret all entities that reside in a DXF file. But currently only LINE, LWPOLYLINE, CIRCLE and ARC entities can be recognizable. For the near future, I'm planning to add BSPLINE.

I provided plenty of comments in the source code, so please look in the source code itself for explanation of the modules.

DXF Viewer

Viewer part contains much more coding than the reader. As I mentioned above, currently I can draw a limited number of shapes. I hope to expand it in the near future.

While developing the Viewer, I got lots of ideas and knowledge from CodeProject. It varies from double buffering techniques to making a GradientBackground.

In the beginning, I said that the viewer is an MDI application. In this way, you can open multiple DXF files to view. After opening a file, if you click on the "Window" button in the main menu, you can see a list of the opened windows.

To make this, add a menu item to the main menu, and then in its properties find MdiList and change its value to "true".

I made the gradient background with overriding OnPaintBackground event:

protected override void OnPaintBackground
(System.Windows.Forms.PaintEventArgs e) //all drawing is made here in OnPaintBackground...
{
    base.OnPaintBackground(e);    //you must pass "e" to the base method

    ...

    Graphics g = e.Graphics;
    Rectangle rect = new Rectangle(this.pictureBox1.Location, this.pictureBox1.Size);
                              //In fact the pictureBox1 is hidden, the sole purpose of it is
                              //to get its dimensions for defining the drawing area.

    System.Drawing.Drawing2D.LinearGradientBrush brush =
			new System.Drawing.Drawing2D.LinearGradientBrush(
    rect,
    Color.SteelBlue,
    Color.Black,
    System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal);

    if (this.WindowState != FormWindowState.Minimized)
    {
        e.Graphics.FillRectangle(brush, rect); //gradient background
        Draw(g); //All drawing is made here...
    }

    brush.Dispose();
}

Conclusion

The main purpose of this project is to demonstrate that the DXF files can be read with the above mentioned techniques. In fact, the viewer part has a secondary priority at the beginning. Later on, I paid some attention to it, but I cannot claim that the viewer is composed of the best practices.

The compressed file for the demo application has the executable file and two sample DXF files. One of the DXF files is the one that can be seen in the screenshot. The drawing seems to be 3-D, but it is not. It is drawn in 2D...

Please feel free to send feedback.

History

  • 8th September, 2005: Added main version
  • 8th September, 2005: Updated source code and demo application to solve the decimal symbol conflict

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Evren Daglioglu
Software Developer
Turkey Turkey
No Biography provided

You may also be interested in...

Comments and Discussions

 
QuestionThank you and how can i read all the data of say line that is imported Pin
moonie19871-Apr-15 16:22
membermoonie19871-Apr-15 16:22 
Questioni want using Entity list data Pin
Member 1110520924-Sep-14 16:36
memberMember 1110520924-Sep-14 16:36 
GeneralMy vote of 1 Pin
Member 1089219818-Jun-14 0:41
memberMember 1089219818-Jun-14 0:41 
QuestionBSPLINE Support Pin
sysmith17-Sep-12 5:03
membersysmith17-Sep-12 5:03 
QuestionSplines/BSplines, Layers Pin
mBuchwald2-Mar-12 6:58
membermBuchwald2-Mar-12 6:58 
GeneralMy vote of 5 Pin
manoj kumar choubey17-Feb-12 23:59
membermanoj kumar choubey17-Feb-12 23:59 
Questionfields in which this application is used. Pin
rohitkandul3-Jan-12 5:08
memberrohitkandul3-Jan-12 5:08 
Questionhow can we edit the dxf file & save it Pin
bhavikkp11-Jul-11 1:42
memberbhavikkp11-Jul-11 1:42 
AnswerRe: how can we edit the dxf file & save it Pin
Evren Daglioglu12-Jul-11 0:36
memberEvren Daglioglu12-Jul-11 0:36 
QuestionHow to read dxf with 3d object Pin
bqhoang23-Jun-11 22:12
memberbqhoang23-Jun-11 22:12 
GeneralThank you so much Pin
hamio12-Mar-11 19:30
memberhamio12-Mar-11 19:30 
GeneralRe: Thank you so much Pin
Evren Daglioglu1-Jun-11 3:42
memberEvren Daglioglu1-Jun-11 3:42 
General.dxf image Pin
Pinank489-Mar-11 19:05
memberPinank489-Mar-11 19:05 
QuestionVery interested in - is there a C++ version? Pin
min_2_max23-Feb-11 19:05
membermin_2_max23-Feb-11 19:05 
AnswerRe: Very interested in - is there a C++ version? Pin
min_2_max2-Jun-11 14:52
membermin_2_max2-Jun-11 14:52 
GeneralMy vote of 1 Pin
Pavel Vladov20-Dec-10 23:29
memberPavel Vladov20-Dec-10 23:29 
GeneralCalculating arc' angle.. Pin
tamannashah199314-Oct-10 22:28
membertamannashah199314-Oct-10 22:28 
Generalgood job Pin
mostafa.elsadany3-Sep-10 18:58
membermostafa.elsadany3-Sep-10 18:58 
GeneralMy vote of 4 Pin
AftPeakTank5-Aug-10 5:31
memberAftPeakTank5-Aug-10 5:31 
Generaldxf to g-code Pin
fika_fa2-Jun-10 21:25
memberfika_fa2-Jun-10 21:25 
Generaldwg Pin
Unruled Boy15-Jan-10 17:12
memberUnruled Boy15-Jan-10 17:12 
GeneralMy vote of 1 Pin
Ashcool8-Jul-09 7:18
memberAshcool8-Jul-09 7:18 
Only draw a small point if you try to load another dxf file isn't on exemple.
GeneralMy vote of 1 Pin
gangjinhunningtu16-Jun-09 17:25
membergangjinhunningtu16-Jun-09 17:25 
Generalfailure to display Pin
InbarBarkai16-Apr-09 1:12
memberInbarBarkai16-Apr-09 1:12 
Generalcant we use AutoCAD's library to read DXF file Pin
prashant_pyxis5-Mar-09 1:52
memberprashant_pyxis5-Mar-09 1:52 
GeneralRe: cant we use AutoCAD's library to read DXF file Pin
InbarBarkai16-Apr-09 1:13
memberInbarBarkai16-Apr-09 1:13 
GeneralRe: cant we use AutoCAD's library to read DXF file Pin
bqhoang23-Jun-11 23:01
memberbqhoang23-Jun-11 23:01 
GeneralSystem.Drawing.Point vs System.Drawing.PointF Pin
Jeff Hastings22-Oct-08 18:39
memberJeff Hastings22-Oct-08 18:39 
QuestionDownload ? Pin
Freudi_t4-Dec-07 4:20
memberFreudi_t4-Dec-07 4:20 
Generaldrawing a INSERT entity Pin
KidAlchemy17-Oct-07 8:27
memberKidAlchemy17-Oct-07 8:27 
GeneralMerhabalar Pin
aaroncoumbye4-Oct-07 3:51
memberaaroncoumbye4-Oct-07 3:51 
GeneralDXF Reader Pin
Digital_Human25-Jun-07 9:48
memberDigital_Human25-Jun-07 9:48 
GeneralDoesn't work on my DXF Pin
Alas8-May-07 22:50
memberAlas8-May-07 22:50 
GeneralBSpline Support for DXF Reader Pin
Paul Gauthier16-Feb-07 11:19
memberPaul Gauthier16-Feb-07 11:19 
GeneralRe: BSpline Support for DXF Reader Pin
vraresh25-Nov-07 20:33
membervraresh25-Nov-07 20:33 
NewsBulge of LWPolyline not implemented Pin
Wouter DW4-Feb-07 23:19
memberWouter DW4-Feb-07 23:19 
QuestionDXF reader+manipulator Pin
buratino2223-Dec-06 20:21
memberburatino2223-Dec-06 20:21 
GeneralMissing mscoree.dll Pin
ckguru4-Oct-06 13:14
memberckguru4-Oct-06 13:14 
GeneralDxf file reader Pin
aniemsh6-Sep-06 18:15
memberaniemsh6-Sep-06 18:15 
GeneralIs there a way to use this code on compact framework? [modified] Pin
Thanya.NET29-May-06 6:55
memberThanya.NET29-May-06 6:55 
GeneralA DXF Reader Solution and A Simple DXF Viewer Pin
VanGen9-May-06 21:24
memberVanGen9-May-06 21:24 
GeneralSample Error Pin
radasys8-Sep-05 2:21
memberradasys8-Sep-05 2:21 
GeneralRe: Sample Error Pin
Evren Daglioglu8-Sep-05 4:17
memberEvren Daglioglu8-Sep-05 4:17 
GeneralRe: Sample Error Pin
a_david1232-Jul-07 0:26
membera_david1232-Jul-07 0:26 
GeneralRe: Sample Error Pin
Evren Daglioglu8-Sep-05 5:51
memberEvren Daglioglu8-Sep-05 5:51 
GeneralRe: Sample Error Pin
Evren Daglioglu8-Sep-05 6:40
memberEvren Daglioglu8-Sep-05 6:40 
GeneralRe: Sample Error Pin
radasys8-Sep-05 6:55
memberradasys8-Sep-05 6:55 
GeneralRe: Sample Error Pin
BLJBLJ25-Sep-08 2:00
memberBLJBLJ25-Sep-08 2:00 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150731.1 | Last Updated 1 Jun 2011
Article Copyright 2005 by Evren Daglioglu
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid