Created
November 7, 2012 03:21
-
-
Save NathanW2/4029400 to your computer and use it in GitHub Desktop.
Print composer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
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.
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
@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
Hiya - I've been trying to use a modified version of this script to load and print some layers according to a QGIS composer I have. The problem is the layer.readXML(layerDOM) line isn't producing valid layers, even though my project XML file seems to have been found ok. Any tips/tricks here?