GithubHelp home page GithubHelp logo

mozman / ezdxf Goto Github PK

View Code? Open in Web Editor NEW
878.0 32.0 184.0 61.03 MB

Python interface to DXF

Home Page: https://ezdxf.mozman.at

License: MIT License

Python 90.88% Cython 1.55% Common Lisp 0.01% Gnuplot 3.06% Prolog 4.49% C 0.01%

ezdxf's Introduction

ezdxf

Abstract

This Python package is designed to facilitate the creation and manipulation of DXF documents, with compatibility across various DXF versions. It empowers users to seamlessly load and edit DXF files while preserving all content, except for comments.

Any unfamiliar DXF tags encountered in the document are gracefully ignored but retained for future modifications. This feature enables the processing of DXF documents containing data from third-party applications without any loss of valuable information.

Quick-Info

  • ezdxf is a Python package to create new DXF files and read/modify/write existing DXF documents
  • MIT-License
  • the intended audience are programmers
  • requires at least Python 3.9
  • OS independent
  • tested with CPython and pypy3
  • has type annotations and passes mypy --ignore-missing-imports -p ezdxf successful
  • additional required packages for the core package without add-ons
  • read/write/new support for DXF versions: R12, R2000, R2004, R2007, R2010, R2013 and R2018
  • additional read-only support for DXF versions R13/R14 (upgraded to R2000)
  • additional read-only support for older DXF versions than R12 (upgraded to R12)
  • read/write support for ASCII DXF and Binary DXF
  • retains third-party DXF content
  • optional C-extensions for CPython are included in the binary wheels, available on PyPI for Windows, Linux and macOS
  • command line script ezdxf to display, convert and inspect DXF files

Included Extensions

Additional packages required for these add-ons are not automatically installed during the basic setup, for more information about the setup & dependencies visit the documentation.

  • The drawing add-on is a translation layer to send DXF data to a render backend, interfaces to matplotlib, which can export images as PNG, PDF or SVG, and PyQt5 are implemented.
  • r12writer add-on to write basic DXF entities direct and fast into a DXF R12 file or stream
  • iterdxf add-on to iterate over DXF entities from the modelspace of huge DXF files (> 5GB) which do not fit into memory
  • Importer add-on to import entities, blocks and table entries from another DXF document
  • dxf2code add-on to generate Python code for DXF structures loaded from DXF documents as starting point for parametric DXF entity creation
  • acadctb add-on to read/write plot style files (CTB/STB)
  • pycsg add-on for basic Constructive Solid Geometry (CSG) modeling
  • MTextExplode add-on for exploding MTEXT entities into single-line TEXT entities
  • text2path add-on to convert text into outline paths
  • geo add-on to support the __geo_interface__
  • meshex for exchanging meshes with other tools as STL, OFF or OBJ files
  • openscad add-on, an interface to OpenSCAD
  • odafc add-on, an interface to the ODA File Converter to read and write DWG files
  • hpgl2 add-on for converting HPGL/2 plot files to DXF, SVG and PDF

A simple example:

import ezdxf
from ezdxf import colors
from ezdxf.enums import TextEntityAlignment

# Create a new DXF document.
doc = ezdxf.new(dxfversion="R2010")

# Create new table entries (layers, linetypes, text styles, ...).
doc.layers.add("TEXTLAYER", color=colors.RED)

# DXF entities (LINE, TEXT, ...) reside in a layout (modelspace, 
# paperspace layout or block definition).  
msp = doc.modelspace()

# Add entities to a layout by factory methods: layout.add_...() 
msp.add_line((0, 0), (10, 0), dxfattribs={"color": colors.YELLOW})
msp.add_text(
    "Test", 
    dxfattribs={
        "layer": "TEXTLAYER"
    }).set_placement((0, 0.2), align=TextEntityAlignment.CENTER)

# Save the DXF document.
doc.saveas("test.dxf")

Example for the r12writer, which writes a simple DXF R12 file without in-memory structures:

from random import random
from ezdxf.addons import r12writer

MAX_X_COORD = 1000
MAX_Y_COORD = 1000

with r12writer("many_circles.dxf") as doc:
    for _ in range(100000):
        doc.add_circle((MAX_X_COORD*random(), MAX_Y_COORD*random()), radius=2)

The r12writer supports only the ENTITIES section of a DXF R12 drawing, no HEADER, TABLES or BLOCKS section is present, except FIXED-TABLES are written, than some additional predefined text styles and line types are available.

Installation

Basic installation by pip including the optional C-extensions from PyPI as binary wheels:

pip install ezdxf

Full installation with all dependencies (matplotlib, PySide6) for using the drawing add-on:

pip install ezdxf[draw]

For more information about the setup & dependencies visit the documentation.

Command Line

Use python -m ezdxf ... if your shell can't find the ezdxf script.

Get additional help for a sub-command:

ezdxf <cmd> -h

