Last active
February 16, 2019 11:26
-
-
Save datagistips/5a16e7b1c6fa18bb780ad04d954a60bd to your computer and use it in GitHub Desktop.
Python code to get print layout extents as a layer in qgis map
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
def getCompositionExtents(crsCode=2154) : | |
# layer | |
vl = QgsVectorLayer("Polygon?crs=EPSG:%s"%(crsCode), "Extent Polygons", "memory") | |
# defining CRS | |
crs = vl.crs() | |
crs.createFromId(crsCode) | |
vl.setCrs(crs) | |
# data provider | |
pr = vl.dataProvider() | |
# start editing | |
vl.startEditing() | |
# add attributes | |
vl.addAttribute(QgsField("name", QVariant.String)) | |
# get compositions | |
projectInstance= QgsProject.instance() | |
projectLayoutManager = projectInstance.layoutManager() | |
comps = projectLayoutManager.printLayouts() | |
# iterate over compositions | |
feats = list() | |
for comp in comps : | |
nom = comp.name() | |
print(nom) | |
for item in comp.items() : | |
if (isinstance(item, QgsLayoutItemMap)) : | |
print("toto") | |
print(item) | |
e = item.extent() | |
feat = QgsFeature() | |
feat.setGeometry(QgsGeometry.fromRect(e)) | |
feat.initAttributes(1) | |
feat.setAttribute(0, QVariant(nom)) | |
feats.append(feat) | |
# add features | |
pr.addFeatures(feats) | |
# commit changes | |
vl.commitChanges() | |
return(vl) | |
def addLayerToCanvas(vl) : | |
# add layer to canvas | |
QgsProject.instance().addMapLayer(vl, False) | |
layerTree = iface.layerTreeCanvasBridge().rootGroup() | |
layerTree.insertChildNode(-1, QgsLayerTreeLayer(vl)) | |
vl = getCompositionExtents() # create layer from extents | |
addLayerToCanvas(vl) # add layer to canvas | |
#writer = QgsVectorFileWriter( "output_path_and_name.shp", vl.encoding(), vl.fields(), QGis.WKBPolygon, vl.crs() ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment