Skip to content

Instantly share code, notes, and snippets.

@NathanW2
Created November 7, 2012 03:21
Show Gist options
  • Save NathanW2/4029400 to your computer and use it in GitHub Desktop.
Save NathanW2/4029400 to your computer and use it in GitHub Desktop.
Print composer
from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import *
from PyQt4.QtGui import QApplication
from PyQt4.QtXml import *
import sys
import xml.etree.ElementTree as ET
app = QgsApplication([], True)
QgsApplication.setPrefixPath("C:/OSGeo4w/apps/qgis-dev", True)
QgsApplication.initQgis()
project = "composer.qgs"
template = "template.qpt"
QgsProject.instance().setFileName(project)
QgsProject.instance().read()
doc = QDomDocument()
doc.setContent(QFile(project), False)
templateDOM = QDomDocument()
templateDOM.setContent(QFile(template), False)
layers = doc.elementsByTagName("maplayer")
layerset = []
for x in xrange(layers.count()):
layerDOM = layers.at(x)
layer = QgsVectorLayer()
layer.readXML(layerDOM)
QgsMapLayerRegistry.instance().addMapLayer(layer)
layerset.append(layer.id())
newlayers = []
for layer in reversed(layerset):
newlayers.append(layer)
myMapRenderer = QgsMapRenderer()
mLBL = QgsPalLabeling()
myMapRenderer.setLabelingEngine(mLBL)
myMapRenderer.setLayerSet(newlayers)
myMapRenderer.setProjectionsEnabled(False)
comp = QgsComposition(myMapRenderer)
comp.loadFromTemplate(templateDOM,{'Name':"Water", 'Tag':'FooBar'})
comp.exportAsPDF("composer.pdf")
QgsApplication.exitQgis()
@rdenham
Copy link

rdenham commented Sep 18, 2015

just in case anyone comes across this again, I think now you will probably have to use:

layer.readlayerXML(layerDOM.toElement()) 

in line 32.

Also might be wise to check that the layer in the project is a vector, not a raster.
Something like:

nodeAttributes = layerDOM.attributes()
thisatt = nodeAttributes.namedItem('type')

and check if thisatt.nodeValue is raster or vector.

@ponceta
Copy link

ponceta commented May 6, 2019

Hi @NathanW2,

Do you have an updated version of this on QGIS 3.X?

I'm trying to launch an Automated Maps creation from the commandline and my google searches ended here.

Best wishes!

Arnaud

@haubourg
Copy link

haubourg commented May 6, 2019

@ponceta this is a perfect use case for QGIS server IMO

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment