SDXF – Python Library for DXF

Stani’s DXF library for python is an excellent tool for writing lines, circles, and polygons in DXF format. DXF (Document Exchange Format) is an ASCII file format published by AutoCad which can be read by a variety of programs, including Blender, Maya, CorelDraw, and a host of others.

I’ll attempt to document the library here as I figure it out, but am no longer actively working with this library. As of July 2012, it has a new home on GitHub! If you have an update / bug fix, you can submit a pull request.

Download SDXF 1.1.1

Changes in 1.1.1

  • Added support for LWPOLYLINE, so you can now make a continuous polyline instead of several separate lines

Example Code

This will draw a line from (0,0) to (1,1) and “Hello World” at (3,0)

import sdxf

d=sdxf.Drawing()

#set the color of the text layer to green
d.layers.append(sdxf.Layer(name="textlayer",color=3))

#add drawing elements
d.append(sdxf.Text('Hello World!',point=(3,0),layer="textlayer"))
d.append(sdxf.Line(points=[(0,0),(1,1)], layer="drawinglayer"))

d.saveas('hello_world.dxf')

Overview

Entities

An Entity is an individual drawing object, like a line or circle. These are appended to the Drawing and rendered in the order they’re added.

Layers

Layers are used to organize entities. Layers can be assigned colors to make drawings easier to read. An entity can be assigned to a new layer on the fly, without explicitly defining the layer first.

Layer(name="mynewlayer",color=8)

Blocks

Blocks are reusable symbols. A block is defined once and can then be appended to the drawing using the Insert entity. A block can be inserted multiple times into a drawing, at different points.

#define the block, a Solid and an Arc
b=Block('test')
b.append(Solid(points=[(0,0,0),(1,0,0),(1,1,0),(0,1,0)],color=1))
b.append(Arc(center=(1,0,0),color=2))

#create a new drawing
d=Drawing()

#add the block to the Blocks table, so it can be referenced later
d.blocks.append(b)

#add entities to the drawing, including the block using the Insert entity
d.append(Circle(center=(1,1,0),color=3))
d.append(Face(points=[(0,0,0),(1,0,0),(1,1,0),(0,1,0)],color=4))
d.append(Insert('test',point=(3,3,3),cols=5,colspacing=2))
d.append(Line(points=[(0,0,0),(1,1,1)]))

Supported Entities

These entities are currently in the library. In addition to passing the arguments for the individual entity type, you can pass common arguments (group codes) which are available for all entities.

Common Group Codes

  • color – the color of the entity. Represented by a number. See the Color List below.
  • extrusion – ?
  • layer – which layer to place the element on. You do not need to explicitly declare a layer before assigning entities to it
  • lineType – ?
  • lineTypeScale – ?
  • thickness – thickness of the entity lines
  • parent – ?

Arc

Draws an arc (part of a circle).

  • center (x, y, z) – The center of the circle from which the arc is to be taken. Z is optional.
  • radius – The radius from the center to the arc
  • startAngle – The angle, in degrees, for the start of the arc.
  • endAngle – The angle, in degrees, for the end of the arc
Arc(center=(3,0),radius=2,startAngle=0,endAngle=90)

Circle

Draws a circle.

  • center (x,y,z) – the center of the circle. Z is optional.
  • radius – the radius of the circle
Arc(center=(3,0),radius=2)

Face

Creates a 3d face. A 3d face takes 4 points, which may or may not all be on the same plane.

Insert

Blocks are added to a file using the Insert entity. The block must be added to the Blocks table before it can be used.

  • name – Block name (defined when the block was added to the Blocks table)
  • point – Insertion point (x,y,z) to add the block
  • xscale – x scale factor; optional, defaults to 1
  • yscale – y scale factor; optional, defaults to 1
  • zscale – z scale factor; optional, defaults to 1
  • cols – column count; optional, defaults to 1
  • colspacing – column spacing; optional, defaults to 0
  • rows – row count; optional, defaults to 1
  • rowspacing – row spacing; optional, defaults to 0
  • rotation – rotation angle; optional, defaults to 0
Insert('test',point=(3,3,3),cols=5,colspacing=2)

Line

Makes a line! Takes a list containing two points. Points can be (x,y) or (x,y,z)

Line(points=[(0,0),(1,1)])

LwPolyLine

Makes a line with vertexes. Takes a list of points.

linePoints = [(0,0),(1,1),(1,0)]
LwPolyLine(points=linePoints,flag=1)

Polyline

In the current implementation, actually just makes a bunch of Lines rather than a polyline.

Point

