Friday, 25 August 2017

Export DXF from QGIS layer using PyQGIS?


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


Sample code:


dialog = QtGui.QFileDialog()
dialog.setFileMode(QtGui.QFileDialog.Directory)
dialog.setOption(QtGui.QFileDialog.ShowDirsOnly)
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()?



Answer



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.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...