I recommend using the following script by Tim Sutton as a base, it worked well for me:- http://kartoza.com/how-to-create-a-qgis-pdf-report-with-a-few-lines-of-python/
Just pass an empty dict to the composition.loadFromTemplate() function instead of the 'substitution map' he uses, since you're not interested in that functionality.
Also, since you asked about "export as image" rather than "export as PDF", you have to do a bit more work than use the exportAsPDF() member function.
Below is a modified version of Tim's code that should do the trick, working from an external Python script. Set the DPI, and project+composer file variables as required.
(If you are using the Python console within QGIS rather than doing this as an external script, you can get the current map canvas using the qgis.iface and don't need to do use all the project loading etc code).
import sys
from qgis.core import (
QgsProject, QgsComposition, QgsApplication, QgsProviderRegistry)
from qgis.gui import QgsMapCanvas, QgsLayerTreeMapCanvasBridge
from PyQt4.QtCore import QFileInfo
from PyQt4.QtXml import QDomDocument
gui_flag = True
app = QgsApplication(sys.argv, gui_flag)
# Make sure QGIS_PREFIX_PATH is set in your env if needed!
app.initQgis()
# Probably you want to tweak this
project_path = 'project.qgs'
# and this
template_path = 'template.qpt'
# Set output DPI
dpi = 300
canvas = QgsMapCanvas()
# Load our project
QgsProject.instance().read(QFileInfo(project_path))
bridge = QgsLayerTreeMapCanvasBridge(
QgsProject.instance().layerTreeRoot(), canvas)
bridge.setCanvasLayers()
template_file = file(template_path)
template_content = template_file.read()
template_file.close()
document = QDomDocument()
document.setContent(template_content)
ms = canvas.mapSettings())
composition = QgsComposition(ms)
composition.loadFromTemplate(document, {})
# You must set the id in the template
map_item = composition.getComposerItemById('map')
map_item.setMapCanvas(canvas)
map_item.zoomToExtent(canvas.extent())
# You must set the id in the template
legend_item = composition.getComposerItemById('legend')
legend_item.updateLegend()
composition.refreshItems()
dpmm = dpi / 25.4
width = int(dpmm * composition.paperWidth())
height = int(dpmm * composition.paperHeight())
# create output image and initialize it
image = QImage(QSize(width, height), QImage.Format_ARGB32)
image.setDotsPerMeterX(dpmm * 1000)
image.setDotsPerMeterY(dpmm * 1000)
image.fill(0)
# render the composition
imagePainter = QPainter(image)
composition.renderPage(imagePainter, 0)
imagePainter.end()
image.save("out.png", "png")
QgsProject.instance().clear()
QgsApplication.exitQgis()
Best Answer
A manual solution would be:
In print composer item properties > extents, find the xmin, xmax, ymin and ymax values of the map item.
Use the
Geometry by expression
tool to create a rectangular polygon. Substitute the actual values into this expression: