2

How can I fit the map extent into the QgsComposerMap size?

printable_layers = QgsMapLayerRegistry.instance().mapLayers().values()
printable_layers_ids = []
bigger_printable_layer = None

for layer in printable_layers:
    printable_layers_ids.append(layer.id())

    if type(bigger_printable_layer) != type(None):
        if layer.extent().width() + layer.extent().height() > bigger_printable_layer.extent().width() + bigger_printable_layer.extent().height():
            bigger_printable_layer = layer
    else:
        bigger_printable_layer = layer

printable_layers_ids.reverse()

template_document = QtXml.QDomDocument()
template_document.setContent(QtCore.QFile(Printer.printing_template_file_path), False)

map_renderer = QgsMapRenderer()
map_renderer.setLayerSet(printable_layers_ids)

rect = QgsRectangle(map_renderer.fullExtent())
rect.scale(1.1)
map_renderer.setExtent(rect)

map_renderer.setOutputSize(QSize(800, 600), 300)

composition = QgsComposition(map_renderer)
composition.loadFromTemplate(template_document)

composer_map = QgsComposerMap(composition, 0, 0, composition.paperWidth(), composition.paperHeight())
composer_map.setNewExtent(rect)
composer_map.updateItem()
composition.addComposerMap(composer_map)

# add created map to composition layers list
composition.refreshZList()

# not working
# composition.moveItemToBottom(composer_map)
# must do that instead
composition.setAllUnselected()
composition.setSelectedItem(composer_map)
composition.moveSelectedItemsToBottom()

# must refresh
composition.refreshZList()
composition.refreshItems()

composition.exportAsPDF(printed_file_path + ".pdf")
2

Done

map_renderer = QgsMapRenderer()
map_renderer.setLayerSet(printable_layers_ids)

composition = QgsComposition(map_renderer)
composition.loadFromTemplate(template_document)

map_renderer.setOutputSize(QSize(composition.paperWidth(), composition.paperHeight()), composition.printResolution())
map_renderer.setExtent(bigger_printable_layer.extent())

composer_map = QgsComposerMap(composition, 0, 0, composition.paperWidth(), composition.paperHeight())
composer_map.setNewExtent(map_renderer.extent())
composition.addComposerMap(composer_map)

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.