External References (XREF)

Added in version 1.1.

Attached XREFs are links to the modelspace of a specified drawing file. Changes made to the referenced drawing are automatically reflected in the current drawing when it’s opened or if the XREF is reloaded.

XREFs can be nested within other XREFs: that is, you can attach an XREF that contains another XREF. You can attach as many copies of an XREF as you want, and each copy can have a different position, scale, and rotation.

You can also overlay an XREF on your drawing. Unlike an attached XREF, an overlaid XREF is not included when the drawing is itself attached or overlaid as an XREF to another drawing.

DXF Files as Attached XREFs

Important

AutoCAD can only display DWG files as attached XREFs but ezdxf can only create DXF files. Consequently, any DXF file attached as an XREF to a DXF document must be converted to DWG in order to be viewed in AutoCAD. Fortunately, other CAD applications are more cooperative, BricsCAD has no problem displaying DXF files as XREFs, although it is not possible to attach a DXF file as an XREF in the BricsCAD application itself.

The ezdxf.xref module provides an interface for working with XREFs.

  • attach() - attach a DXF/DWG file as XREF

  • detach() - detach a BLOCK definition as XREF

  • embed() - embed an XREF as a BLOCK definition

  • dxf_info() - scans a DXF file for basic settings and properties

For loading the content of DWG files is a loading function required, which loads the DWG file as Drawing document. The odafc add-on module provides such a function: readfile()

XREF Structures

An XREF is a normal block definition located in the BLOCKS section with special flags set and a filename to the referenced DXF/DWG file and without any content, the block content is the modelspace of the referenced file. An XREF can be referenced (inserted) by one or multiple INSERT entities.

Find block definitions in the BLOCKS section:

for block_layout in doc.blocks:
    block = block_layout.block  # the BLOCK entity
    if block.is_xref:
        handle_xref(block_layout)
    elif block.is_xref_overlay:
        handle_xref_overlay(block_layout)

Find XREF references in modelspace:

for insert in msp.query("INSERT"):
    if insert.is_xref:
        handle_xref_reference(insert)
        # ... or get the XREF definition
        block_layout = insert.block()
        if block_layout is not None:
            handle_xref_definition(block_layout)

Use the helper function define() to create your own XREF definition, the attach() creates this definition automatically and raises an exception if the block already exists.

Supported Entities

The current implementation supports only copyable and transformable DXF entities, these are all basic entity types as LINE, CIRCLE, … and block references and their associated required table entries and objects from the OBJECTS section.

Unsupported is the ACAD_TABLE entity and preserved unknown entities wrapped in a DXFTagStorage class like proxy entities and objects. Support for these entities may be added in a later version of ezdxf. Unsupported entities are ignored and do not raise exceptions.

Most document features stored in the HEADER and OBJECTS sections are not supported by this module like GROUPS, LAYER_FILTER, GEODATA, SUN.

Added in version 1.3.0: Support for ACIS based entities was added.

Importing Data and Resources

The ezdxf.xref module replaces the Importer add-on.

The basic functionality of the ezdxf.xref module is loading data from external files including their required resources, which is an often requested feature by users for importing data from other DXF files into the current document.

The Importer add-on was very limited and removed many resources, where the ezdxf.xref module tries to preserve as much information as possible.

High Level Functions

ezdxf.xref.attach(doc: Drawing, *, block_name: str, filename: str, insert: UVec = (0, 0, 0), scale: float = 1.0, rotation: float = 0.0, overlay=False) Insert

Attach the file filename to the host document as external reference (XREF) and creates a default block reference for the XREF in the modelspace of the document. The function raises an XrefDefinitionError exception if the block definition already exist, but an XREF can be inserted multiple times by adding additional block references:

msp.add_blockref(block_name, insert=another_location)

Important

If the XREF has different drawing units than the host document, the scale factor between these units must be applied as a uniform scale factor to the block reference! Unfortunately the XREF drawing units can only be detected by scanning the HEADER section of a document by the function dxf_info() and is therefore not done automatically by this function. Advice: always use the same units for all drawings of a project!

Parameters:
  • doc – host DXF document

  • block_name – name of the XREF definition block

  • filename – file name of the XREF

  • insert – location of the default block reference

  • scale – uniform scaling factor

  • rotation – rotation angle in degrees

  • overlay – creates an XREF overlay if True and an XREF attachment otherwise

Returns:

default block reference for the XREF

Return type:

Insert

Raises:

XrefDefinitionError – block with same name exist

Added in version 1.1.

ezdxf.xref.define(doc: Drawing, block_name: str, filename: str, overlay=False) None

Add an external reference (xref) definition to a document.

