Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python code to get print layout extents as a layer in qgis map
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
You can’t perform that action at this time.