Friday, 28 October 2016

pyqgis - Programmatically exporting composition as image from QGIS?


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')

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')

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...