.. _vector.dxf:

AutoCAD DXF
===========

.. shortname:: DXF

.. built_in_by_default::

DXF is an ASCII format used for interchanging AutoCAD drawings between
different software packages. OGR supports reading DXF files generated by
all recent versions of AutoCAD, and writing DXF files that are
compatible with AutoCAD 2004 and later.

Starting with GDAL 3.12, the DXF driver can also read the AutoCAD Binary DXF format
(not to be confused with DWG!)

DXF files are considered to have no georeferencing information through
OGR.

Driver capabilities
-------------------

.. supports_create::

.. supports_virtualio::

DXF Reader
----------

By default, the entire contents of the file are represented as a single
OGR layer named "entities". Features will all have the following generic
fields:

-  Layer: The name of the DXF layer. The default layer is "0".
-  PaperSpace: 1 if the entity is located on a layout (paper space),
   NULL otherwise.
-  SubClasses: Where available, a list of classes to which an entity
   belongs.
-  RawCodeValues: A string list
   containing all group codes and values that are not handled by the DXF
   reader. Only available when the configuration
   option :config:`DXF_INCLUDE_RAW_CODE_VALUES=TRUE`.

   .. config:: DXF_INCLUDE_RAW_CODE_VALUES
      :choices: TRUE, FALSE
      :default: FALSE

   -  Linetype: Where available, the line type used for this entity.
-  EntityHandle: The hexadecimal entity handle. A sort of feature id.
-  Text: The text of labels.

Supported Entities
~~~~~~~~~~~~~~~~~~

The following entity types are supported:

-  POINT: Produces a simple POINT geometry feature.
-  MTEXT, TEXT: Produces a POINT feature with LABEL style information.
   The style string may include the following parameters: f s t a c w p
   dx dy bo it. Text positioning might not precisely match CAD software
   (especially the vertical alignment of MTEXT), as calculation of the
   exact position would require GDAL to be aware of the font metrics.
   By default, character escapes such as %%p are honored where
   applicable, and MTEXT control sequences like \\Wx.xx; are stripped.
   To disable this behavior and retrieve the raw text values,
   set the configuration option :config:`DXF_TRANSLATE_ESCAPE_SEQUENCES=FALSE`.

   .. config:: DXF_TRANSLATE_ESCAPE_SEQUENCES
      :choices: TRUE, FALSE
      :default: TRUE

-  LINE, POLYLINE, LWPOLYLINE: Translated as a LINESTRING. Rounded
   polylines (those with their vertices' bulge attributes set) will be
   tessellated. Single-vertex polylines are translated to POINT.
   Polyface meshes are translated as POLYHEDRALSURFACE geometries.

   Starting with GDAL 3.10, the :config:`DXF_CLOSED_LINE_AS_POLYGON`
   configuration option can be set to TRUE to ask for closed POLYLINE and
   LWPOLYLINE to be exposed as OGR polygons.

   .. config:: DXF_CLOSED_LINE_AS_POLYGON
      :choices: TRUE, FALSE
      :default: FALSE


-  MLINE: Translated as a MULTILINESTRING. Only the geometry
   is reconstructed; styling applied to individual line elements
   within the MLINE is ignored. Fill colors and start/end caps are
   also omitted.

-  CIRCLE, ELLIPSE, ARC, SPLINE,HELIX: Translated as a
   LINESTRING, tessellating the curve into line segments.

   CIRCLEs with nonzero "thickness" (cylinders) are
   approximated as a POLYHEDRALSURFACE.

-  INSERT: By default, the block definition referenced by the INSERT
   will be inserted as a compound geometry (for example, a
   MULTILINESTRING for a block containing many lines, or a
   GEOMETRYCOLLECTION for a block that contains points and lines). If
   the block contains TEXT or MTEXT entities, they are not merged into
   the compound geometry and are instead returned as separate features.

   Three configuration options are available to control the behavior of
   INSERT entities:

   -  .. config:: DXF_MERGE_BLOCK_GEOMETRIES
         :choices: TRUE, FALSE
         :default: TRUE

         To avoid merging blocks into a
         compound geometry the :config:`DXF_MERGE_BLOCK_GEOMETRIES` config option may
         be set to FALSE. Use this option if you need to preserve the
         styling (such as colors) of individual linework entities within
         the block.

   -  .. config:: DXF_INLINE_BLOCKS

          See below.

   -  .. config:: DXF_FEATURE_LIMIT_PER_BLOCK
         :since: 2.3.0
         :default: 10000

         Maximum number of
         features inserted from a single block. Set to -1 for no limit.

-  ATTDEF, ATTRIB: Attributes (ATTRIB) are treated as TEXT entities,
   and attribute definitions (ATTDEF) inside blocks are ignored. The
   behavior is different when :config:`DXF_INLINE_BLOCKS` is false (see below).

-  HATCH: Line and arc boundaries are collected as a polygon geometry,
   but no effort is currently made to represent the fill style of HATCH
   entities. Behavior is affected by the following configuration option:

   -  .. config:: DXF_HATCH_TOLERANCE
         :since: 2.3.0

         Determines the
         tolerance used when looking for the next component to add to the
         hatch boundary.

-  3DFACE, SOLID, TRACE: Translated as POLYGON, except
   for SOLID and TRACE entities with only one distinct vertex
   (translated as POINT) or two distinct vertices (translated as
   LINESTRING).

-  DIMENSION: The DXF format allows each DIMENSION entity to
   reference an "anonymous" block (a block whose name starts with
   \*D) that contains the geometry of the DIMENSION. If present, this
   anonymous block will be inlined at the required position.
   Otherwise, fallback will occur to a simple DIMENSION renderer that
   explodes a linear dimension as a MULTILINESTRING feature.
   Arrowheads, if present, are translated as one or more additional
   features. The fallback renderer will render nonlinear dimensions
   as if they were linear.

-  LEADER, MULTILEADER: The leader line is translated as a LINESTRING
   (LEADER) or MULTILINESTRING (MULTILEADER). Arrowheads, if present,
   are translated as one or more additional features. Text for
   MULTILEADER entities is translated into a POINT feature with a
   label. Block content for MULTILEADERS is treated as for INSERT.
   Spline leaders are tessellated into line segments.

-  WIPEOUT: a light support of WIPEOUT entities can parse the outline
   geometry of WIPEOUT entities and translate it into a POLYGON feature.
   The feature is 2D support only - Z coordinates are ignored.

-  3DSOLID, REGION, BODY, SURFACE: See below.

A reasonable attempt is made to preserve color, line width (lineweight),
line type, text size and orientation via OGR feature styling information
when translating entities. Currently no effort is made to preserve
complex line types (those that include text or shapes) or HATCH fill
styles.

The :config:`OGR_ARC_STEPSIZE` and :config:`OGR_ARC_MAX_GAP` configurations
options control the approximation of arcs, ellipses, circles and rounded
polylines as linestrings.

For splines, the interpolated polyline contains eight vertices for each
control point.

Object coordinate systems (OCS), also known as "extrusions", are
supported for all entities to which they apply as per the DXF
specification, except DIMENSION, LEADER and MULTILEADER. These three
entity types also currently lack support for elevations; the geometries
will always be 2D.


.. _dxf_inline_blocks:

DXF_INLINE_BLOCKS
~~~~~~~~~~~~~~~~~

The default behavior is for INSERT entities to be exploded with the
geometry of the BLOCK they reference. However, if the :config:`DXF_INLINE_BLOCKS`
configuration option is set to the value FALSE, then the behavior is
different as described here.

-  A new layer will be available called "blocks". It will contain one or
   more features for each BLOCK defined in the file. In addition to the
   usual fields, they will also have a Block field indicating what block
   they are part of.
-  ATTDEF entities in the blocks layer will have an
   AttributeTag field, giving the tag of the ATTDEF entity.
-  The entities layer will have several new fields:

   -  BlockName: The name of the referenced block.
   -  BlockScale: The X, Y, and Z scale factors.
   -  BlockAngle: The angle of the block in degrees.
   -  BlockOCSNormal: The unit normal vector of the
      object coordinate system (OCS) of the INSERT entity.
   -  BlockOCSCoords: The OCS coordinates of the
      insertion point.
   -  BlockAttributes: The text content of attributes
      associated with this block. Each entry in this string list
      contains an attribute tag, followed by a space, followed by the
      text for that attribute (which may be empty).

-  INSERT entities will populate these new fields with the corresponding
   information (they are null for all other entities).
-  INSERT entities will not have block geometry inlined - instead they
   will have a POINT geometry for the insertion point.

The intention is that with :config:`DXF_INLINE_BLOCKS` disabled, the block
references will remain as references and the original block definitions
will be available via the blocks layer. On export this configuration
will result in the creation of similar blocks.

3D Extensibility
~~~~~~~~~~~~~~~~

DXF files may contain 3DSOLID, REGION, BODY and SURFACE entities, which
contain 3D modelling data in the proprietary Autodesk ShapeManager (ASM) format,
a broadly compatible fork of the ACIS format. GDAL cannot transform these
entities into OGR geometries, so they are skipped by default.

This behavior can be controlled with the following configuration option:

- .. config:: DXF_3D_EXTENSIBLE_MODE
     :choices: TRUE, FALSE
     :since: 2.3.0

     If TRUE, include ASM entities with the raw ASM
     data stored in a field, allowing for interoperability with commercial conversion
     tools. This option adds two new fields:

     -  ASMData: A binary field that contains the ASM data.
     -  ASMTransform: A column-major list of 12 real values indicating the affine
        transformation to be applied to the entity.

This feature only works for DXF files in AutoCAD 2013 (AC1027) format
and later.

Character Encodings
~~~~~~~~~~~~~~~~~~~

Normally DXF files are in the ANSI_1252 / Win1252 encoding. GDAL/OGR
attempts to translate this to UTF-8 when reading and back into ANSI_1252
when writing. DXF files can also have a header field ($DWGCODEPAGE)
indicating the encoding of the file. An attempt is made to use this to
recode other code pages to UTF-8. Whether this works will depend on the
code page naming and whether GDAL/OGR is built against the iconv library
for character recoding.

In some cases the $DWGCODEPAGE setting in a DXF file will be wrong, or
unrecognised by OGR. In this case, :config:`DXF_ENCODING` may be used to
override what id will be used by OGR in transcoding:

-  .. config:: DXF_ENCODING

      An encoding name
      supported by :cpp:func:`CPLRecode` (i.e. an iconv name), not a DXF $DWGCODEPAGE
      name. Using a value "UTF-8" will avoid any attempt to
      recode the text as it is read.

Open options
------------

.. versionadded:: 3.10

|about-open-options|
The following open options are supported:

- .. oo:: CLOSED_LINE_AS_POLYGON
     :since: 3.10
     :default: NO
     :choices: YES, NO

     See :config:`DXF_CLOSED_LINE_AS_POLYGON`

- .. oo:: INLINE_BLOCKS
     :since: 3.10
     :default: YES
     :choices: YES, NO

     See :ref:`dxf_inline_blocks`

- .. oo:: MERGE_BLOCK_GEOMETRIES
     :since: 3.10
     :default: YES
     :choices: YES, NO

     See :config:`DXF_MERGE_BLOCK_GEOMETRIES`

- .. oo:: TRANSLATE_ESCAPE_SEQUENCES
     :since: 3.10
     :default: YES
     :choices: YES, NO

     See :config:`DXF_TRANSLATE_ESCAPE_SEQUENCES`

- .. oo:: INCLUDE_RAW_CODE_VALUES
     :since: 3.10
     :default: NO
     :choices: YES, NO

     See :config:`DXF_INCLUDE_RAW_CODE_VALUES`

- .. oo:: 3D_EXTENSIBLE_MODE
     :since: 3.10
     :default: NO
     :choices: YES, NO

     See :config:`DXF_3D_EXTENSIBLE_MODE`

- .. oo:: HATCH_TOLERANCE
     :since: 3.10
     :choices: <tolerance>

     See :config:`DXF_HATCH_TOLERANCE`

- .. oo:: ENCODING
     :since: 3.10
     :choices: <encoding>

     See :config:`DXF_ENCODING`


DXF Writer
----------

DXF files are written in AutoCAD 2004 format. A standard header
(everything up to the ENTITIES keyword) is written from the
$GDAL_DATA/header.dxf file, and the $GDAL_DATA/trailer.dxf file is added
after the entities. Only one OGR layer can be used to create the output
file (but many DXF layers can be created - see below).

-  Point features with LABEL styling are written as MTEXT entities based
   on the styling information.
-  Point features without LABEL styling are written as POINT entities.
-  LineString and MultiLineString features are written as one or more
   LWPOLYLINE entities, closed in the case of polygon rings. If the
   geometry does not have a constant elevation, a POLYLINE entity is
   written. An effort is made to preserve line width and color.
-  Polygon, Triangle and MultiPolygon features are written as HATCH
   entities by default. To write these features as LWPOLYLINE/POLYLINE
   entities instead, set the configuration option :config:`DXF_WRITE_HATCH=FALSE`:

   -  .. config:: DXF_WRITE_HATCH
         :choices: TRUE, FALSE
         :default: TRUE

         If ``TRUE``, write Polygon, Triangle, and MultiPolygon features as
         ``HATCH`` entities. If false, write them as ``LWPOLYLINE/POLYLINE``.

   You may need to do this if your geometries do not have a
   constant elevation, as the DXF HATCH entity cannot represent such
   geometries.

Only the first tool (PEN, BRUSH, etc) in the style string is read. The
following style string parameters are understood:

.. list-table::
   :header-rows: 1

   * - Tool
     - Available on geometry types
     - Supported parameters
   * - PEN
     - Point, (Multi)LineString
     - color (c); width (w); dash pattern (p)
   * - BRUSH
     - (Multi)Polygon, Triangle
     - foreground color (fc), background color (bc), brush id (id), angle (a), scaling factor (s)
   * - SYMBOL
     - Point
     - color (c)
   * - LABEL
     - Point
     - text (t); font name (f); font size (s), treated as cap
       height; bold (bo); italic (it); text color (c); x and y offsets (dx,
       dy); angle (a); anchor point (p); stretch (w)

Note: for BRUSH, only foreground color is supported before GDAL 3.12.

|about-dataset-creation-options|
The driver supports the following dataset creation options:

-  .. dsco:: HEADER
      :choices: <filename>

      Override the header file used - in place of
      header.dxf located in the GDAL_DATA directory.

-  .. dsco:: TRAILER
      :choices: <filename>

      Override the trailer file used - in place
      of trailer.dxf located in the GDAL_DATA directory.

-  .. dsco:: FIRST_ENTITY
      :choices: <integer>

      Identifier of first entity

-  .. dsco:: INSUNITS
      :choices: AUTO, HEADER_VALUE, UNITLESS, INCHES, FEET, MILLIMETERS, CENTIMETERS, METERS, US_SURVEY_FEET
      :default: AUTO
      :since: 3.11

      Drawing units for the model space
      (`$INSUNITS <https://help.autodesk.com/view/ACD/2018/ENU/?guid=GUID-A58A87BB-482B-4042-A00A-EEF55A2B4FD8>`__ system variable).
      The default ``AUTO`` mode first check if the written layer has a projected
      CRS, and if so uses is linear units to determine the value of ``$INSUNITS``.
      Otherwise it fallbacks to the value of the header template (``HEADER_VALUE`` mode),
      which is ``INCHES``.

-  .. dsco:: MEASUREMENT
      :choices: HEADER_VALUE, IMPERIAL, METRIC
      :default: HEADER_VALUE
      :since: 3.11

      Whether the current drawing uses imperial or metric hatch pattern and linetype
      (`$MEASUREMENT <https://help.autodesk.com/view/ACD/2018/ENU/?guid=GUID-1D074C55-0B63-482E-8A37-A52AC0C7C8FE>`__ system variable).
      Defaults to the value of the header template, which is ``IMPERIAL``.


The header and trailer templates can be
complete DXF files. The driver will scan them and only extract the
needed portions (portion before or after the ENTITIES section).

Block References
~~~~~~~~~~~~~~~~

It is possible to export a "blocks" layer to DXF in addition to the
"entities" layer in order to produce actual DXF BLOCKs definitions in
the output file. It is also possible to write INSERT entities if a block
name is provided for an entity. To make this work the following
conditions apply:

-  A "blocks" layer may be created, and it must be created before the
   entities layer.
-  The entities in the blocks layer should have the Block field
   populated.
-  Objects to be written as INSERTs in the entities layer should have a
   POINT geometry, and the BlockName field set. You may also set
   BlockAngle, BlockScale, BlockOCSNormal and BlockOCSCoords (see above
   under :config:`DXF_INLINE_BLOCKS` for details). If BlockOCSCoords is set to a
   list of 3 real numbers, it is used as the location of the block; in
   this situation the position of the POINT geometry is ignored.
-  If a block (name) is already defined in the template header, that
   will be used regardless of whether a new definition was provided in
   the blocks layer.

The intention is that a simple translation from DXF to DXF with
:config:`DXF_INLINE_BLOCKS` set to FALSE will approximately reproduce the original
blocks and keep INSERT entities as INSERT entities rather than exploding
them.

Layer Definitions
~~~~~~~~~~~~~~~~~

When writing entities, if populated the Layer field is used to set the
written entities layer. If the layer is not already defined in the
template header then a new layer definition will be introduced, copied
from the definition of the default layer ("0").

Linetype Definitions
~~~~~~~~~~~~~~~~~~~~

When writing linestring geometries, the following rules apply with
regard to linetype (dash pattern) definitions.

-  If the Linetype field is set on a written feature, and that linetype
   is already defined in the template header, then it will be referenced
   from the entity. If a style string is present with a "p" pattern
   proportional to the linetype defined in the header, a linetype scale
   value is written.
-  If the Linetype field is set, but the linetype is not defined in the
   header template, then a definition will be added if the feature has
   an OGR style string with a PEN tool and a "p" pattern setting.
-  If the feature has no Linetype field set, but it does have an OGR
   style string with a PEN tool with a "p" pattern set, then an
   automatically named linetype will be created in the output file. Or,
   if an appropriate linetype was previously created, that linetype will
   be referenced, with a linetype scale if required.

The intention is that "dot dash" style patterns will be preserved when
written to DXF and that specific linetypes can be predefined in the
header template, and referenced using the Linetype field if desired.

It is assumed that patterns are using "g" (georeferenced) units for
defining the line pattern. If not, the scaling of the DXF patterns is
likely to be wrong - potentially very wrong.

Binary DXF to ASCII DXF direct translation
------------------------------------------

.. versionadded:: 3.12

A command like ``ogr2ogr out_ascii.dxf in_binary.dxf`` without any additional
parameter will go through a direct conversion path.

See also
--------

List of known issues :source_file:`ogr/ogrsf_frmts/dxf/KNOWN_ISSUES.md`

`AutoCAD 2000 DXF
Reference <https://web.archive.org/web/20150923180435/http://www.autodesk.com/techpubs/autocad/acad2000/dxf/>`__

`AutoCAD 2014 DXF
Reference <http://images.autodesk.com/adsk/files/autocad_2014_pdf_dxf_reference_enu.pdf>`__
