Friday, 16 November 2018

qgis - How to use map composer in a stand-alone script?


I'm trying to follow the map rendering section from the pyqgis cookbook, but I'd like to test this as a standalone application. I can do the first part, using simple rendering, but I'm a bit stuck doing the second example using the map composer as a standalone script.


Here is a standalone example for the bit I can do:


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

from PyQt4.QtXml import *

QgsApplication.setPrefixPath("/usr/", True)
QgsApplication.initQgis()

fh = open("eg.csv","w")
fh.write("""
x,y,name
153.0278, -27.4679, Brisbane
144.2500, -23.4500, Longreach

145.7753, -16.9256, Cairns
""")
fh.close()

uri = "eg.csv?delimiter=%s&xField=%s&yField=%s" % (",", "x", "y")
layer = QgsVectorLayer(uri, "eglayer", "delimitedtext")
QgsMapLayerRegistry.instance().addMapLayer(layer)
img = QImage(QSize(800,600), QImage.Format_ARGB32_Premultiplied)
color = QColor(255,255,255)
img.fill(color.rgb())

p = QPainter()
p.begin(img)
render = QgsMapRenderer()
lst = [ layer.getLayerID() ] # add ID of every layer
render.setLayerSet(lst)
rect = QgsRectangle(render.fullExtent())
rect.scale(1.1)
render.setExtent(rect)
render.setOutputSize(img.size(), img.logicalDpiX())
render.render(p)

p.end()
img.save("render.png","png")

What I'd really like to do is the same, but use QgsComposition, and save as for example pdf. The cookbook says:



When using composer in a standalone application, you can create your own map renderer instance the same way as shown in the section above and pass it to the composition.



This bit I couldn't do, all my attempts either get an empty map, or a segfault. I'm running linux mint 13, using qgis 1.8.0. It would be great if someone could show me how to modify the simple example to one that uses the composer.




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...