Python and ezdxf copying blocks

末鹿安然 提交于 2020-04-07 09:05:55

问题


I have a dxf file with one or more blocks. How can I use ezdxf to read this dxf and copy a block to another dxf file?

This code does not work as expected:

dxf = ezdxf.readfile("blocks.dxf")
block_test = dxf.blocks.get('b_test')
dxf_test = ezdxf.readfile("arc.dxf")
msp_test = dxf_test.modelspace()
flag = dxf_test.blocks.new(name='FLAG')
flag.add_lwpolyline([(0, 0), (0, 5), (4, 3), (0, 3)])
flag.add_circle((0, 0), .4, dxfattribs={'color': 2}) 
msp_test.add_blockref(block_test, (10.1, 10.1), dxfattribs={
'xscale': 1,
'yscale': 1,
'rotation': 0
})

msp_test.add_blockref('flag', (0.1, 0.1), dxfattribs={
'xscale': 5.1,
'yscale': 5.1,
'rotation': 115
})

dxf_test.saveas("blockref_tutorial.dxf")
exit()

The above code sample does not work as expected. That is, ´block_test` is not in the saved file...


回答1:


Because of the complex extensibility of the DXF format and the lack of sufficient documentation of the internal structures beyond entity descriptions, it is not that easy to copy entities or move them inside of a DXF file and certainly not between different DXF documents.

To accomplish this kind of task ezdxf has an Importer add-on, which can import some resources, entities and block definitions from a source document into a target document, but don't expect perfect results and please read the docs.

The following code imports the block definition 'b_test' from the source DXF file 'blocks.dxf' into the target DXF file 'arc.dxf', after the import is done, you can add block references to block 'b_test' to the modelspace of the target DXF file.

import ezdxf
from ezdxf.addons import Importer

source_dxf = ezdxf.readfile("blocks.dxf")

if 'b_test' not in source_dxf.blocks:
    print("Block 'b_test' not defined.")
    exit()

target_dxf = ezdxf.readfile("arc.dxf")

importer = Importer(source_dxf, target_dxf)
importer.import_block('b_test')
importer.finalize()

msp = target_dxf.modelspace()
msp.add_blockref('b_test', insert=(10, 10))
target_dxf.saveas("blockref_tutorial.dxf")


来源:https://stackoverflow.com/questions/60708633/python-and-ezdxf-copying-blocks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!