[GIS] Extent problem in PyQgis

pyqgispythonqgis-2.10qgis-2.11

I'm trying to set the extent of a square feature to the canvas, that works in QGIS, but when I print the canvas into a PDF, it always gives me some empty area, below is the screenshot of QGIS canvas having feature extent:

enter image description here

and below is the resulting PDF having empty spaces:

enter image description here

the pyqgis code used to get these results:

from qgis.core import *  

mr=iface.mapCanvas().mapRenderer()  
composition = QgsComposition(mr)
composition.setPaperSize(220, 220)
composerMap=QgsComposerMap(composition,0,0,composition.paperWidth(),composition.paperHeight())
composition.addItem(composerMap)

layer =  QgsVectorLayer('Polygon?crs=EPSG:4326', 'poly' , "memory")
pr = layer.dataProvider() 
poly = QgsFeature()
poly.setGeometry(QgsGeometry.fromWkt("POLYGON((0 0, 0 1, 1 1, 1 0, 0 0))"))
pr.addFeatures([poly])
layer.updateExtents()
QgsMapLayerRegistry.instance().addMapLayers([layer])
bb =  poly.geometry().boundingBox()
iface.mapCanvas().setExtent(bb)
iface.mapCanvas().refresh()
composition.refreshItems()
composition.exportAsPDF('test.pdf')

Best Answer

The following code should work:

from qgis.core import *

# create an in-memory layer and add it to the QGIS project
layer =  QgsVectorLayer('Polygon?crs=EPSG:4326', 'poly' , "memory")
pr = layer.dataProvider() 
poly = QgsFeature()
poly.setGeometry(QgsGeometry.fromWkt("POLYGON((0 0, 0 1, 1 1, 1 0, 0 0))"))
pr.addFeatures([poly])
layer.updateExtents()
QgsMapLayerRegistry.instance().addMapLayers([layer])

# set map canvas extent
bb =  poly.geometry().boundingBox()
iface.mapCanvas().setExtent(bb)

mr = iface.mapCanvas().mapRenderer()
composition = QgsComposition(mr)
composition.setPaperSize(220, 220)
composition.setPlotStyle(QgsComposition.Print)
composerMap = QgsComposerMap(
    composition, 0, 0, 
    composition.paperWidth(), composition.paperHeight()
)
composerMap.zoomToExtent(bb)
composition.addItem(composerMap)
composition.exportAsPDF('test.pdf')

There are 2 main differences:

  1. In your code, the layer was not included in the map composer. One way for solving this is to create the layer before creating the map composer. Obviously you could manage this part somehow otherwise you would not have anything in your PDF.

  2. You need to set the extent of the composer map manually to fit the rectangle with composerMap.zoomToExtent(bb).

The resulting PDF is as follows:

enter image description here

Related Question