Preview DXF files in a graphical window:

ezdxf view <file.dxf>

Export the modelspace of DXF files as PNG|SVG|PDF:

ezdxf draw -o file.<png|svg|pdf> <file.dxf>

Print basic information about DXF files:

ezdxf info <file.dxf>

Show detailed information and structures of DXF files:

ezdxf browse <file.dxf>

Audit DXF files:

ezdxf audit <file.dxf>

Preview and convert HPGL/2 plot files:

ezdxf hpgl <file.plt>

Website

https://ezdxf.mozman.at/

Documentation

Documentation of the development version at https://ezdxf.mozman.at/docs

Documentation of the latest release at https://ezdxf.readthedocs.io/

Knowledge Graph

The knowledge graph contains additional information beyond the documentation and is managed by logseq. The source data is included in the repository in the folder ezdxf/notes. There is also a HTML export on the website which gets regular updates.

Contribution

The source code of ezdxf can be found at GitHub, target your pull requests to the master branch:

https://github.com/mozman/ezdxf.git

Feedback

Questions and feedback at GitHub Discussions:

https://github.com/mozman/ezdxf/discussions

Questions at Stack Overflow:

Post questions at stack overflow and use the tag dxf or ezdxf.

Issue tracker at GitHub:

http://github.com/mozman/ezdxf/issues

Release Notes

The release notes are included in the knowledge graph.

Changelog

The changelog is included in the knowledge graph.

Contact

Please always post questions at the forum or stack overflow to make answers available to other users as well.

[email protected]

Feedback is greatly appreciated.

Manfred

ezdxf's People

Contributors

andrewadev avatar bdon avatar chr15m avatar danielpompermayer avatar danofsteel32 avatar deltoro05 avatar dgriffin91 avatar ewsterrenburg avatar guyi2000 avatar hu-xiaonan avatar jaehaaheaj avatar joao-pm-santos96 avatar johnthagen avatar jrflack avatar k3rn3l3rr0r avatar luzpaz avatar maderero avatar mbway avatar mihirat avatar mozman avatar musicinmybrain avatar neiljackson1984 avatar nikolarobottesla avatar odidev avatar rossop avatar ru4ert avatar scotthilton avatar seanpk avatar wojsam avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ezdxf's Issues

Viewport.AcDbViewport crash

When calling the method AcDbViewport on an instance of Viewport the following crash happens.

File "lib\site-packages\ezdxf\modern\viewport.py", line 210, in AcDbViewport
return self.tags.sublasses[2]
AttributeError: 'ExtendedTags' object has no attribute 'sublasses'

This is due to a typo in this line self.tag.sublasses[2] - notice the missing c. It should instead be self.tag.subclasses[2].

For example when trying to use the Viewport method set_frozen_layers this crash occurs.

This is using version 0.8.8.

About table and hatch

Hi ,
I want to ask two question. Is it possible to create a table by row and col? And Can I use hatch By my .pat file?

Thank you.

Incorrect `entity.handle()` call?

https://github.com/mozman/ezdxf/blob/master/ezdxf/query.py#L251

Should the call on this line be entity.dxf.handle instead?

Currently, I'm getting an error trying to accomplish the following:

import ezdxf
drawing = ezdxf.readfile("path/to/some/file.dxf")

q = modelspace().query('INSERT')
entity = q[0]

query = ezdxf.query.new()
query.extend(entity) # error, not a sequence
query.extend([entity]) # error, object has no attribute 'handle'

Basically, I'm trying to create a query from scratch and add only some entities to it that I already have reference too and this led me to this potential problem. Perhaps in addition to this fix there could be an addition of query.add(Entity)? Thoughts?

I'll create a pull request with the required work, I just need to know what you'd prefer :)

dxf file not opening in Autocad

The following test script is meant to create a .dxf file with some line and circles. The script runs with no errors, but I am not able to load the dxf files on Autocad.

