I try to write a python script in order to do the following:
- load a vector layer
- open an existing composition
- export the composition as PDF
If I use this simplified code in the Python console of QGis. Everything is working fine, the new layer is added and exported with the composition (you must have at least one composer in your project) :
from PyQt4.QtGui import *
vectorLyr = QgsVectorLayer("d:/test.shp", 'test','ogr')
if not vectorLyr.isValid():
print "Layer %s did not load" % vectorLyr.name()
vectorLyr.updateExtents()
iface.mapCanvas().refresh()
reg = QgsMapLayerRegistry.instance()
reg.addMapLayer(vectorLyr)
#load first composition
comp = iface.activeComposers()[0].composition()
comp.refreshItems()
comp.setUseAdvancedEffects(True)
comp.exportAsPDF('d:/tmp/test.pdf')
# export is correct
but once I try to generalize the code by creating an export function, the layer is no longer exported with the composition:
from PyQt4.QtGui import *
def export(layerPath, layerName):
vectorLyr = QgsVectorLayer(layerPath, layerName,"ogr")
if not vectorLyr.isValid():
print "Layer %s did not load" % vectorLyr.name()
vectorLyr.updateExtents()
iface.mapCanvas().refresh()
reg = QgsMapLayerRegistry.instance()
reg.addMapLayer(vectorLyr)
comp = iface.activeComposers()[0].composition()
comp.refreshItems()
comp.setUseAdvancedEffects(True)
comp.exportAsPDF('d:/tmp/test.pdf')
return
export("d:/test.shp", "test")
#the vector layer added dynamically is not on the map
I'm new to Python and new to QGis API. Any idea of what I'm missing?