PyQGIS Export – Exporting Composition as Image

print-composerpyqgis

QGIS Print Composer has tool "Save As Image" and I found appropriate function in QGIS source code exportCompositionAsImage. Is it possible to get access to existing Print Composer from Python console and perform this operation – export composition as image with composer settings.

UPDATE #1: Thanks to @ndawson. I'm using printPageAsRaster function for printing different combinations of layers created with layerCombinations plugin:

from layerCombinations import classFactory
lc = classFactory(iface)
lc_manager = lc.manager
combinations = lc_manager.combinationsList
composition = iface.activeComposers()[0].composition()
composition_items = composition.items()
for cmb in combinations:
  for item in composition_items:
    if item.type() ==  65641: #this is the type of ComposerMap
      lc_manager.applyCombinationToMap(cmb, item)
  image = composition.printPageAsRaster(0)
  image.save('/home/dr/' + cmb +'.png','png')

Best Answer

To get a list of existing composer windows:

composers = iface.activeComposers()

Then, you need to get a reference to a specific composition:

c = composers[0].composition()

Render the page as an image (0 refers to the page number):

image = c.printPageAsRaster(0)

Save the image to disk (first argument is the filename, second is the format):

image.save('output.png','png')

So, the entire code should look something like this:

c = iface.activeComposers()[0].composition()
image = c.printPageAsRaster(0)
image.save('output.png','png')