I want to export a DXF file from a QGIS layer.

Sample code:

dialog = QtGui.QFileDialog()
DirectoryName = dialog.getExistingDirectory()
layers = self.iface.mapCanvas().layers()

for layer in layers:         
     filename = DirectoryName + "/" + layer.name() + ".dxf"    
     QgsVectorFileWriter.writeAsVectorFormat(layer, filename, "utf-8", layer.crs(), "DXF", 1)

Result DXF file is empty.

How can I export as DXF file using either QgsVectorFileWriter() or QgsDxfExport()?

  • 2
    Welcome to GIS SE! As a new user be sure to take the Tour to learn about our focussed Q&A format. You mention Qgsdxfexport() in your title but have you tried it? If so, what happened?
    – PolyGeo
    Feb 1 '18 at 8:20
  • I want to export a DXF file using QgsVectorFileWriter.writeAsVectorFormat() or Qgsdxfexport() ... anyway ...... i wish!! search !!! sample Code export DXF
    – 김철진
    Feb 1 '18 at 11:22

You can take example on the code in qgisapp.cpp and transform it to python as follows (just replace the elements within underscores):

dxfExport = QgsDxfExport()

settings = iface.mapCanvas().mapSettings()
# settings.setLayerStyleOverrides( QgsProject.instance().mapThemeCollection().mapThemeStyleOverrides( _yourmaptheme_ ) )
dxfExport.setMapSettings( settings )
dxfExport.addLayers( _layers_ )
dxfExport.setSymbologyScale( _scale_ )
dxfExport.setSymbologyExport( _mode_ )
dxfExport.setLayerTitleAsName( _title_ )
dxfExport.setDestinationCrs( _crs_ )
dxfExport.setForce2d( _force2d_ )
# dxfExport.setFlags( _flags_ )
dxfExport.setExtent( _extent_ )

dxfFile = QFile( fileName )
dxfExport.writeToFile( dxfFile, _encoding_ )

addLayer was causing a crash in QGIS. It has been fixed in QGIS 2.18.17 and QGIS 3.0. _layers_ is now a list of QgsDxfExport.DxfLayer( layer )

Another interesting approach (although not in Python) is that you can run QGIS dxf export from the command line: qgis.exe --dxf-export file.dxf myproject.qgs

See the command line options in the QGIS documentation for a complete description.

  • 1
    issues.qgis.org/issues/11790 QgsDxfExport.addLayers causes crash
    – 김철진
    Feb 12 '18 at 5:49
  • In this cas maybe you can try installing an earlier version of QGIS? @김철진
    – NettaB
    Feb 12 '18 at 10:46
  • I found an issue in the Python bindings. Will try to fix it. Feb 12 '18 at 11:35
  • There are 2 pull requests (QGIS 2.18 and QGIS 3.0) pending which fixe the issue. See github.com/qgis/QGIS/pull/6323 I will update the code as soon as it's merged Feb 12 '18 at 13:42
  • this is merged and will be release in QGIS 2.18.17 (23.02.2018) Feb 12 '18 at 16:55

If I use your code in the Python Console with the QgsVectorFileWriter() class , the value 5 is returned which seems to be a ErrAttributeCreationFailed. We could skip the attribute creation using skipAttributeCreation=True as a parameter if you don't care for the attributes.

So your final line should read:

QgsVectorFileWriter.writeAsVectorFormat(layer, filename, "utf-8", layer.crs(), "DXF", skipAttributeCreation=True)
  • I really appreciate your answer.!!! If the layer has a column called 'AAA' and I want to use it as a layer attribute of a DXF file, how do I change the code?
    – 김철진
    Feb 1 '18 at 23:15
  • @김철진 - Not easily unfortunately, I could not find a way to transfer the attributes over as you would using Project > Export DXF....
    – Joseph
    Feb 2 '18 at 11:36
  • Hm...anyway. really. Thank you!!! Do you know a simple sample code that uses QgsDxfexport?
    – 김철진
    Feb 2 '18 at 11:41
  • @김철진 - Apologies but I could not find any sample code online yet, if I do I will post it here :)
    – Joseph
    Feb 2 '18 at 11:58

Suggested solution: using the ogr library, with this approach it is possible to set the value of the "Layer" attribute of the DXF with an attribute from the inLayer.

from osgeo import ogr
import os

# Get the input Layer
inShapefile = "c://gis//wrld.shp"
inDriver = ogr.GetDriverByName("ESRI Shapefile")
inDataSource = inDriver.Open(inShapefile, 0)
inLayer = inDataSource.GetLayer()

# Create the output Layer
outDXF = "wrld.dxf"
outDriver = ogr.GetDriverByName("DXF")

# Create the output DXF
outDataSource = outDriver.CreateDataSource(outDXF)
outLayer = outDataSource.CreateLayer("wrld", geom_type=ogr.wkbPolygon)

# Add input Layer Fields to the output Layer
inLayerDefn = inLayer.GetLayerDefn()
for i in range(0, inLayerDefn.GetFieldCount()):
    fieldDefn = inLayerDefn.GetFieldDefn(i)

# Get the output Layer's Feature Definition
outLayerDefn = outLayer.GetLayerDefn()

for i in range(0, inLayer.GetFeatureCount()):
    # Get the input Feature
    inFeature = inLayer.GetFeature(i)
    # Create output Feature
    outFeature = ogr.Feature(outLayerDefn)
    # Add attribute by index from inFeature to pass to output Layer.
    # Set the field_num (here 2) by the position of the field in the original file.
    outFeature.SetField("Layer", inFeature.GetField(2))         
    # Set geometry.
    geom = inFeature.GetGeometryRef()
    # Add new feature to output Layer
    inFeature = None
    outFeature = None

# Save and close DataSources
inDataSource = None
outDataSource = None

EDIT: This can be achieved also by :

import subprocess
command = ["C:\\Program Files\\QGIS 2.14\\bin\\ogr2ogr.exe", "-f", "DXF", "output.dxf", "c:\\gis\\wrld.shp", "-sql", "select ISO as Layer from wrld"]

For lines use:

import subprocess
command = ["C:\\Program Files\\QGIS 2.14\\bin\\ogr2ogr.exe", "-f", "DXF", "output_l.dxf", "c:\\gis\\wrld.shp", "-sql", "select ISO as Layer from wrld", "-nlt", "MULTILINESTRING"]

[Note: ISO is a name of a field in wrld.shp]

  • I would like to create one DXF file with both point, line, and ploygon. Is it possible?
    – 김철진
    Feb 12 '18 at 15:26
  • I am very pleased to learn from you. and this case. The dxf file has only polygons. What if I want to add point data and line data to dxf?
    – 김철진
    Feb 13 '18 at 0:55
  • I'm looking into the matter, nothing in the doc, so I'm imrovising hopefully I'll have an answer today.
    – NettaB
    Feb 13 '18 at 9:50
  • if [a.shp] is point and [b.shp] is line and [c.shp] is polygon .. I wish [D.dxf] including [a.shp] , [b.shp] and [c.shp]]
    – 김철진
    Feb 13 '18 at 10:46
  • Unfortunately I couldn't find a solution for that, will keep trying. Also looking for merge options for dxf
    – NettaB
    Feb 13 '18 at 11:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.