File: separate_layers.py

package info (click to toggle)
ezdxf 1.4.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 104,528 kB
  • sloc: python: 182,341; makefile: 116; lisp: 20; ansic: 4
file content (54 lines) | stat: -rw-r--r-- 2,153 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#  Copyright (c) 2022, Manfred Moitzi
#  License: MIT License
import pathlib
import ezdxf
from ezdxf.addons import Importer
from ezdxf.query import EntityQuery

CWD = pathlib.Path("~/Desktop/Outbox").expanduser()
if not CWD.exists():
    CWD = pathlib.Path(".")

# ------------------------------------------------------------------------------
# This example shows how to separate entities by their layer attribute
#
# The example imports all entities from the modelspace into a new DXF document.
# The Importer add-on is required to also import the required resources used by
# the imported entities.
#
# Important advice:
# Keep things simple, more complex DXF documents may fail or at least the entities
# will not look the same as in the source file! Read the docs!
#
# Basic concept of layers : https://ezdxf.mozman.at/docs/concepts/layers.html
# Importer add-on: https://ezdxf.mozman.at/docs/addons/index.html
# ------------------------------------------------------------------------------


def main(filename: str):
    source_doc = ezdxf.readfile(CWD / filename)
    source_msp = source_doc.modelspace()
    # create an EntityQuery container with all entities from the modelspace
    source_entities = source_msp.query()
    # get all layer names from entities in the modelspace:
    all_layer_names = [e.dxf.layer for e in source_entities]
    # remove unwanted layers if needed

    for layer_name in all_layer_names:
        # create a new document for each layer with the same DXF version as the
        # source file
        layer_doc = ezdxf.new(dxfversion=source_doc.dxfversion)
        layer_msp = layer_doc.modelspace()
        importer = Importer(source_doc, layer_doc)
        # select all entities from modelspace from this layer (extended query
        # feature of class EntityQuery)
        entities: EntityQuery = source_entities.layer == layer_name  # type: ignore
        if len(entities):
            importer.import_entities(entities, layer_msp)
            # create required resources
            importer.finalize()
            layer_doc.saveas(CWD / f"{layer_name}.dxf")


if __name__ == "__main__":
    main("test.dxf")