0
# Add-ons
1
2
Extended functionality including import/export utilities, geometry generators, table creation, dimension tools, and specialized format support. The addons package provides high-level tools and specialized functionality built on top of the core ezdxf library.
3
4
## Capabilities
5
6
### Import and Export Tools
7
8
Utilities for transferring entities and definitions between DXF documents and specialized export formats.
9
10
```python { .api }
11
class Importer:
12
"""Import entities and definitions between DXF documents"""
13
14
def __init__(self, source_doc, target_doc): ...
15
16
def import_entities(self, entities):
17
"""
18
Import entities from source to target document.
19
20
Parameters:
21
- entities: sequence of entities to import
22
23
Returns:
24
List: Imported entities in target document
25
"""
26
27
def import_blocks(self, block_names):
28
"""Import block definitions"""
29
30
def import_layers(self, layer_names):
31
"""Import layer definitions"""
32
33
def import_linetypes(self, linetype_names):
34
"""Import linetype definitions"""
35
36
def import_text_styles(self, style_names):
37
"""Import text style definitions"""
38
39
def import_dim_styles(self, dimstyle_names):
40
"""Import dimension style definitions"""
41
42
class MTextExplode:
43
"""Explode MTEXT entities to simple text and geometric entities"""
44
45
def __init__(self): ...
46
47
def explode(self, mtext, target_layout):
48
"""
49
Explode MTEXT to basic entities.
50
51
Parameters:
52
- mtext: MTEXT entity to explode
53
- target_layout: layout to receive exploded entities
54
55
Returns:
56
List: Basic entities representing the MTEXT
57
"""
58
```
59
60
Usage examples:
61
```python
62
from ezdxf.addons import Importer, MTextExplode
63
import ezdxf
64
65
# Import entities between documents
66
source_doc = ezdxf.readfile('source.dxf')
67
target_doc = ezdxf.new()
68
69
importer = Importer(source_doc, target_doc)
70
71
# Import specific entities
72
source_entities = source_doc.modelspace().query('CIRCLE')
73
imported_circles = importer.import_entities(source_entities)
74
75
# Import supporting definitions
76
importer.import_layers(['GEOMETRY', 'DIMENSIONS'])
77
importer.import_linetypes(['DASHED', 'CENTER'])
78
79
# Explode MTEXT for R12 compatibility
80
mtext_exploder = MTextExplode()
81
for mtext in target_doc.modelspace().query('MTEXT'):
82
exploded = mtext_exploder.explode(mtext, target_doc.modelspace())
83
target_doc.modelspace().delete_entity(mtext) # Remove original
84
```
85
86
### High-Performance R12 Writer
87
88
Fast DXF R12 file writer optimized for large datasets and simple geometry.
89
90
```python { .api }
91
class R12Writer:
92
"""High-performance DXF R12 file writer"""
93
94
def __init__(self, filename: str, *, fixed_tables: bool = False): ...
95
96
def add_line(self, start, end, *, layer: str = '0', color: int = None): ...
97
def add_circle(self, center, radius: float, *, layer: str = '0', color: int = None): ...
98
def add_arc(self, center, radius: float, start_angle: float, end_angle: float,
99
*, layer: str = '0', color: int = None): ...
100
def add_point(self, location, *, layer: str = '0', color: int = None): ...
101
def add_text(self, text: str, insert, *, height: float = 1.0, layer: str = '0',
102
color: int = None, rotation: float = 0, style: str = 'STANDARD'): ...
103
def add_polyline(self, points, *, layer: str = '0', color: int = None,
104
closed: bool = False): ...
105
def add_3dface(self, face, *, layer: str = '0', color: int = None): ...
106
107
def close(self): ...
108
109
def __enter__(self): ...
110
def __exit__(self, exc_type, exc_val, exc_tb): ...
111
```
112
113
Usage examples:
114
```python
115
from ezdxf.addons.r12writer import R12Writer
116
import random
117
118
# High-performance writing of large datasets
119
with R12Writer('large_dataset.dxf') as r12:
120
# Generate thousands of entities quickly
121
for i in range(10000):
122
x, y = random.uniform(0, 1000), random.uniform(0, 1000)
123
radius = random.uniform(1, 10)
124
125
r12.add_circle((x, y), radius, layer='CIRCLES', color=1)
126
127
if i % 100 == 0: # Add some text markers
128
r12.add_text(f'#{i}', (x, y + radius + 2), height=2, layer='LABELS')
129
```
130
131
### Geometry Generators
132
133
Specialized generators for complex geometric shapes and fractal patterns.
134
135
```python { .api }
136
class MengerSponge:
137
"""Generate Menger sponge fractal meshes"""
138
139
def __init__(self, level: int = 3, size: float = 1.0): ...
140
141
@property
142
def level(self) -> int:
143
"""Fractal recursion level"""
144
145
@property
146
def size(self) -> float:
147
"""Overall size of the sponge"""
148
149
def mesh(self) -> MeshBuilder:
150
"""Generate mesh representation"""
151
152
def render(self, layout, *, dxfattribs: dict = None):
153
"""Render sponge to layout as mesh entities"""
154
155
class SierpinskyPyramid:
156
"""Generate Sierpinsky pyramid fractal meshes"""
157
158
def __init__(self, level: int = 4, size: float = 1.0): ...
159
160
def mesh(self) -> MeshBuilder:
161
"""Generate mesh representation"""
162
163
def render(self, layout, *, dxfattribs: dict = None):
164
"""Render pyramid to layout"""
165
```
166
167
Usage examples:
168
```python
169
from ezdxf.addons import MengerSponge, SierpinskyPyramid
170
171
# Generate Menger sponge
172
sponge = MengerSponge(level=3, size=50)
173
sponge.render(msp, dxfattribs={'color': 1, 'layer': 'FRACTALS'})
174
175
# Generate Sierpinsky pyramid
176
pyramid = SierpinskyPyramid(level=4, size=30)
177
pyramid_mesh = pyramid.mesh()
178
pyramid_mesh.translate(100, 0, 0) # Position away from sponge
179
pyramid_mesh.render_mesh(msp, dxfattribs={'color': 2, 'layer': 'FRACTALS'})
180
```
181
182
### Table Creation Tools
183
184
Advanced table creation and formatting utilities with cell-based editing.
185
186
```python { .api }
187
class TablePainter:
188
"""Create and format table entities with cells and borders"""
189
190
def __init__(self, insert = (0, 0), nrows: int = 1, ncols: int = 1,
191
cell_width: float = 10, cell_height: float = 5): ...
192
193
@property
194
def nrows(self) -> int:
195
"""Number of rows"""
196
197
@property
198
def ncols(self) -> int:
199
"""Number of columns"""
200
201
def cell(self, row: int, col: int) -> 'CustomCell':
202
"""Get cell at specified position"""
203
204
def frame(self, *, style: str = 'default', color: int = None) -> 'TablePainter':
205
"""Set table frame style"""
206
207
def grid(self, *, style: str = 'default', color: int = None) -> 'TablePainter':
208
"""Set grid line style"""
209
210
def render(self, layout, *, dxfattribs: dict = None):
211
"""Render table to layout"""
212
213
class CustomCell:
214
"""Individual table cell with content and formatting"""
215
216
def __init__(self): ...
217
218
def add_text(self, text: str, *, height: float = 2.5, color: int = None,
219
halign: str = 'CENTER', valign: str = 'MIDDLE') -> 'CustomCell': ...
220
def add_line(self, start, end, *, color: int = None) -> 'CustomCell': ...
221
def add_circle(self, center, radius: float, *, color: int = None) -> 'CustomCell': ...
222
223
def background_color(self, color: int) -> 'CustomCell': ...
224
def border(self, *, style: str = 'default', color: int = None) -> 'CustomCell': ...
225
```
226
227
Usage examples:
228
```python
229
from ezdxf.addons import TablePainter
230
231
# Create table with data
232
table = TablePainter(insert=(0, 0), nrows=4, ncols=3,
233
cell_width=20, cell_height=8)
234
235
# Header row
236
table.cell(0, 0).add_text('Item', height=3, color=1).background_color(250)
237
table.cell(0, 1).add_text('Quantity', height=3, color=1).background_color(250)
238
table.cell(0, 2).add_text('Price', height=3, color=1).background_color(250)
239
240
# Data rows
241
items = [
242
('Widget A', '10', '$5.00'),
243
('Widget B', '25', '$3.50'),
244
('Widget C', '5', '$12.00')
245
]
246
247
for i, (item, qty, price) in enumerate(items, 1):
248
table.cell(i, 0).add_text(item, halign='LEFT')
249
table.cell(i, 1).add_text(qty, halign='CENTER')
250
table.cell(i, 2).add_text(price, halign='RIGHT')
251
252
# Style table
253
table.frame(style='thick', color=1)
254
table.grid(style='thin', color=8)
255
256
# Render to layout
257
table.render(msp, dxfattribs={'layer': 'TABLES'})
258
```
259
260
### Dimension Creation Tools
261
262
High-level dimension creation utilities with automatic formatting and positioning.
263
264
```python { .api }
265
class LinearDimension:
266
"""Create linear dimensions with automatic positioning"""
267
268
@staticmethod
269
def quick_dimension(p1, p2, distance: float, *, dimstyle: str = 'EZDXF',
270
override: dict = None, dxfattribs: dict = None):
271
"""Create linear dimension between two points"""
272
273
class AngularDimension:
274
"""Create angular dimensions"""
275
276
@staticmethod
277
def quick_dimension(center, p1, p2, *, dimstyle: str = 'EZDXF',
278
override: dict = None, dxfattribs: dict = None):
279
"""Create angular dimension from center and two points"""
280
281
class RadialDimension:
282
"""Create radial dimensions for circles and arcs"""
283
284
@staticmethod
285
def quick_dimension(center, radius: float, angle: float = 0,
286
*, dimstyle: str = 'EZDXF', override: dict = None,
287
dxfattribs: dict = None):
288
"""Create radial dimension"""
289
290
class ArcDimension:
291
"""Create arc length dimensions"""
292
293
@staticmethod
294
def quick_dimension(center, radius: float, start_angle: float, end_angle: float,
295
*, dimstyle: str = 'EZDXF', override: dict = None,
296
dxfattribs: dict = None):
297
"""Create arc length dimension"""
298
299
# Dimension style management
300
def dimstyles(doc):
301
"""Access dimension style management utilities"""
302
```
303
304
### Text Processing Tools
305
306
Advanced text handling and compatibility utilities for MTEXT processing.
307
308
```python { .api }
309
class MTextSurrogate:
310
"""MTEXT compatibility layer for older DXF versions"""
311
312
def __init__(self, mtext): ...
313
314
def explode_to_text(self, layout, *, line_spacing: float = 1.67,
315
dxfattribs: dict = None):
316
"""Explode MTEXT to multiple TEXT entities"""
317
318
def plain_text(self) -> str:
319
"""Extract plain text content without formatting"""
320
321
def word_wrap(self, box_width: float) -> List[str]:
322
"""Word wrap text to specified width"""
323
```
324
325
### Advanced Add-on Subpackages
326
327
Specialized subpackages for complex functionality and format support.
328
329
```python { .api }
330
# Drawing and rendering backends
331
from ezdxf.addons.drawing import Frontend, Backend
332
from ezdxf.addons.drawing.matplotlib import MatplotlibBackend
333
from ezdxf.addons.drawing.pyqt import PyQtBackend
334
335
# DXF structure browser
336
from ezdxf.addons.browser import Browser
337
338
# HPGL2 plotter format support
339
from ezdxf.addons.hpgl2 import api as hpgl2
340
341
# Limited DWG file support
342
from ezdxf.addons.dwg import readfile as read_dwg
343
```
344
345
Usage examples:
346
```python
347
# Drawing backend example
348
from ezdxf.addons.drawing import Frontend
349
from ezdxf.addons.drawing.matplotlib import MatplotlibBackend
350
import matplotlib.pyplot as plt
351
352
# Render DXF to matplotlib
353
doc = ezdxf.readfile('drawing.dxf')
354
msp = doc.modelspace()
355
356
fig = plt.figure()
357
ax = fig.add_axes([0, 0, 1, 1])
358
ctx = MatplotlibBackend(ax)
359
Frontend(ctx, doc).draw_layout(msp, finalize=True)
360
plt.show()
361
362
# DXF structure browser
363
from ezdxf.addons.browser import Browser
364
365
# Inspect DXF file structure
366
browser = Browser(doc)
367
browser.print_structure() # Print document structure to console
368
369
# HPGL2 export example
370
from ezdxf.addons.hpgl2 import api as hpgl2
371
372
# Export DXF to HPGL2 format
373
hpgl2.export_dxf('drawing.dxf', 'output.plt',
374
paper_size='A3',
375
pen_table={'1': 'red', '2': 'blue'})
376
```
377
378
### Utility Classes and Functions
379
380
Additional utility classes and functions for specialized operations.
381
382
```python { .api }
383
class GeneticAlgorithm:
384
"""Genetic algorithm implementation for optimization problems"""
385
386
def __init__(self, population_size: int = 100, mutation_rate: float = 0.01): ...
387
388
def evolve(self, fitness_function, generations: int = 100): ...
389
390
class BinPacking:
391
"""2D bin packing algorithms for layout optimization"""
392
393
@staticmethod
394
def pack_rectangles(rectangles, bin_width: float, bin_height: float): ...
395
396
def openscad_integration():
397
"""OpenSCAD file format integration utilities"""
398
399
def pycsg_integration():
400
"""PyCSG (Constructive Solid Geometry) integration"""
401
```
402
403
## Complete Add-ons Usage Example
404
405
```python
406
import ezdxf
407
from ezdxf.addons import Importer, TablePainter, MengerSponge
408
from ezdxf.addons import LinearDimension, MTextExplode
409
from ezdxf.addons.r12writer import R12Writer
410
411
# Create main document
412
doc = ezdxf.new('R2018', setup=True)
413
msp = doc.modelspace()
414
415
# Import from another document
416
if True: # Conditional import
417
try:
418
source_doc = ezdxf.readfile('source_drawing.dxf')
419
importer = Importer(source_doc, doc)
420
421
# Import specific layers and styles
422
importer.import_layers(['IMPORTED_GEOMETRY'])
423
importer.import_text_styles(['TITLE_STYLE'])
424
425
# Import selected entities
426
imported_entities = importer.import_entities(
427
source_doc.modelspace().query('CIRCLE[radius>5.0]')
428
)
429
print(f"Imported {len(imported_entities)} large circles")
430
431
except ezdxf.DXFError:
432
print("Source document not found, skipping import")
433
434
# Create specification table
435
spec_table = TablePainter(insert=(50, 50), nrows=6, ncols=3,
436
cell_width=25, cell_height=10)
437
438
# Fill table with specifications
439
headers = ['Component', 'Specification', 'Notes']
440
for i, header in enumerate(headers):
441
spec_table.cell(0, i).add_text(header, height=4, color=1).background_color(251)
442
443
spec_data = [
444
('Material', 'Steel AISI 1018', 'Cold rolled'),
445
('Thickness', '3.0 mm', '±0.1 tolerance'),
446
('Surface', 'Zinc plated', 'Clear passivate'),
447
('Weight', '2.5 kg', 'Approximate'),
448
('Qty Required', '100 pcs', 'Initial order')
449
]
450
451
for i, (comp, spec, note) in enumerate(spec_data, 1):
452
spec_table.cell(i, 0).add_text(comp, halign='LEFT')
453
spec_table.cell(i, 1).add_text(spec, halign='CENTER')
454
spec_table.cell(i, 2).add_text(note, halign='LEFT', color=8)
455
456
spec_table.frame(style='thick', color=1)
457
spec_table.grid(style='default', color=8)
458
spec_table.render(msp, dxfattribs={'layer': 'SPECIFICATIONS'})
459
460
# Add decorative fractal element
461
fractal = MengerSponge(level=2, size=20)
462
fractal_mesh = fractal.mesh()
463
fractal_mesh.translate(150, 25, 0)
464
fractal_mesh.render_mesh(msp, dxfattribs={'color': 3, 'layer': 'DECORATION'})
465
466
# Create simplified R12 export for compatibility
467
r12_filename = 'simplified_export.dxf'
468
with R12Writer(r12_filename) as r12:
469
# Export basic geometry only
470
for entity in msp.query('LINE CIRCLE ARC'):
471
if entity.dxftype() == 'LINE':
472
r12.add_line(entity.dxf.start, entity.dxf.end,
473
layer=entity.dxf.layer, color=entity.dxf.color)
474
elif entity.dxftype() == 'CIRCLE':
475
r12.add_circle(entity.dxf.center, entity.dxf.radius,
476
layer=entity.dxf.layer, color=entity.dxf.color)
477
elif entity.dxftype() == 'ARC':
478
r12.add_arc(entity.dxf.center, entity.dxf.radius,
479
entity.dxf.start_angle, entity.dxf.end_angle,
480
layer=entity.dxf.layer, color=entity.dxf.color)
481
482
# Process any MTEXT for R12 compatibility
483
mtext_exploder = MTextExplode()
484
for mtext in msp.query('MTEXT'):
485
exploded_entities = mtext_exploder.explode(mtext, msp)
486
msp.delete_entity(mtext)
487
print(f"Exploded MTEXT to {len(exploded_entities)} entities")
488
489
# Save main document
490
doc.saveas('addon_features_demo.dxf')
491
print(f"Created main document and R12 export: {r12_filename}")
492
```