XREF attachment types:

  • attached: the XREF that’s inserted into this drawing is also present in a document to which this document is inserted as an XREF.

  • overlay: the XREF that’s inserted into this document is not present in a document to which this document is inserted as an XREF.

Parameters:
  • doc – host document

  • block_name – name of the xref block

  • filename – external reference filename

  • overlay – creates an XREF overlay if True and an XREF attachment otherwise

Raises:

XrefDefinitionError – block with same name exist

Added in version 1.1.

ezdxf.xref.detach(block: BlockLayout, *, xref_filename: str | PathLike, overlay=False) Drawing

Write the content of block into the modelspace of a new DXF document and convert block to an external reference (XREF). The new DXF document has to be written by the caller: xref_doc.saveas(xref_filename). This way it is possible to convert the DXF document to DWG by the odafc add-on if necessary:

xref_doc = xref.detach(my_block, "my_block.dwg")
odafc.export_dwg(xref_doc, "my_block.dwg")

It’s recommended to clean up the entity database of the host document afterwards:

doc.entitydb.purge()

The function does not create any block references. These references should already exist and do not need to be changed since references to blocks and XREFs are the same.

Parameters:
  • block – block definition to detach

  • xref_filename – name of the external referenced file

  • overlay – creates an XREF overlay if True and an XREF attachment otherwise

Added in version 1.1.

ezdxf.xref.dxf_info(filename: str | PathLike) DXFInfo

Scans the HEADER section of a DXF document and returns a DXFInfo object, which contains information about the DXF version, text encoding, drawing units and insertion base point.

Raises:

IOError – not a DXF file or a generic IO error

ezdxf.xref.embed(xref: BlockLayout, *, load_fn: Callable[[str], Drawing] | None = None, search_paths: Iterable[Path | str] = tuple(), conflict_policy=ConflictPolicy.XREF_PREFIX) None

Loads the modelspace of the XREF as content into a block layout.

The loader function loads the XREF as Drawing object, by default the function ezdxf.readfile() is used to load DXF files. To load DWG files use the readfile() function from the ezdxf.addons.odafc add-on. The ezdxf.recover.readfile() function is very robust for reading DXF files with errors.

If the XREF path isn’t absolute the XREF is searched in the folder of the host DXF document and in the search_path folders.

Parameters:
  • xrefBlockLayout of the XREF document

  • load_fn – function to load the content of the XREF as Drawing object

  • search_paths – list of folders to search for XREFS, default is the folder of the host document or the current directory if no filepath is set

  • conflict_policy – how to resolve name conflicts

Raises:
  • XrefDefinitionError – argument xref is not a XREF definition

  • FileNotFoundError – XREF file not found

  • DXFVersionError – cannot load a XREF with a newer DXF version than the host document, try the odafc add-on to downgrade the XREF document or upgrade the host document

Added in version 1.1.

ezdxf.xref.load_modelspace(sdoc: Drawing, tdoc: Drawing, filter_fn: Callable[[DXFEntity], bool] | None = None, conflict_policy=ConflictPolicy.KEEP) None

Loads the modelspace content of the source document into the modelspace of the target document. The filter function filter_fn gets every source entity as input and returns True to load the entity or False otherwise.

Parameters:
  • sdoc – source document

  • tdoc – target document

  • filter_fn – optional function to filter entities from the source modelspace

  • conflict_policy – how to resolve name conflicts

Added in version 1.1.

ezdxf.xref.load_paperspace(psp: Paperspace, tdoc: Drawing, filter_fn: Callable[[DXFEntity], bool] | None = None, conflict_policy=ConflictPolicy.KEEP) None

Loads the paperspace layout psp into the target document. The filter function filter_fn gets every source entity as input and returns True to load the entity or False otherwise.

Parameters:
  • psp – paperspace layout to load

  • tdoc – target document

  • filter_fn – optional function to filter entities from the source paperspace layout

  • conflict_policy – how to resolve name conflicts

Added in version 1.1.

ezdxf.xref.write_block(entities: Sequence[DXFEntity], *, origin: UVec = (0, 0, 0)) Drawing

Write entities into the modelspace of a new DXF document.

This function is called “write_block” because the new DXF document can be used as an external referenced block. This function is similar to the WBLOCK command in CAD applications.

Virtual entities are not supported, because each entity needs a real database- and owner handle.

Parameters:
  • entities – DXF entities to write

  • origin – block origin, defines the point in the modelspace which will be inserted at the insert location of the block reference

Raises:

EntityError – virtual entities are not supported

Added in version 1.1.

Conflict Policy