When I try to load the file on A360 view the error is "Unrecoverable exit code from extractor: -1073741831"

  1 import ezdxf                                                                    
  2 import numpy as np                                                              
  3 import scipy.io as sio                                                          
  4 import pathlib                                                                  
  5 import sys                                                                      
  6                                                                                 
  7 data = {'circles':[[5, [13, 2]], [19, [15, 15]], [19, [12, 4]], [8, [8, 13]],   
  8         [3, [29, 29]],[2, [8, 11]], [1, [2, 6]]],                               
  9         'lines':[[[12, 18], [3, 2], 'CONTINUOS', 'B'],                          
 10         [[29, 4], [18, 15], 'DASHED', 'A'],                                     
 11         [[5, 24], [10, 16], 'DASHED', 'A'],                                     
 12         [[8, 20], [21, 23], 'DOTTED', 'B'],                                     
 13         [[7, 28], [5, 25], 'CONTINUOS', 'B'],                                   
 14         [[3, 14], [4, 29], 'CONTINUOS', 'A'],                                   
 15         [[11, 16], [13, 3], 'DOTTED','A']]}                                     
 16         #line format [x_start, x_end], [y_start, y_end], style, layer           
 17                                                                                 
 18 dwg = ezdxf.new('AC1015') # Version necessary for saving images                 
 19 msp = dwg.modelspace()                                                          
 20 layout = dwg.layout()                                                           
 21                                                                                 
 22 dwg.layers.new(name = 'CIRCLES',dxfattribs={'linetype': 'DASHED', 'color': 5})  
 23 dwg.layers.new(name = 'A', dxfattribs={'color': 5})                        
 24 dwg.layers.new(name = 'B', dxfattribs={'color': 5})                        
 25 dwg.layers.new(name = 'C', dxfattribs={'color': 5})                        
 26                                                                                 
 27 # WRITE                                                                         
 28 for circle in data['circles']:                                                  
 29     r = circle[0]                                                               
 30     center = tuple(circle[1])                                                   
 31     msp.add_circle(center, r, dxfattribs = {'layer': 'CIRCLE'})                 
 32 print 'circle'                                                                  
 33                                                                                 
 34 for line in data['lines']:                                                      
 35     line_strt = (line[0][0], line[1][0])                                        
 36     line_end  = (line[0][1], line[1][1])                                        
 37     msp.add_line(line_strt, line_end, dxfattribs= {'linetype':line[2],          
 38         'layer':line[3]})                                                       
 39 print 'lines'                                                                   
 40                                                                                 
 41                                                                                 
 42                                                                                 
 43                                                                                 
 44 dwg.saveas('issue#01.dxf')    ``` 

polyline read as lwpolyline in DXF2007

I have librecad dxf that is saved as DXF2007
It contains this polyline:
image

I read this and it is returned as lwpolyline. When I save it into new dxf file I get this:
image

Shouldn't this be read as polyline so I can keep Arc inside this polyline?

add_image - size_in_units different from set value

Dear @mozman ,
I tried to set specific value in size_in_unit but when I open the dxf these values are different.

msp.add_image(insert=(4, 5), size_in_units=(12.1826,1.6305), image_def=my_image_def, rotation = 0)
When I open the CAD and check the image, I see:
12.1983,1.6326

Why is that? Is there anything I can do to safely get the required value in the output?
Thanks,
Gianluca

doc on pythonhosted.org is not searchable

There are two documentation sites:

Trying to search (using the builtin Sphinx based search running within browser):

  • the "readthedocs" works as expected
  • while the "pythonhosted" does not bring any results.

Proposed solution:

  • change README to show only the readthedocs site as it works (now it first shows the "pythonhosted"
    one)
  • if possible, fix the "pythonhosted" site (no idea, what can cause this), otherwise stop declaring
    this doc url.

Remove block layer link

First, thanks for this lib very usefull !
I search to dynamically remove layers from DXF file.

But some of layers are linked with an entity draw in a block. So, lib can't remove this layers.

Someone have solution to remove linked layers or remove entity in a bloc corresponding to one layer ?

Thank you for your help ! 😄

MTEXT dxf attrib for inital text group code

Mozman,

First off, fantastic library, you rock. Also, I'm back to working on DXF stuff so I'll be around and hopefully able to help add some features as I come across them.

Second, the MTEXT entity type is defined in a DXF to use group codes 1 as the initial 250 chars of text and then 3 as the additional as many as needed. Currently there is no way to query on either group code due to the definition in modern/mtext.py

Would it be possible to add at minimum group code 1 so we could use some filtering?

Then in the future perhaps there might be a way to allow for dxf attribs that span multiple group codes?

Thoughts?

--Harrison

Missing Entities

Thanks for this library; extremely useful!

As the title suggests, I have an issue with missing entities.

I'm able to view all the layers with ezdxf with no problem. Using an external program such as Solidworks' eDrawing application, I can confirm that there are entities in all the layers (stuff disappear when I make a layer hidden). However, when I try to see which entities are on a specific layer, I can't. This is the code I'm using:

*edit: I was running the code on dxfgrabber instead of ezdxf, but the issue is still the same :(

for layer in dxf.layers:
	layerItems = [entity for entity in dxf.entities if entity.dxf.layer == layer.dxf.name]
	print(layer.dxf.name, len(layerItems))

The output is something like:

0 3
Border (ANSI) 0
Center Mark (ANSI) 86
Centerline (ANSI) 4
Dimension (ANSI) 0
Hatch (ANSI) 0
Sketch Geometry (ANSI) 0
Symbol (ANSI) 8
Title (ANSI) 0
Title Block 0
Visible (ANSI) 517
Defpoints 0

Any ideas?
Thanks :)

loading and writing a DXF modifies it (and breaks converters).

Say I convert my dxf to a png, using libre office :

subprocess.call(['libreoffice', '--headless', '--convert-to', 'png', 'PFI350-3.dxf'])
I get a nice image.

But, and just by cloning the file :

dxf = ezdxf.readfile('PC-PFI-300-406.dxf')
ts = time.time()
dxf.saveas('%s.dxf' % ts)
subprocess.call(['libreoffice', '--headless', '--convert-to', 'png', '%s.dxf' % ts])

I get a white image.

Any ideas why?

Also if using libreoffice I convert the dxf to an svg, and then edit the file, I can clearly see that there is almost nothing in it. where did all the objects go?

r12writer creates invalid file on exception

The r12writer context doesn't close the file properly when an exception happens. See below for examples of what happens and what I expected.

The following snippet creates an invalid dxf file:

>>> ezdxf.version
(0, 8, 5)
>>> from ezdxf.r12writer import r12writer
>>> with r12writer("test.dxf") as dxf:
...   raise ValueError("")
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ValueError

This can be seen here:

>>> import ezdxf
>>> ezdxf.readfile("test.dxf")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/kjw53/Documents/code/survey_fix/venv/lib/python3.6/site-packages/ezdxf/filemanagement.py", line 118, in readfile
    dwg = read(fp, legacy_mode=legacy_mode, dxfversion=info.version)
  File "/home/kjw53/Documents/code/survey_fix/venv/lib/python3.6/site-packages/ezdxf/filemanagement.py", line 61, in read
    return Drawing.read(stream, legacy_mode=legacy_mode, dxfversion=dxfversion)
  File "/home/kjw53/Documents/code/survey_fix/venv/lib/python3.6/site-packages/ezdxf/drawing.py", line 296, in read
    return Drawing(tagreader)
  File "/home/kjw53/Documents/code/survey_fix/venv/lib/python3.6/site-packages/ezdxf/drawing.py", line 44, in __init__
    sections = load_dxf_structure(tagger)  # load complete DXF entity structure
  File "/home/kjw53/Documents/code/survey_fix/venv/lib/python3.6/site-packages/ezdxf/lldxf/loader.py", line 87, in load_dxf_structure
    raise DXFStructureError("DXFStructureError: missing ENDSEC tag.")
ezdxf.lldxf.const.DXFStructureError: DXFStructureError: missing ENDSEC tag.

However, this works (and it is also how I expected the context manager to work):

>>> with open("test.dxf", "w") as f:
...   dxf = R12FastStreamWriter(f)
...   try:
...     raise ValueError("")
...   finally:
...     dxf.close()
... 
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
ValueError

new insert with `.dxf.attribs_follow ==1` fails on .add_attribute

Steps to reproduce:

  • create a block
  • insert the block and set .dxf.attribs_follow=1 (either via dxfattribs or later explicitly .dxf.attribs_follow=1)
  • try insert.add_attrib(....)

add_attrib fails on attempt to get last of attributes which are at the moment none. see graphics.pyL537

Proposed solution

There are few places, where it could be affected, not sure, which one is the proper one:

  • creation of insert shall ignore attribs_follow value in dxfattribs and keep it 0.
  • call to _append_attrib_entity shall handle empty list of attributes

Workaround

When creating new insert, always ensure, the attribus_follow is kept in default value 0 even when planning adding some attributes.

Further linetype BYLAYER default issue

@mozman I have run into another BYLAYER=None issue where the string "None" is getting put into the DXF export which makes CAD programs throw an error upon load. I have a fix for this which I will PR now.

3D rotation?

Is there a way to rotate a (3D) block in other planes than XY?

modelspace.add_blockref('FLAG', point, dxfattribs={
    'xscale': random_scale,
    'yscale': random_scale,
    'rotation': (-15, point1, point2) # maybe like this?
    # or like this: 'rotation_axis': 'X' ?
})

Documentation is missing on reading geometry data for INSERT types

Hi, thank you for this great package!

I am struggling to re-draw the model I get from the DXF file. I know how to deal with LINE, ARC, etc. But these INSERT types seem to refer to pre-defined blocks, and I had no success to retrieve their info. Tutorials and references in https://ezdxf.readthedocs.io did not help either.

I am attaching some code just for the sake of clarity:

import ezdxf
dwg = ezdxf.readfile("./test_files/test_foot_internal.dxf")
model = dwg.modelspace()
all_data = {}
for e in model: # xdata[0][3] is apparently "element id"
    if (e.tags.xdata[0][3].value in all_data):
        all_data[e.tags.xdata[0][3].value].append(e)
    else:
        all_data[e.tags.xdata[0][3].value] = []
        all_data[e.tags.xdata[0][3].value].append(e)
i1 = all_data['1354459'] # air terminal
i1 = i1[0]
print("dxf.name = " + i1.dxf.name)
print("dxf.insert = " + str(i1.dxf.insert))
print("dxf.xscale = " + str(i1.dxf.xscale))
print("dxf.yscale = " + str(i1.dxf.yscale))
print("dxf.zscale = " + str(i1.dxf.zscale))
print("dxf.rotation = " + str(i1.dxf.rotation))
print("dxf.row_count = " + str(i1.dxf.row_count))
print("dxf.row_spacing = " + str(i1.dxf.row_spacing))
print("dxf.column_count = " + str(i1.dxf.column_count))
print("dxf.column_spacing = " + str(i1.dxf.column_spacing))
# shared:
print("dxf.handle = " + str(i1.dxf.handle))
print("dxf.layer = " + str(i1.dxf.layer))
print("dxf.linetype = " + str(i1.dxf.linetype))
print("dxf.color = " + str(i1.dxf.color))
print("dxf.paperspace = " + str(i1.dxf.paperspace))
# below code finds 4 instances but does NOT print ANYTHING
blockrefs = model.query('INSERT[name=="CLT_AirTerminal_Swirl - Flex 200-1320235-DATUM"]')
for b in blockrefs:
    for attrib in b.attribs():
        print("attrib.dxf.tag = " + str(attrib.dxf.tag))
        print("attrib.dxf.text = " + str(attrib.dxf.text))

AttributeError: entities

I get this error when using ezdxf.read() with stream from google cloud storage:

AttributeError: entities
/lib/ezdxf/sections/sections.py:69

ezdxf.readfile() working fine with same file (when not using google cloud storage).

Update: looks like this is fixed by removing CR characters from DXF files. Is it possible to support DXF files which are using CRLF as EOL?

Copy to clipboard failed.

On opening any with ezdxf created drawing in Autocad 2014 and trying to copy something I get: Copy to cliboard failed.

Too fast end in the TABLE BLOCK RECORD.

Hi,

Thanks for your work.

I try to transfert a block between two file and insert it.

I can open the dxf source with the original block, it's an Autocad save as to dxf.

When i open the new file, Autocad give me an error

Erreur dans la table BLOCK_RECORD Fin prématurée de l'objet à la ligne 2502. Entrée DXF incomplète ou non valable -- dessin ignoré.

BLOCK_RECORD
5
5FC
102
{ACAD_XDICTIONARY
360
5F3
102
}
330
1
100
AcDbSymbolTableRecord
100
AcDbBlockTableRecord
2
cartoucheA4
340
0
102
{BLKREFS
102
}
70
4
280
1
281
0
1001
AcDbDynamicBlockGUID
1000
{5586419D-FB6E-394D-82BC-A22B4349C6F1}
0
ENDTAB

There was an dynamic block in here but i delete it and purge.

Edit :
When i replace AcDbDynamicBlockGUID by Acad , it's work with Autocad. (Work with libreCAD with this issue)

Thx

MText change text issue

Hi Mozman,
First of thanks for this great package. It is awesome.
I have some issues with mtext. i try to change a mtext with below code. It works with out any error. But i got an autocad error when i try to open DXF (Invalid or incomplete DXF input -- drawing discarded.).

import ezdxf
dwg = ezdxf.readfile("DEMO.dxf")
msp = dwg.modelspace()
for i in msp.query("MTEXT"):
    with i.edit_data() as data:
        data += "append some text" + data.NEW_LINE
        data.text = "Replacement for the existing text."
dwg.saveas("output1.dxf")  

import ezdxf
dwg = ezdxf.readfile("DEMO.dxf")
msp = dwg.modelspace()
for i in msp.query("MTEXT"):
    i.set_text("some text")
dwg.saveas("output1.dxf")  

I checked original and changed DXF files. mtext group code 1 is moved under 101 (embed object) at changed file. I try to change it manually and move it to above 101 (like original). It works after this change.

Could you please help about this issue?
Autocad 2018 / DXF version AC1032
Python 3.6.6 / ezdxf 0.8.8

Original File: http://pasted.co/af623681
Output: http://pasted.co/fca4bca9
Output Manually Edited: http://pasted.co/af623681

Output (MText part):

100
AcDbMText
 10
2762.147931969048
 20
2327.073414283525
 30
0.0
 40
2.5
 41
18.85176797699841
 46
0.0
 71
1
 72
5									  
 73
1
 44
1.0
101
Embedded Object
 70
1
 10
1.0
 20
0.0
 30
0.0
 11
2762.147931969048
 21
2327.073414283525
 31
0.0
 40
18.85176797699841
 41
0.0
 42
15.42803547066848
 43
15.04263301500682
 71
2
 72
1
 44
18.85176797699841
 45
12.5
 73
0
 74
0
 46
0.0
  1
Replacement for the existing text.
  0
ENDSEC

Original (MText part):

100
AcDbMText
 10
2762.147931969048
 20
2327.073414283525
 30
0.0
 40
2.5
 41
18.85176797699841
 46
0.0
 71
     1
 72
     5
  1
{\fArial|b0|i0|c162|p34;CHANGE;\P\P\PTEXT}
 73
     1
 44
1.0
101
Embedded Object
 70
     1
 10
1.0
 20
0.0
 30
0.0
 11
2762.147931969048
 21
2327.073414283525
 31
0.0
 40
18.85176797699841
 41
0.0
 42
15.42803547066848
 43
15.04263301500682
 71
     2
 72
     1
 44
18.85176797699841
 45
12.5
 73
     0
 74
     0
 46
0.0							  
  0
ENDSEC

Release memory after usage

So i've noticed that dxf files can use huge amounts of memory compared to their initial file size (ie: 200mb dxf can use up to 5gb of memory).. but i'm wondering if there is a way to free up the memory after we are done reading our data.

What most libraries would do:

style 1:
with ezdxf.readfile(...) as dwg:
do_something(dwg)
#memory is cleared by this line

style 2:
dwg = ezdxf.readfile(...)
do_something(dwg)
dwg.close()
#memory is cleared by this line

It seems like none of these options exist for this particular library. Am i missing something obvious? Just having the python program exit is not an option, since my dxf reading is part of a webserver that runs indefinitely.

invalid handle while importing block entity

source_dwg = ezdxf.readfile(in_file1)
target = ezdxf.new(source_dwg .dxfversion)
importer = ezdxf.Importer(source_dwg, target_dwg)
importer.import_tables()
importer.import_modelspace_entities()
target .saveas(out_file)

I got errors:
Traceback (most recent call last):
File "E:/reseaux/example.py", line 49, in
get_reseaux()
File "E:/reseaux/example.py", line 46, in get_reseaux
importer.import_modelspace_entities()
File "C:\Users\y.song\AppData\Local\Programs\Python\Python36\lib\site-packages\ezdxf\tools\importer.py", line 52, in import_modelspace_entities
target_modelspace.add_entity(new_entity) # add entity to modelspace
File "C:\Users\y.song\AppData\Local\Programs\Python\Python36\lib\site-packages\ezdxf\legacy\layouts.py", line 124, in add_entity
for linked_entity in entity.linked_entities():
File "C:\Users\y.song\AppData\Local\Programs\Python\Python36\lib\site-packages\ezdxf\dxfentity.py", line 136, in linked_entities
entity = wrap(link)
File "C:\Users\y.song\AppData\Local\Programs\Python\Python36\lib\site-packages\ezdxf\legacy\factory.py", line 102, in wrap_handle
raise DXFKeyError('invalid handle #{}'.format(handle))
ezdxf.lldxf.const.DXFKeyError: 'invalid handle #287B'
capture

reading writing entites

what is the best way to read multiple DXF files and combine them into one?

I tried to read the entities from dxf but saving them into an empty dxf with add_entity(e) always produces and error.

I also did not find and easy way to move entities. Lets say I want to move them with a certain vector before saving them to DXF.

Traceback (most recent call last):
    dxf.saveas(target)
  File "C:\Python27\lib\site-packages\ezdxf\drawing.py", line 285, in saveas
    self.save(encoding=encoding)
  File "C:\Python27\lib\site-packages\ezdxf\drawing.py", line 296, in save
    self.write(fp)
  File "C:\Python27\lib\site-packages\ezdxf\drawing.py", line 303, in write
    self.sections.write(stream)
  File "C:\Python27\lib\site-packages\ezdxf\sections\sections.py", line 91, in write
    section.write(stream)
  File "C:\Python27\lib\site-packages\ezdxf\sections\entities.py", line 38, in write
    self._entity_space.write(stream, layout_keys)
  File "C:\Python27\lib\site-packages\ezdxf\entityspace.py", line 141, in write
    layout_spaces[key].write(stream)
  File "C:\Python27\lib\site-packages\ezdxf\entityspace.py", line 37, in write
    tags = self._entitydb[handle]
  File "C:\Python27\lib\site-packages\ezdxf\database.py", line 40, in __getitem__
    return self._database[handle]
KeyError: u'BA'

Generated DXF files can not be opened in TrueView

Hi. I'm trying to open a DXF file (readfile) and just save it first again (saveas). When I open this new file I get an error message from Autodesk TrueView:

Group 280 (was-a-zombie-flag) expected on line 180.
Invalid or incomplete DXF input -- drawing discarded.

I also tried a cleanup. Without success. What can i do?:-( See attachment, please. I use Python 3.7.0, ezdxf 0.8.8 and TrueView 2018.

dxf_test.zip

Problem creating viewports

It seems when adding viewports to the paper space, the first time it's not actually created. When added a second time it works correctly.
No viewport created:

import ezdxf

dxf = ezdxf.new('R12')
model = dxf.modelspace()
paper = dxf.layout()
model.add_polyline2d([(0, 0), (10, 10), (2, 7), (0, 0)])
paper.add_viewport(center=(105,145), size=(200,280), view_center_point=(0,0), view_height=22)
dxf.saveas('viewport.dxf')

Viewport correctly created:

import ezdxf

dxf = ezdxf.new('R12')
model = dxf.modelspace()
paper = dxf.layout()
model.add_polyline2d([(0, 0), (10, 10), (2, 7), (0, 0)])
paper.add_viewport(center=(105,145), size=(200,280), view_center_point=(0,0), view_height=22)
paper.add_viewport(center=(105,145), size=(200,280), view_center_point=(0,0), view_height=22)
dxf.saveas('viewport.dxf')

I'm using ezdxf 0.7.9 in python 2.7 on ubuntu.

Documentation: Python 3.5 is required

In the documentation, it is stated that:

ezdxf requires at least Python 2.7 and it’s Python 3 compatible

However, the library cannot be imported in Python <3.5 because of math.isclose which is new to Python 3.5.

Conda installation not adding templete files

The conda installation on conda-forge did not added the dxf template files (AC1009.dxf, ..., AC1032.dxf) in the template folder Lib/site-packages/ezdxf/templates/. There is a crash any time one of those files is required...

"Invalid XDATA structure" error

Hi there,

While reading a DXF file (version 'AC1027') I end up with following error:

raise DXFXDataError('Invalid XDATA structure, only group code >=1000 allowed in XDATA section')
ezdxf.lldxf.const.DXFXDataError: Invalid XDATA structure, only group code >=1000 allowed in XDATA section

From my understanding of AutoCAD and ezdxf, I suspect that ezdxf does not recognize "basepoint" object in a block definition. That's because if I use a file without these basepoints in the blocks, it runs just fine.

The simple code I use follows:

dxf = ezdxf.readfile("file.dxf")
for b in dxf.blocks:
    print(b.name)
    if not b.name.startswith('*'):
        for bb in b:
            print(bb)

Thanks in advance for any improvement or a simple reply
Jan

Why drawing arcs clock-wisely when adding hatches?

Why is drawing arcs clock-wisely default when adding it to a hatch boundary EdgePath, while counter-clock-wisely is the default when adding an arc to some layout?

Since layout.add_arc hasn't the is_counter_clockwise parameter, we cannot write some functions to draw some complex and useful objects and use them to fill those objects.

about block

I have see your document about How to Get/Set block reference attributes,but i still do not know how to get block reference attributes. Please you tell me how to do that in detail. Thank you! And I am weak in English,so please use simple terms.Thank you!

Example Correction

I love the library, which is helping me to create the new import features for OpenJSCAD.org

I found that the mesh.py example creates inconsistent clockwise versus counter-clockwise faces. The impact is that the face orientation cannot be determined; outward versus inward facing.

I believe that Autocad creates all faces CCW and facing outward (right-handed rule). Please correct if not so.

Here's the fix:

6 cube faces

cube_faces_wrong = [
[0, 1, 2, 3],
[4, 5, 6, 7],
[0, 1, 5, 4],
[1, 2, 6, 5],
[3, 2, 6, 7],
[0, 3, 7, 4],
]
cube_faces = [
[0, 3, 2, 1],
[4, 5, 6, 7],
[0, 1, 5, 4],
[1, 2, 6, 5],
[3, 7, 6, 2],
[0, 4, 7, 3],
]

Image import flags

Hello! You've done a great module, thank you.
Is it possible to add two or more flags when importing image or any other object type?
Image.dxf.flags has four possible flags - IMAGE_SHOW (1), IMAGE_SHOW_WHEN_NOT_ALIGNED (2), IMAGE_USE_CLIPPING_BOUNDARY (4) and IMAGE_TRANSPARENCY_IS_ON(8)

When I use flag IMAGE_TRANSPARENCY_IS_ON(8) the transparensy is on but the image disappears. I suppose it turns off IMAGE_SHOW (1) flag

If it is applicable, I could help you with documentation, for example, tutorials

Images don't show in AutoCAD until you manually Reload them in the xref manager

Images with relative paths fail to show on DXFs opened in AutoCAD by default. XRef manager shows them as !unreadable. You have to go to the xref manager and manually 'Reload' them before they show.

##POTENTIAL FIX:
I found that you need to add the following to the headers section

'''
9
$PROJECTNAME
1

'''

##REASON:
If the value after the 1 is left blank, it uses the DXF file's path as the initial place to look when loading images and shows the images straight away.

How to split layers into dxf files?

Sorry for this. It should be a help information.

I check doc and tutorials to find means to split layers from a source dxf file into different dxfs which will only contain one layer corresponding to source dxf.

dwg = ezdxf.readfile("source.dxf")
for layer in dwg.layers:
....dwg_new = ezdfx.new()
....dwg_new.add_layer(layer)
....dwg_new.saveas(layer.dxf.name + '.dxf')

How to do this?

Color value is wrong?

I got color of dxf by "e.dxf.color".But i found it just a single value and even being 256?
What's mean?
I don't understand,is it the color of layer?

about hatch

Can I hatch an object with pattern? When can an object be hatch with pattern? Thank you!

error in ezdxf setup command: package_data must be a dictionary

Hello,
I'm trying to install the develop branch of your wonderful project, but I'm facing a recurrent error.

sudo pip install git+https://github.com/mozman/ezdxf.git@develop

Collecting git+https://github.com/mozman/ezdxf.git@develop
Cloning https://github.com/mozman/ezdxf.git (to revision develop) to /tmp/pip-req-build-3D4XZp
Complete output from command python setup.py egg_info:
error in ezdxf setup command: package_data must be a dictionary mapping package names to lists of wildcard patterns
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-req-build-3D4XZp/

I also tried to install it from sources using
sudo git clone -b develop https://github.com/mozman/ezdxf/
cd ezdxf
sudo python setup.py install

error in ezdxf setup command: package_data must be a dictionary mapping package names to lists of wildcard patterns

Did I miss something obvious ?
Thank you <3 !

Edit : OS Raspbian, Linux 4.14.62-v7+ / Hardware : RPI-3B

INSERT can attach undefined attribute

From my understanding, a block is required to define attdef entities before an INSERT entity can attach attrib to itself, but during a random test I found out that ezdxf allows the user to attach undefined attributes to INSERT. I don't know whether it is a valid operation or a bug. Testing code is below:

### Append attribute to block
block = dxf.blocks.get('ǰƬ(L)-0')
msp = dxf.modelspace()
### Add block definition
block.add_attdef('Style', (0.5, -0.5), {'height': 0.25, 'color': 3})
block.add_attdef('Size', (0.5, -10.0), {'height': 0.25, 'color': 4})
block.add_attdef('Fabric', (0.5, -20.0), {'height': 0.25, 'color': 4})

values = {
    'Style': "Gangster",
    'Size': "160/23",
    'Fabric': "Demin"
}
insert = msp.add_blockref('ǰƬ(L)-0', (100, 100), dxfattribs={'xscale': 1.0, 'yscale': 1.0, 'rotation': 15})
insert.add_attrib('Style', 'Gangster')
insert.add_attrib('Size', '160/23')
insert.add_attrib('Fabric', 'Demin')
insert.add_attrib('Sdf', 'sdfs')     ### Undefined attribute
for attrib in insert.attribs():
    #attrib.is_invisible = True
    print(attrib.dxf.tag)

Result:

Style
Size
Fabric
Sdf

Errror when creating layer

Hi,

Thanks for this great package!

I think I found an error, or I havent found the source of the error, but found a way to provoking the error.

Step by step guide to provoking this error (see the Attached file for code, dxf and screenshot):

  1. I use your hatch example on page 18 in [1], "solid_hatch_polyline_path.dxf". I add the line for creating a layer

dwg.layers.new('This_Give_Me_And_Error_layer')
2) Open the dxf i Autocad Map 2013/2016 or Autocad 2016
3) Save as dwg
4) Create new dwg
5) attach solid_hatch_polyline_path_notworking.dwg file
6) Try to Save, get the recover error.

ezdxf_error.zip

[1] https://media.readthedocs.org/pdf/ezdxf/latest/ezdxf.pdf

questions about speed

Hi,
First of all, really great lib, it's a very big help for me :)
Big files can take a lot of time to open, even on a 4.2Ghz I7. Would it be possible to use Numpy or another solution to somehow speedup the read process?
I use DXFGrabber many times a week, it saved my day many times.
Regards

[Feature] Add ATTDEF helper function for blocks

The statement "All ATTDEFS on BLOCKS will appear as ATTRIBS on INSERTS in a DXF file." is incorrect.

Unfortunately, "constant" defined ATTDEFS are not written as ATTRIBS on the INSERT. There is an op-code (70) for ATTDEF/ATTRIB flags where this can be checked:

  • 1 = Attribute is invisible (does not appear).
  • 2 = This is a constant attribute.
  • 4 = Verification is required on input of this attribute.
  • 8 = Attribute is preset (no prompt during insertion).

This can lead to the situation where one might want to select attribute text from the BLOCK rather than the INSERT. What are your thoughts on adding the following features?

  • Add block.get_attrib_text(tag, default=None) function similar to insert.get_attrib_text().
  • Add op-code 70 as a new tag to ATTDEF and ATTRIB entities.

If you like these solutions, then I will create a pull request with the changes. Thanks!

--Katz

Create new xdf and import existing draw

Hi,
for a small project I have to draw simple entities (lines, arc..) to create a "frame" and the add more "complex" dxf draws taken from a given file inside this frame and save the new draw.
The draw taken from the given file have to be moved and scaled. Could someone suggest the best method to reach this result?

Thanks for this great project, actually I was looking for something similar in php, but I'm going to move to Phyton and use this.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.