1

I expect the following code to find the bounding box around feature (which is the magenta polygon in the picture) and render that so that the height is 1000px. The white background is indeed the bounding box of the feature but it's smaller than 1000px, on a bigger gray background, and the whole SVG is still larger; moreover, features outside the bounding box are drawn.

How do I draw the exact extent I want, at an exact specified extent?

from PyQt4.QtSvg import *
from PyQt4.QtGui import *
from PyQt4.QtCore import *

layers = QgsMapLayerRegistry.instance().mapLayers()
for layer_name, layer in layers.items():
    if 'regions' in layer_name:
        break

feature = next(layer.getFeatures(QgsFeatureRequest(4)))
region_name = feature.attribute('regionname')
region = feature.geometry()
bb = region.boundingBox()

renderer = iface.mapCanvas().mapRenderer()

c = QgsComposition(renderer)
c.setPlotStyle(QgsComposition.Print)

composerMap = QgsComposerMap(c, 0, 0, 1000, 1000)
composerMap.setNewExtent(bb)
c.addItem(composerMap)

print (composerMap.rect().width(),composerMap.rect().height())
print composerMap.extent().toRectF()

c.setPaperSize(composerMap.rect().width(),composerMap.rect().height())

svg = QSvgGenerator()
svg.setFileName("/tmp/mwe.svg")
svg.setSize(QSize(composerMap.rect().width(),composerMap.rect().height()))
svg.setTitle(region_name)

painter = QPainter(svg)
c.render(painter)
painter.end()

mwe.svg

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.