I would like to automate two steps in my QGIS Print Layout by using PyQGIS
I have my print layout already created, and I was trying to open it by this code:
composerTitle = 'Strand3' project = QgsProject.instance() projectLayoutManager = project.layoutManager() layout = projectLayoutManager.layoutByName(composerTitle)
which comes from this query:
The code didn't work as I wanted. I just wanted to load my print layout called "Strand3" from the layout manager. However is not as important as the stuff below, because I can load it once manually and keep it open.
Next, I would like to do an automatic Set Map Extent to Match Main Canvas Extent.
I found some solution here:
- Setting the extent for a QGIS map using python
- Set print composer to map canvas extent using python
- Map extent matching permanently main canvas extent
but it doesn't work, as they propose the definition of map rectangle. I simply need my map refreshed, what was considered here:
I would like to have this step done automatically as well as the last one - exporting map to PNG.
Since I've managed with setting the fixed DPI resolution for the map, I want to skip the window below:
I found the code like this:
.exportToImage(fn, QgsLayoutExporter.ImageExportSettings()) exporter.exportToPdf(fn, QgsLayoutExporter.PdfExportSettings())
and solution like this:
but I don't know how to implement Qgis Layout Exporter.
Anyway my final code looks like this:
comp = iface.createNewComposer() comp.composition().loadFromTemplate(myDocument) map_item = comp.composition().getComposerItemById('Strand3') map_item.setMapCanvas(canvas) map_item.zoomToExtent(canvas.extent()) base_path = os.path.join(QgsProject.instance().homePath()) png_path = os.path.join(base_path, ".png") exporter = QgsLayoutExporter(layout) exporter.exportToPdf(png_path, QgsLayoutExporter.ImageExportSettings())
and I am getting an error:
'QgisInterface' object has no attribute 'createNewComposer'.
How can I automate these 2 things in my QGIS print layout?