3

I made a simple standalone QGIS app for rendering a set of layers and export it as a PDF file.

When i use iface.mapCanvas().mapRenderer() (inside QGIS console) for rendering, my output is OK.
If i want to create my own QgsMapRenderer (inside standalone app), the extent is displaced like on the picture:

displaced output

Here is my code:

from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import config

app = QgsApplication([], True)
QgsApplication.setPrefixPath(config.qgis_path, True)
QgsApplication.initQgis()

mlr = QgsMapLayerRegistry.instance()
crs = QgsCoordinateReferenceSystem(3857)

# creating a single layer
layer = QgsVectorLayer(config.data_dir + 'ZASRO.shp', 'ZASRO', 'ogr')
if not layer.isValid():
    print "layer failed to load !"
layer.setCrs(crs)
mlr.addMapLayer(layer)

layerSet = [layer.id()]

# map renderer
renderer = QgsMapRenderer()
renderer.setDestinationCrs(crs)
renderer.setLayerSet(layerSet)
renderer.setExtent(layer.extent())

# composition
comp = QgsComposition(renderer)
comp.setPlotStyle(QgsComposition.Print)
comp.setPaperSize(420.0, 297.0)
comp.setPrintResolution(300)

# composer map
composerMap = QgsComposerMap(comp, 0, 0, 420.0, 297.0)
composerMap.setNewExtent(renderer.fullExtent())
comp.addComposerMap(composerMap)

# pdf rendering
comp.exportAsPDF(config.out_dir + "out.pdf")

QgsApplication.exitQgis()

This i due to the fullExtent() function returning some bad values.
I guess my QgsMapRenderer is not valid for some reason ?

  • What happens if you replace composerMap.setNewExtent(renderer.fullExtent()) with composerMap.setNewExtent(layer.extent())? – ArMoraer Feb 17 '16 at 15:40
  • Same displacement. I tried a lot of things, even creating a QgsMapCanvas, still it doesn't solve the problem – Kef Feb 17 '16 at 15:44
2

OK I solved the problem by setting the renderer output size:

renderer.setOutputUnits(QgsMapRenderer.Millimeters)
renderer.setOutputSize(QSizeF(width, height), dpi)

And use zoomToExtent() instead of setNewExtent() on your QgsMapComposer

#composerMap.setNewExtent(extent)
composerMap.zoomToExtent(extent)

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.