3
dxf_input.py - input a DXF file >= (AutoCAD Release 13 == AC1012)
5
Copyright (C) 2008, 2009 Alvin Penner, penner@vaxxine.com
6
Copyright (C) 2009 Christian Mayer, inkscape@christianmayer.de
7
- thanks to Aaron Spike for inkex.py and simplestyle.py
8
- without which this would not have been possible
10
This program is free software; you can redistribute it and/or modify
11
it under the terms of the GNU General Public License as published by
12
the Free Software Foundation; either version 2 of the License, or
13
(at your option) any later version.
15
This program is distributed in the hope that it will be useful,
16
but WITHOUT ANY WARRANTY; without even the implied warranty of
17
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18
GNU General Public License for more details.
20
You should have received a copy of the GNU General Public License
21
along with this program; if not, write to the Free Software
22
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25
import inkex, simplestyle, math
26
from StringIO import StringIO
29
# mandatory group codes : (1 or 3, 10, 20) (text, x, y)
30
if (vals[groups['1']] or vals[groups['3']]) and vals[groups['10']] and vals[groups['20']]:
31
x = vals[groups['10']][0]
32
y = vals[groups['20']][0]
33
# optional group codes : (21, 40, 50) (direction, text height mm, text angle)
34
size = 12 # default fontsize in px
35
if vals[groups['40']]:
36
size = scale*vals[groups['40']][0]
37
attribs = {'x': '%f' % x, 'y': '%f' % y, 'style': 'font-size: %.1fpx; fill: %s' % (size, color)}
38
angle = 0 # default angle in degrees
39
if vals[groups['50']]:
40
angle = vals[groups['50']][0]
41
attribs.update({'transform': 'rotate (%f %f %f)' % (-angle, x, y)})
42
elif vals[groups['21']]:
43
if vals[groups['21']][0] == 1.0:
44
attribs.update({'transform': 'rotate (%f %f %f)' % (-90, x, y)})
45
elif vals[groups['21']][0] == -1.0:
46
attribs.update({'transform': 'rotate (%f %f %f)' % (90, x, y)})
47
attribs.update({inkex.addNS('linespacing','sodipodi'): '125%'})
48
node = inkex.etree.SubElement(layer, 'text', attribs)
51
for i in range (0, len(vals[groups['3']])):
52
text += vals[groups['3']][i]
54
text += vals[groups['1']][0]
55
found = text.find('\P') # new line
57
tspan = inkex.etree.SubElement(node , 'tspan', {inkex.addNS('role','sodipodi'): 'line'})
58
tspan.text = text[:found]
59
text = text[(found+2):]
60
found = text.find('\P')
61
tspan = inkex.etree.SubElement(node , 'tspan', {inkex.addNS('role','sodipodi'): 'line'})
65
# mandatory group codes : (10, 20) (x, y)
66
if vals[groups['10']] and vals[groups['20']]:
67
generate_ellipse(vals[groups['10']][0], vals[groups['20']][0], w/2, 0.0, 1.0, 0.0, 0.0)
70
# mandatory group codes : (10, 11, 20, 21) (x1, x2, y1, y2)
71
if vals[groups['10']] and vals[groups['11']] and vals[groups['20']] and vals[groups['21']]:
72
path = 'M %f,%f %f,%f' % (vals[groups['10']][0], vals[groups['20']][0], scale*(vals[groups['11']][0] - xmin), - scale*(vals[groups['21']][0] - ymax))
73
attribs = {'d': path, 'style': style}
74
inkex.etree.SubElement(layer, 'path', attribs)
77
# mandatory group codes : (10, 20, 70) (x, y, flags)
78
if vals[groups['10']] and vals[groups['20']] and vals[groups['70']]:
79
if not (vals[groups['70']][0] & 3) and len(vals[groups['10']]) == 4 and len(vals[groups['20']]) == 4:
80
path = 'M %f,%f C %f,%f %f,%f %f,%f' % (vals[groups['10']][0], vals[groups['20']][0], vals[groups['10']][1], vals[groups['20']][1], vals[groups['10']][2], vals[groups['20']][2], vals[groups['10']][3], vals[groups['20']][3])
81
attribs = {'d': path, 'style': style}
82
inkex.etree.SubElement(layer, 'path', attribs)
83
if not (vals[groups['70']][0] & 3) and len(vals[groups['10']]) == 3 and len(vals[groups['20']]) == 3:
84
path = 'M %f,%f Q %f,%f %f,%f' % (vals[groups['10']][0], vals[groups['20']][0], vals[groups['10']][1], vals[groups['20']][1], vals[groups['10']][2], vals[groups['20']][2])
85
attribs = {'d': path, 'style': style}
86
inkex.etree.SubElement(layer, 'path', attribs)
89
# mandatory group codes : (10, 20, 40) (x, y, radius)
90
if vals[groups['10']] and vals[groups['20']] and vals[groups['40']]:
91
generate_ellipse(vals[groups['10']][0], vals[groups['20']][0], scale*vals[groups['40']][0], 0.0, 1.0, 0.0, 0.0)
94
# mandatory group codes : (10, 20, 40, 50, 51) (x, y, radius, angle1, angle2)
95
if vals[groups['10']] and vals[groups['20']] and vals[groups['40']] and vals[groups['50']] and vals[groups['51']]:
96
generate_ellipse(vals[groups['10']][0], vals[groups['20']][0], scale*vals[groups['40']][0], 0.0, 1.0, vals[groups['50']][0]*math.pi/180.0, vals[groups['51']][0]*math.pi/180.0)
99
# mandatory group codes : (10, 11, 20, 21, 40, 41, 42) (xc, xm, yc, ym, width ratio, angle1, angle2)
100
if vals[groups['10']] and vals[groups['11']] and vals[groups['20']] and vals[groups['21']] and vals[groups['40']] and vals[groups['41']] and vals[groups['42']]:
101
generate_ellipse(vals[groups['10']][0], vals[groups['20']][0], scale*vals[groups['11']][0], scale*vals[groups['21']][0], vals[groups['40']][0], vals[groups['41']][0], vals[groups['42']][0])
104
# mandatory group codes : (10, 20) (x, y)
105
if vals[groups['10']] and vals[groups['20']]:
106
if len(vals[groups['10']]) > 1 and len(vals[groups['20']]) == len(vals[groups['10']]):
107
path = 'M %f,%f' % (vals[groups['10']][0], vals[groups['20']][0])
108
for i in range (1, len(vals[groups['10']])):
109
path += ' %f,%f' % (vals[groups['10']][i], vals[groups['20']][i])
110
attribs = {'d': path, 'style': style}
111
inkex.etree.SubElement(layer, 'path', attribs)
113
def export_LWPOLYLINE():
114
# mandatory group codes : (10, 20, 70) (x, y, flags)
115
if vals[groups['10']] and vals[groups['20']] and vals[groups['70']]:
116
if len(vals[groups['10']]) > 1 and len(vals[groups['20']]) == len(vals[groups['10']]):
117
# optional group codes : (42) (bulge)
120
while seqs[iseqs] != '20':
122
path = 'M %f,%f' % (vals[groups['10']][0], vals[groups['20']][0])
123
xold = vals[groups['10']][0]
124
yold = vals[groups['20']][0]
125
for i in range (1, len(vals[groups['10']])):
128
while seqs[iseqs] != '20':
129
if seqs[iseqs] == '42':
130
bulge = vals[groups['42']][ibulge]
134
sweep = 0 # sweep CCW
138
large = 0 # large-arc-flag
141
r = math.sqrt((vals[groups['10']][i] - xold)**2 + (vals[groups['20']][i] - yold)**2)
142
r = 0.25*r*(bulge + 1.0/bulge)
143
path += ' A %f,%f 0.0 %d %d %f,%f' % (r, r, large, sweep, vals[groups['10']][i], vals[groups['20']][i])
145
path += ' L %f,%f' % (vals[groups['10']][i], vals[groups['20']][i])
146
xold = vals[groups['10']][i]
147
yold = vals[groups['20']][i]
148
if vals[groups['70']][0] == 1: # closed path
150
attribs = {'d': path, 'style': style}
151
inkex.etree.SubElement(layer, 'path', attribs)
154
# mandatory group codes : (10, 20, 70, 72, 92, 93) (x, y, fill, Edge Type, Path Type, Number of edges)
155
if vals[groups['10']] and vals[groups['20']] and vals[groups['70']] and vals[groups['72']] and vals[groups['92']] and vals[groups['93']]:
156
if vals[groups['70']][0] and len(vals[groups['10']]) > 1 and len(vals[groups['20']]) == len(vals[groups['10']]):
157
# optional group codes : (11, 21, 40, 50, 51, 73) (x, y, r, angle1, angle2, CCW)
158
i10 = 1 # count start points
159
i11 = 0 # count line end points
160
i40 = 0 # count circles
161
i72 = 0 # count edge type flags
163
for i in range (0, len(vals[groups['93']])):
164
xc = vals[groups['10']][i10]
165
yc = vals[groups['20']][i10]
166
if vals[groups['72']][i72] == 2: # arc
167
rm = scale*vals[groups['40']][i40]
168
a1 = vals[groups['50']][i40]
169
path += 'M %f,%f ' % (xc + rm*math.cos(a1*math.pi/180.0), yc + rm*math.sin(a1*math.pi/180.0))
172
path += 'M %f,%f ' % (xc, yc)
173
for j in range(0, vals[groups['93']][i]):
174
if vals[groups['92']][i] & 2: # polyline
176
path += 'L %f,%f ' % (vals[groups['10']][i10], vals[groups['20']][i10])
177
if j == vals[groups['93']][i] - 1:
179
elif vals[groups['72']][i72] == 2: # arc
180
xc = vals[groups['10']][i10]
181
yc = vals[groups['20']][i10]
182
rm = scale*vals[groups['40']][i40]
183
a2 = vals[groups['51']][i40]
184
diff = (a2 - a1 + 360) % (360)
185
sweep = 1 - vals[groups['73']][i40] # sweep CCW
186
large = 0 # large-arc-flag
188
path += 'A %f,%f 0.0 %d %d %f,%f ' % (rm, rm, large, sweep, xc + rm*math.cos(a2*math.pi/180.0), yc + rm*math.sin(a2*math.pi/180.0))
190
path += 'A %f,%f 0.0 %d %d %f,%f ' % (rm, rm, large, sweep, xc + rm*math.cos((a1+180.0)*math.pi/180.0), yc + rm*math.sin((a1+180.0)*math.pi/180.0))
191
path += 'A %f,%f 0.0 %d %d %f,%f ' % (rm, rm, large, sweep, xc + rm*math.cos(a1*math.pi/180.0), yc + rm*math.sin(a1*math.pi/180.0))
194
elif vals[groups['72']][i72] == 1: # line
195
path += 'L %f,%f ' % (scale*(vals[groups['11']][i11] - xmin), -scale*(vals[groups['21']][i11] - ymax))
200
style = simplestyle.formatStyle({'fill': '%s' % color})
201
attribs = {'d': path, 'style': style}
202
inkex.etree.SubElement(layer, 'path', attribs)
204
def export_DIMENSION():
205
# mandatory group codes : (10, 11, 13, 14, 20, 21, 23, 24) (x1..4, y1..4)
206
if vals[groups['10']] and vals[groups['11']] and vals[groups['13']] and vals[groups['14']] and vals[groups['20']] and vals[groups['21']] and vals[groups['23']] and vals[groups['24']]:
207
dx = abs(vals[groups['10']][0] - vals[groups['13']][0])
208
dy = abs(vals[groups['20']][0] - vals[groups['23']][0])
209
if (vals[groups['10']][0] == vals[groups['14']][0]) and dx > 0.00001:
212
path = 'M %f,%f %f,%f' % (vals[groups['10']][0], vals[groups['20']][0], vals[groups['13']][0], vals[groups['20']][0])
213
elif (vals[groups['20']][0] == vals[groups['24']][0]) and dy > 0.00001:
216
path = 'M %f,%f %f,%f' % (vals[groups['10']][0], vals[groups['20']][0], vals[groups['10']][0], vals[groups['23']][0])
219
attribs = {'d': path, 'style': style + '; marker-start: url(#DistanceX); marker-end: url(#DistanceX)'}
220
inkex.etree.SubElement(layer, 'path', attribs)
221
x = scale*(vals[groups['11']][0] - xmin)
222
y = - scale*(vals[groups['21']][0] - ymax)
223
size = 12 # default fontsize in px
224
if vals[groups['3']]:
225
if DIMTXT.has_key(vals[groups['3']][0]):
226
size = scale*DIMTXT[vals[groups['3']][0]]
229
attribs = {'x': '%f' % x, 'y': '%f' % y, 'style': 'font-size: %.1fpx; fill: %s' % (size, color)}
231
attribs.update({'transform': 'rotate (%f %f %f)' % (-90, x, y)})
232
node = inkex.etree.SubElement(layer, 'text', attribs)
233
tspan = inkex.etree.SubElement(node , 'tspan', {inkex.addNS('role','sodipodi'): 'line'})
234
tspan.text = str(float('%.2f' % d))
237
# mandatory group codes : (2, 10, 20) (block name, x, y)
238
if vals[groups['2']] and vals[groups['10']] and vals[groups['20']]:
239
x = vals[groups['10']][0]
240
y = vals[groups['20']][0] - scale*ymax
241
attribs = {'x': '%f' % x, 'y': '%f' % y, inkex.addNS('href','xlink'): '#' + vals[groups['2']][0]}
242
inkex.etree.SubElement(layer, 'use', attribs)
245
# mandatory group codes : (2) (block name)
246
if vals[groups['2']]:
248
block = inkex.etree.SubElement(defs, 'symbol', {'id': vals[groups['2']][0]})
252
block = defs # initiallize with dummy
255
# mandatory group codes : (1, 2) (default, tag)
256
if vals[groups['1']] and vals[groups['2']]:
257
vals[groups['1']][0] = vals[groups['2']][0]
260
def generate_ellipse(xc, yc, xm, ym, w, a1, a2):
261
rm = math.sqrt(xm*xm + ym*ym)
262
a = math.atan2(ym, xm)
263
diff = (a2 - a1 + 2*math.pi) % (2*math.pi)
264
if abs(diff) > 0.0000001 and abs(diff - 2*math.pi) > 0.0000001: # open arc
265
large = 0 # large-arc-flag
269
yt = w*rm*math.sin(a1)
270
x1 = xt*math.cos(a) - yt*math.sin(a)
271
y1 = xt*math.sin(a) + yt*math.cos(a)
273
yt = w*rm*math.sin(a2)
274
x2 = xt*math.cos(a) - yt*math.sin(a)
275
y2 = xt*math.sin(a) + yt*math.cos(a)
276
path = 'M %f,%f A %f,%f %f %d 0 %f,%f' % (xc+x1, yc-y1, rm, w*rm, -180.0*a/math.pi, large, xc+x2, yc-y2)
278
path = 'M %f,%f A %f,%f %f 1 0 %f,%f %f,%f %f 1 0 %f,%f z' % (xc+xm, yc-ym, rm, w*rm, -180.0*a/math.pi, xc-xm, yc+ym, rm, w*rm, -180.0*a/math.pi, xc+xm, yc-ym)
279
attribs = {'d': path, 'style': style}
280
inkex.etree.SubElement(layer, 'path', attribs)
283
return (stream.readline().strip(), stream.readline().strip())
285
def get_group(group):
288
return float(line[1])
292
# define DXF Entities and specify which Group Codes to monitor
294
entities = {'MTEXT': export_MTEXT, 'TEXT': export_MTEXT, 'POINT': export_POINT, 'LINE': export_LINE, 'SPLINE': export_SPLINE, 'CIRCLE': export_CIRCLE, 'ARC': export_ARC, 'ELLIPSE': export_ELLIPSE, 'LEADER': export_LEADER, 'LWPOLYLINE': export_LWPOLYLINE, 'HATCH': export_HATCH, 'DIMENSION': export_DIMENSION, 'INSERT': export_INSERT, 'BLOCK': export_BLOCK, 'ENDBLK': export_ENDBLK, 'ATTDEF': export_ATTDEF, 'DICTIONARY': False}
295
groups = {'1': 0, '2': 1, '3': 2, '6': 3, '8': 4, '10': 5, '11': 6, '13': 7, '14': 8, '20': 9, '21': 10, '23': 11, '24': 12, '40': 13, '41': 14, '42': 15, '50': 16, '51': 17, '62': 18, '70': 19, '72': 20, '73': 21, '92': 22, '93': 23, '370': 24}
296
colors = { 1: '#FF0000', 2: '#FFFF00', 3: '#00FF00', 4: '#00FFFF', 5: '#0000FF',
297
6: '#FF00FF', 8: '#414141', 9: '#808080', 12: '#BD0000', 30: '#FF7F00',
298
250: '#333333', 251: '#505050', 252: '#696969', 253: '#828282', 254: '#BEBEBE', 255: '#FFFFFF'}
300
parser = inkex.optparse.OptionParser(usage="usage: %prog [options] SVGfile", option_class=inkex.InkOption)
301
parser.add_option("--auto", action="store", type="inkbool", dest="auto", default=True)
302
parser.add_option("--scale", action="store", type="string", dest="scale", default="1.0")
303
parser.add_option("--encoding", action="store", type="string", dest="input_encode", default="latin_1")
304
(options, args) = parser.parse_args(inkex.sys.argv[1:])
305
doc = inkex.etree.parse(StringIO('<svg xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"></svg>'))
306
desc = inkex.etree.SubElement(doc.getroot(), 'desc', {})
307
defs = inkex.etree.SubElement(doc.getroot(), 'defs', {})
308
marker = inkex.etree.SubElement(defs, 'marker', {'id': 'DistanceX', 'orient': 'auto', 'refX': '0.0', 'refY': '0.0', 'style': 'overflow:visible'})
309
inkex.etree.SubElement(marker, 'path', {'d': 'M 3,-3 L -3,3 M 0,-5 L 0,5', 'style': 'stroke:#000000; stroke-width:0.5'})
310
stream = open(args[0], 'r')
312
ymax = 297.0 # default A4 height in mm
314
flag = 0 # (0, 1, 2, 3) = (none, LAYER, LTYPE, DIMTXT)
315
layer_colors = {} # store colors by layer
316
layer_nodes = {} # store nodes by layer
317
linetypes = {} # store linetypes by name
318
DIMTXT = {} # store DIMENSION text sizes
320
while line[0] and line[1] != 'BLOCKS':
323
if line[1] == '$EXTMIN':
324
xmin = get_group('10')
325
if line[1] == '$EXTMAX':
326
xmax = get_group('10')
327
ymax = get_group('20')
328
if flag == 1 and line[0] == '2':
329
layername = unicode(line[1], options.input_encode)
330
attribs = {inkex.addNS('groupmode','inkscape'): 'layer', inkex.addNS('label','inkscape'): '%s' % layername}
331
layer_nodes[layername] = inkex.etree.SubElement(doc.getroot(), 'g', attribs)
332
if flag == 2 and line[0] == '2':
333
linename = unicode(line[1], options.input_encode)
334
linetypes[linename] = []
335
if flag == 3 and line[0] == '2':
336
stylename = unicode(line[1], options.input_encode)
337
if line[0] == '2' and line[1] == 'LAYER':
339
if line[0] == '2' and line[1] == 'LTYPE':
341
if line[0] == '2' and line[1] == 'DIMSTYLE':
343
if flag == 1 and line[0] == '62':
344
layer_colors[layername] = int(line[1])
345
if flag == 2 and line[0] == '49':
346
linetypes[linename].append(float(line[1]))
347
if flag == 3 and line[0] == '140':
348
DIMTXT[stylename] = float(line[1])
349
if line[0] == '0' and line[1] == 'ENDTAB':
355
scale = 210.0/(xmax - xmin) # scale to A4 width
357
scale = float(options.scale) # manual scale factor
358
desc.text = '%s - scale = %f' % (unicode(args[0], options.input_encode), scale)
359
scale *= 90.0/25.4 # convert from mm to pixels
362
attribs = {inkex.addNS('groupmode','inkscape'): 'layer', inkex.addNS('label','inkscape'): '0'}
363
layer_nodes['0'] = inkex.etree.SubElement(doc.getroot(), 'g', attribs)
364
layer_colors['0'] = 7
366
for linename in linetypes.keys(): # scale the dashed lines
368
for length in linetypes[linename]:
369
linetype += '%.4f,' % math.fabs(length*scale)
370
linetypes[linename] = 'stroke-dasharray:' + linetype
373
block = defs # initiallize with dummy
374
while line[0] and line[1] != 'DICTIONARY':
376
if entity and groups.has_key(line[0]):
377
seqs.append(line[0]) # list of group codes
378
if line[0] == '1' or line[0] == '2' or line[0] == '3' or line[0] == '6' or line[0] == '8': # text value
379
val = line[1].replace('\~', ' ')
380
val = inkex.re.sub( '\\\\A.*;', '', val)
381
val = inkex.re.sub( '\\\\H.*;', '', val)
382
val = inkex.re.sub( '\\^I', '', val)
383
val = inkex.re.sub( '{\\\\L', '', val)
384
val = inkex.re.sub( '}', '', val)
385
val = inkex.re.sub( '\\\\S.*;', '', val)
386
val = inkex.re.sub( '\\\\W.*;', '', val)
387
val = unicode(val, options.input_encode)
388
val = val.encode('unicode_escape')
389
val = inkex.re.sub( '\\\\\\\\U\+([0-9A-Fa-f]{4})', '\\u\\1', val)
390
val = val.decode('unicode_escape')
391
elif line[0] == '62' or line[0] == '70' or line[0] == '92' or line[0] == '93':
393
elif line[0] == '10' or line[0] == '13' or line[0] == '14': # scaled float x value
394
val = scale*(float(line[1]) - xmin)
395
elif line[0] == '20' or line[0] == '23' or line[0] == '24': # scaled float y value
396
val = - scale*(float(line[1]) - ymax)
397
else: # unscaled float value
399
vals[groups[line[0]]].append(val)
400
elif entities.has_key(line[1]):
401
if entities.has_key(entity):
402
if block != defs: # in a BLOCK
404
elif vals[groups['8']]: # use Common Layer Name
405
layer = layer_nodes[vals[groups['8']][0]]
406
color = '#000000' # default color
407
if vals[groups['8']]:
408
if layer_colors.has_key(vals[groups['8']][0]):
409
if colors.has_key(layer_colors[vals[groups['8']][0]]):
410
color = colors[layer_colors[vals[groups['8']][0]]]
411
if vals[groups['62']]: # Common Color Number
412
if colors.has_key(vals[groups['62']][0]):
413
color = colors[vals[groups['62']][0]]
414
style = simplestyle.formatStyle({'stroke': '%s' % color, 'fill': 'none'})
415
w = 0.5 # default lineweight for POINT
416
if vals[groups['370']]: # Common Lineweight
417
if vals[groups['370']][0] > 0:
418
w = 90.0/25.4*vals[groups['370']][0]/100.0
421
style = simplestyle.formatStyle({'stroke': '%s' % color, 'fill': 'none', 'stroke-width': '%.1f' % w})
422
if vals[groups['6']]: # Common Linetype
423
if linetypes.has_key(vals[groups['6']][0]):
424
style += ';' + linetypes[vals[groups['6']][0]]
427
vals = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
430
doc.write(inkex.sys.stdout)
432
# vim: expandtab shiftwidth=4 tabstop=8 softtabstop=4 encoding=utf-8 textwidth=99