A point in space. Takes a point (duh).

Solid

From what I can tell, this creates a 3D solid by taking either 3 or 4 points and then extruding the face in various directions.

Text

Renders a string as text at the given point.

Text('Hello World!',point=(3,0))

Mtext

I think this is like Text but supports line breaks. In this version of SDXF it just creates multiple Text entities.

Extras

These are not actual DXF entities, but are classes that make building other shapes easier.

Rectangle

Creates a rectangle using 4 lines. Could probably be modified to use LwPolyLine instead.

  • point – lower left (?) corner point
  • width – rectangle width
  • height – rectangle height
  • solid – ?
  • line – ?

Line List

Creates a bunch of lines from a set of points. Currently used instead of PolyLine.

  • points – list of verticies
  • closed – whether to close the shape; defaults to 0

Color List

The colors may vary depending on the rendering software used.
1 – Red
2 – Yellow
3 – Green
4 – Cyan
5 – Blue
6 – Magenta
7 – White
8 – Black

39 thoughts on “SDXF – Python Library for DXF”

  1. Thanks so much for this page Kellbot! I couldn’t find a copy of sdxf anywhere, much less such a useful and concise explanation.

    I am hoping to produce a solar concentrator dish with it — will let you know how it turns out.

    Andy 🙂

  2. This is a great tool for the kind of thing I’m trying to do (highway alignment related calculations). Unfortunately the LWPOLYLINE object doesn’t seem to work. Whenever I try and import the dxf into AutoCAD, I get an error:

    “Undefined group code 70 for object on line 138.”

    When I use the POLYLINE object (which produces many individual lines) it imports ok, but the LWPOLYLINE doesn’t seem to work.

    I’ll do more tests and see what I can discover.

    1. Hm, interesting. I haven’t tried it with AutoCAD, just QCAD, and I honestly haven’t put it through its paces, so there’s bound to be a few snags in LWPOLYLINE. Let me know if you figure out where it’s coming from!

  3. I am a Machinist and dxf is practically my life. I am currently working on a C library for dxf, so this can be helpful to me. Thanks!

  4. I did a bit of messing around with the original PolyLine class during my morning commute and it seems to work now (ie. it generates a dxf containing a polyline that AutoCAD will accept), but it still needs a lot of testing. In particular I want to see if it works for polylines with different Z coordinates on each vertex. (I only tested it with an XY list.) Kell, let me know if you want me to send it to you as it is now, otherwise I’ll debug it a bit more first.

  5. I fussed with the PolyLine class and now Autocad2009 seems to accept it.

    class PolyLine(_Entity):
    def __init__(self,points,flag=1,width=None,**common): #Not sure if any other values of flag will work
    _Entity.__init__(self,**common)
    self.points=points
    self.width=width
    self.flag=flag
    def __str__(self):
    result= ‘0\nPOLYLINE\n%s\n66\n%s\n’%\
    (self._common(),self.flag)
    result+=’%s’ %_point((0.,0.,0.))
    for point in self.points:
    result+=’\n0\nVERTEX\n8\n%s\n%s’% (self.layer,_point(point))
    if self.width:result+=’\n40\n%s\n41\n%s’%(self.width,self.width)
    result+=’\n0\nSEQEND’
    return result

  6. I have the same issue about LwPolyLine.
    It’s show “Undefined group code 70 for object on line 138.” when I open dxf file with AutoCAD.
    Please let me know if it can be solved.
    Thanks.

  7. DWG TrueView and Intellicad will open the dxf generated via the module test using the following class modified from the one provided by David:
    ————————————–
    class PolyLine(_Entity):
    ”’Polyline”’
    def __init__(self, points, flag=0, width=None, **common):
    _Entity.__init__(self, **common)
    self.points = points
    self.flag = flag
    self.width = width

    def __str__(self):
    result = ‘0\nPOLYLINE\n%s\n66\n1\n70\n%s\n’ % (self._common(), self.flag)
    result += ‘%s’ % _point((0.0, 0.0, 0.0))
    for point in self.points:
    result += ‘\n0\nVERTEX\n8\n%s\n%s’ % (self.layer,_point(point))
    if self.width:
    result += ‘\n40\n%s\n41\n%s’ % (self.width, self.width)
    result += ‘\n0\nSEQEND’
    return result
    ————————–
    I’ve set code 66 as 1 and added code 70 to accept the standard polyline flags.

    In the “PolyLine” call in the module test, change “closed” to “flag”; leave the value set as “1” for a closed polyline.

    I’ve been using the following resources to help understand the file format:
    http://autodesk.com/techpubs/autocad/acad2000/dxf/
    http://local.wasp.uwa.edu.au/~pbourke/dataformats/dxf/dxf10.html

  8. Hi ,
    I have tried to run Example code of Hello World with Python 2.6.4. When tried to run the program, the message is “There’s an error in your program: invalid syntax”.

    The item that highlighted in the pythons code is “6” of Python 2.6.4.

    Ca you please help in sorting out.

    Thanks

    Chinnaswamy

  9. Hello,
    how can I draw a point, I can not find out the exact syntax.

    d.append(sdxf.Point(points=[(2,2)]))

    This does not work for me.
    I am opening the resulting file with qcad. Drawing Lines and Text like in the example works fine.

    Johannes

  10. I found that even in your test code at the end of sdxf.py
    There is no test for Point.
    You should complete your testcases.

    1. Hi johannes,

      I’m not working on this project at the moment, but if you make improvements I’d be happy to add them.

      I need to move this onto GitHub but haven’t had the spare cycles to do so. Perhaps someone already has?!

    1. Hi Franco, this is all the documentation there is, sorry! But if you play with it and want to add to the documentation, send it to me and I can add it.

      Hola Franco, esta es toda la documentación que hay, lo siento! Pero si usted trabaja con él y desea agregar a la documentación, me lo envíe y puedo añadir.

  11. For those banging their headers against a brick wall with lwpolylines:
    The issue with LWPOLYLINEs is that they were only introduced in R14. Autocad (unlike perhaps other dxf readers?) is a bit strict and believes the version number it is given in the dxf file and carps if it sees entities that shouldn’t exist in R10 files. Unfortunately bumping the release number up to emulate R14 files isn’t sufficient as you also need to have the code generate handles for lots of entities. So far I can’t get a set of handles that doesn’t make autocad fall over…

  12. I have this traceback
    Traceback (most recent call last):
    File “v.WESdaSDFtoGRASS.py”, line 171, in
    sys.exit(main())
    File “v.WESdaSDFtoGRASS.py”, line 143, in main
    d.append(sdxf.PolyLine(points=linePoints,flag=1))
    File “C:\Program Files\GRASS GIS
    6.4.3svn\etc\python\sdxf.py”, line 556, in __init__
    _Entity.__init__(self,**common)
    TypeError: __init__() got an unexpected keyword argument
    ‘flag’
    (Thu Oct 09 04:41:51 2014) Comando terminato (3 sec)
    (Thu Oct 09 04:43:59 2014)
    v.WESdaSDFtoGRASS.py dns=C:\Users\Giuliano\Desktop4_riu_chixinagghju_prova.RASexport.sdf output_esond=C:\Users\Giuliano\Desktop\provissima2.dxf
    Traceback (most recent call last):
    File “v.WESdaSDFtoGRASS.py”, line 171, in
    sys.exit(main())
    File “v.WESdaSDFtoGRASS.py”, line 143, in main
    d.append(sdxf.PolyLine(points=linePoints,flag=1))
    File “C:\Program Files\GRASS GIS
    6.4.3svn\etc\python\sdxf.py”, line 556, in __init__
    _Entity.__init__(self,**common)
    TypeError: __init__() got an unexpected keyword argument
    ‘flag’

  13. can anybody tell me how to recognize closed shapes for example a square,rectangle or any quadrilateral in dxf file?

  14. Of Paul’s cathedral created Outdated Unhappinessis house|the household
    of Old Misery was designed by Christopher Wren, who
    had been the seventeenth-century builder A great copy editor appreciates grammar rules and
    the English terminology inside. Plus, our authors have an extensive,
    general knowledge of the publishing market. Accuracy, rate, and focus on depth are crucial skills demonstrated by the professional
    editing solutions of FirstEditing. Paul’s cathedral|Wren, who had been the seventeenth-century
    designer A CV writing support needs to have experience in every areas.
    They’ve the ability to understand what employers need, they’ve the capacity to highlight your functions, triumphs and advantages.
    The truth is, if you do not have an application that is well-written;
    it means you’re previously dropped within the competitiveness.

    Really, everyone really wants to be a success and you may
    accomplish this if you seek the aid of professional writing companies.
    Paul’s cathedral created Previous Miseryis house|the property of Aged Unhappiness was created by Wren, who had been the seventeenth-century designer I was ready
    to obvious IELTS(7) by following your website. Paul’s cathedral|Christopher Wren, who
    was the seventeenth century architect A friend of the friend’s uncle.
    Ofcourse, asking your relatives inside the tenth creation and their numerous
    friends continues to be an idea that is better
    than ordering report using an unknown corporation but occasionally perhaps they CAn’t save you from your difficulty of the report to the theme that is complicated and
    upcoming deadlines. WE, to the other hand, are very timely and
    responsible for our clients, supporting them with all necessary information of creating your order to the process.
    Paul’s cathedral designed the residence of Old Agony|Wren, who had
    been A reporter that is good needs to have many characteristics.
    To begin with, he must increase the truth rather than whispers of ill media that
    is founded. Only authenticated information ought to be offered.
    Secondly, he must be unbiased and not favor any class. He shouldn’t harm
    the statements of any specific area. That is extremely important in a pluralistic (multicultural and multiple-strict) community like India.

    Paul’s cathedral designed the household of Aged Unhappiness|Wren, who had been A
    great individual statement should clearly reveal
    why you intend to take legislation up. Why fantastic entry documents typically focus
    on the consumer’s enthusiasm in its discussion this is.

    Be a storyteller and walk the viewer during your individual encounters which encouraged
    one to wish to turn into a lawyer. Paul’s cathedral|Wren, who was simply the seventeenth-century builder Of Paul’s cathedral|Christopher Wren, who was simply the seventeenth-century designer A
    thorough set of sources is also of-value in analyzing the caliber of the document itself and realising your
    efforts in its system. See the Referencing Information on the UCB Portal (log in required) for information on how exactly to present recommendations correctly
    in your published work.

  15. Of Paul’s cathedral designed Previous Agony’s property|the home of Previous Agony was created by Wren, who had
    been the seventeenth century architect Your final look for grammar and punctuation mistakes
    is definitely occasion well-spent, because grading is affected By the appropriate utilization of
    common Language. Paul’s cathedral|Christopher Wren, who was the
    seventeenth-century builder PR and report release
    submissions should be included by your approach in the very least, to membership
    organizations and your regional company magazine.
    Paul’s cathedral created Aged Misery’s residence|the home of Old Agony was designed by Wren, who was simply the seventeenth-century builder An obvious, brief, and identified thesis statement occurring in the first paragraph of the essay.
    Paul’s cathedral|Christopher Wren, who was simply the seventeenth-century architect Be certain together with your guidelines and offer the detailed demands to make sure we do not miss anything out to people.

    Paul’s cathedral created the household of Outdated Unhappiness|Wren,
    who was simply A superb dissertation takes some time to get ready and write,
    thus begin to contemplate it and do the research properly prior to the article
    timeline (even yet in timed circumstances, such as checks, it’s important to make an effort to prepare
    and composition the essay before starting to write). Paul’s cathedral designed the property of Old Unhappiness|Wren, who was A realization must take on an essay together.
    Paul’s cathedral|Christopher Wren, who was the seventeenth-century builder Of Paul’s cathedral|Wren, who
    was the seventeenth century builder Publicrelations program and a marketing doesn’t have to be complex.
    Actually, it ought to be very simple so that you are more more likely to abide by
    it. You’re far more prone to satisfy your targets when you have a simple approach that you
    just have integrated with your schedule. You will view effects should you choose five to five approaches to market your business and repeat
    them constantly. Furthermore, free publicity chances are outthere foryou!

  16. What’s Going down i am new to this, I stumbled upon this
    I have discovered It absolutely useful and it has helped me
    out loads. I hope to give a contribution & help
    different customers like its helped me. Good job.

  17. Hi, i feel that i noticed you visited my website so i
    got here to return the want?.I am trying to find things
    to improve my web site!I guess its ok to make use of some of your ideas!!

  18. I used to be recommended this blog by way of my cousin. I’m now not sure whether this put up is
    written by him as no one else realize such distinctive approximately my trouble.
    You’re wonderful! Thanks!

  19. Ԝith haᴠin so much content do you ever run into any
    issues of plagorism or copyright violаtion? My website has a lot of exclusive content I’ve either authοrеd myself or
    outsourced but it appeaгs a lot of it is popping it up all
    over the internet without my permission. Do yoս know
    any methods to help protect against content from being stolen? I’d truly appreciate it.

  20. I would like to thank you for the efforts you’ve
    put in penning this website. I really hope to check out the
    same high-grade content from you later on as well. In fact, your creative writing abilities
    has motivated me to get my very own site now 😉

  21. Hi there to every body, it’s my first pay ɑ
    visit of this webpage; thіs web site сontains remarkable and truⅼy excellent material designed for
    readers.

Leave a Reply

Your email address will not be published. Required fields are marked *