[Qgis-developer] Rendering and Labeling Shapefile with PyQGIS
Zied Habtoul
zied.habtoul at gmail.com
Thu Nov 12 08:16:35 PST 2015
Hello i use this function to take a shapefile, label it based on the
specified attribute name, and render an image. but i get a white image.
i use Qgis 2.12 .
def quick_export(self):
file = QgsVectorLayer("path to shapefile", "BMAS", "ogr")
QgsMapLayerRegistry.instance().addMapLayer(file)
#Adjust layer Settings
#Code sample from
http://gis.stackexchange.com/questions/77870/how-to-label-vector-features-programmatically
palyr = QgsPalLayerSettings()
palyr.enabled = True
palyr.fieldName = 'Sum_emplpa'
palyr.placement= QgsPalLayerSettings.OverPoint
palyr.setDataDefinedProperty(QgsPalLayerSettings.Size,True,True,'8','')
palyr.writeToLayer(file)
if file.isValid():
print "File is valid."
mapRenderer = QgsMapRenderer()
rect = file.extent()
mapRenderer.setExtent(rect)
mapRenderer.setLabelingEngine(QgsPalLabeling())
lst = [file.id()]
mapRenderer.setLayerSet(lst)
mapRenderer.setLayerSet( lst )
c = QgsComposition(mapRenderer)
c.setPlotStyle(QgsComposition.Print)
x, y = 0, 0
w, h = c.paperWidth(), c.paperHeight()
composerMap = QgsComposerMap(c, x,y,w,h)
c.addItem(composerMap)
composerLabel = QgsComposerLabel(c)
composerLabel.adjustSizeToText()
c.addItem(composerLabel)
composerLabel.setItemPosition(20,10)
composerLabel.setItemPosition(20,10, 100, 30)
legend = QgsComposerLegend(c)
legend.model().setLayerSet(mapRenderer.layerSet())
c.addItem(legend)
#set image sizing
dpi = c.printResolution()
dpmm = dpi / 25.4
width = int(dpmm * c.paperWidth())
height = int(dpmm * c.paperHeight())
img = QImage(QSize(width, height), QImage.Format_ARGB32)
img.setDotsPerMeterX(dpmm * 1000)
img.setDotsPerMeterY(dpmm * 1000)
img.fill(0)
imagePainter = QPainter(img)
sourceArea = QRectF(0, 0, c.paperWidth(), c.paperHeight())
targetArea = QRectF(0, 0, width, height)
#renders image
c.render(imagePainter, targetArea, sourceArea)
imagePainter.end()
img.save("path to save the image", "png")
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/qgis-developer/attachments/20151112/f4186abe/attachment.html>
More information about the Qgis-developer
mailing list