3

I want to develop "Print lay out functionality", but in output system is giving me whole image, I want to print only selected polygon. Also it is not displaying label names on print image.

Please suggest some way.

from PyQt4.QtGui import *
from PyQt4.QtCore import *
import time
l = iface.activeLayer()

for a in l.getFeatures():
     attrs = {16: 1}
     l.dataProvider().changeAttributeValues({a.id(): attrs})
     img = QImage(QSize(1280, 1024), QImage.Format_ARGB32_Premultiplied)
     # set image's background color
     color = QColor(255, 255, 255)
     img.fill(color.rgb())
     # create painter
     p = QPainter()
     p.begin(img)
     p.setRenderHint(QPainter.Antialiasing)
     render = QgsMapRenderer()
     palyr = QgsPalLayerSettings()
     palyr.readFromLayer(l)
     lst = [l.id()]
     render.setLayerSet(lst)
     render.setLabelingEngine(QgsPalLabeling())
     # set extent
     rect = QgsRectangle(render.fullExtent())
     rect.scale(1.1)
     render.setExtent(rect)
     render.setScale(1)
     render.setOutputSize(img.size(), img.logicalDpiX())
     render.render(p)
     p.end()
     # save image
     img.save("C:/example/Ashwin/%s.jpg" % a['CHALTA_NO'],"jpg")
     attrs = {16: 0}
     l.dataProvider().changeAttributeValues({a.id(): attrs})
     time.sleep(1)

enter image description here

  • I note that you used rect = QgsRectangle(render.fullExtent()), this uses the entire area. You could use the extent of selection – luca76 Dec 17 '15 at 9:37
  • when i am use rect = QgsRectangle(render.extent ()), it has giving me blank image. – Ashwin Bhayal Dec 17 '15 at 9:48
  • Is your QGIS updated to last version? – luca76 Dec 17 '15 at 10:06
2

Hint: for each feature, use the QgsFeature().geometry().boundingBox() to achieve the rectangle. In your case, is a.geometry().boundingBox() and it returns a QgsRectangle() object

rect = a.geometry().boundingBox()
...
render.setExtent(rect)
  • Thanks for the help friend. I got my solution .Now the only issue is that in image I am not getting the labels, I have on polygon. Please help in that too Please see above attached screenshots here I need labels – Ashwin Bhayal Dec 17 '15 at 10:17
  • Is your QGIS updated? Last version is 2.12.1 – luca76 Dec 17 '15 at 13:21
  • I have updated QGIS it's version 2.12.1-Lyon but it was making same polygon image it can not show length of polygon line and polygon Sr. No on label. for show label on image required any special code or not. – Ashwin Bhayal Dec 18 '15 at 5:49
  • Sorry for my huge late in response. I think that your code isn't correct. Have you seen the example from: gis.stackexchange.com/questions/84723/… – luca76 Dec 21 '15 at 13:59

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.