class ezdxf.xref.ConflictPolicy(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

These conflict policies define how to handle resource name conflicts.

Added in version 1.1.

KEEP

Keeps the existing resource name of the target document and ignore the resource from the source document.

XREF_PREFIX

This policy handles the resource import like CAD applications by always renaming the loaded resources to <xref>$0$<name>, where xref is the name of source document, the $0$ part is a number to create a unique resource name and <name> is the name of the resource itself.

NUM_PREFIX

This policy renames the loaded resources to $0$<name> only if the resource <name> already exists. The $0$ prefix is a number to create a unique resource name and <name> is the name of the resource itself.

Low Level Loading Interface

The Loader class is the basic building block for loading entities and resources. The class manages a list of loading commands which is executed at once by calling the Loader.execute() method. It is important to execute the commands at once to get a consistent renaming of resources when using resource name prefixes otherwise the loaded resources would get a new unique name at each loading process even when the resources are loaded from the same document.

class ezdxf.xref.Loader(sdoc: Drawing, tdoc: Drawing, conflict_policy=ConflictPolicy.KEEP)

Load entities and resources from the source DXF document sdoc into the target DXF document.

Parameters:
  • sdoc – source DXF document

  • tdoc – target DXF document

  • conflict_policyConflictPolicy

load_modelspace(target_layout: BaseLayout | None = None, filter_fn: Callable[[DXFEntity], bool] | None = None) None

Loads the content of the modelspace of the source document into a layout of the target document, the modelspace of the target document is the default target layout. The filter function filter_fn is used to skip source entities, the function should return False for entities to ignore and True otherwise.

Parameters:
  • target_layout – target layout can be any layout: modelspace, paperspace layout or block layout.

  • filter_fn – function to filter source entities

load_paperspace_layout(psp: Paperspace, filter_fn: Callable[[DXFEntity], bool] | None = None) None

Loads a paperspace layout as a new paperspace layout into the target document. If a paperspace layout with same name already exists the layout will be renamed to “<layout name> (2)” or “<layout name> (3)” and so on. The filter function filter_fn is used to skip source entities, the function should return False for entities to ignore and True otherwise.

The content of the modelspace which may be displayed through a VIEWPORT entity will not be loaded!

Parameters:
  • psp – the source paperspace layout

  • filter_fn – function to filter source entities

load_paperspace_layout_into(psp: Paperspace, target_layout: BaseLayout, filter_fn: Callable[[DXFEntity], bool] | None = None) None

Loads the content of a paperspace layout into an existing layout of the target document. The filter function filter_fn is used to skip source entities, the function should return False for entities to ignore and True otherwise.

The content of the modelspace which may be displayed through a VIEWPORT entity will not be loaded!

Parameters:
  • psp – the source paperspace layout

  • target_layout – target layout can be any layout: modelspace, paperspace layout or block layout.

  • filter_fn – function to filter source entities

load_block_layout(block_layout: BlockLayout) None

Loads a block layout (block definition) as a new block layout into the target document. If a block layout with the same name exists the conflict policy will be applied. This method cannot load modelspace or paperspace layouts.

Parameters:

block_layout – the source block layout

load_block_layout_into(block_layout: BlockLayout, target_layout: BaseLayout) None

Loads the content of a block layout (block definition) into an existing layout of the target document. This method cannot load the content of modelspace or paperspace layouts.

Parameters:
  • block_layout – the source block layout

  • target_layout – target layout can be any layout: modelspace, paperspace layout or block layout.

load_layers(names: Sequence[str]) None

Loads the layers defined by the argument names into the target document. In the case of a name conflict the conflict policy will be applied.

load_linetypes(names: Sequence[str]) None

Loads the linetypes defined by the argument names into the target document. In the case of a name conflict the conflict policy will be applied.

load_text_styles(names: Sequence[str]) None

Loads the TEXT styles defined by the argument names into the target document. In the case of a name conflict the conflict policy will be applied.

load_dim_styles(names: Sequence[str]) None

Loads the DIMENSION styles defined by the argument names into the target document. In the case of a name conflict the conflict policy will be applied.

load_mline_styles(names: Sequence[str]) None

Loads the MLINE styles defined by the argument names into the target document. In the case of a name conflict the conflict policy will be applied.

load_mleader_styles(names: Sequence[str]) None

Loads the MULTILEADER styles defined by the argument names into the target document. In the case of a name conflict the conflict policy will be applied.

load_materials(names: Sequence[str]) None

Loads the MATERIALS defined by the argument names into the target document. In the case of a name conflict the conflict policy will be applied.

execute(xref_prefix: str = '') None

Execute all loading commands. The xref_prefix string is used as XREF name when the conflict policy ConflictPolicy.XREF_PREFIX is applied.