My goal is to write a standalone Python script in QGIS 3.10.4 to automate the export of layouts as images. I want it to have the same result as opening a particular project in QGIS, opening a layout in the project, and exporting that layout as an image. It's almost working! But unfortunately I am able to get an image that only has 1 of the 3 layers I want.
What it looks like if I manually export from within the QGIS app:
What the image exported by my code looks like:
In fact, if I run my code in the Python console in the QGIS app, it works (all layers are in the image). This makes me think there may be something else I need to do to force the layers to render before I export. However, the example code illustrating exporting using a print layout in the PyQGIS Developer Cookbook doesn't do anything special that I can see.
My code:
from qgis.core import (
QgsApplication,
QgsLayoutExporter,
QgsProject,
)
# Supply path to qgis install location
QgsApplication.setPrefixPath("/usr", True)
# Create a reference to the QgsApplication. Setting the
# second argument to False disables the GUI.
qgs = QgsApplication([], False)
qgs.initQgis()
project = QgsProject.instance()
project.read("gnss-interference.qgz")
layout_manager = project.layoutManager()
for layout in layout_manager.printLayouts():
exporter = QgsLayoutExporter(layout)
layout_name = layout.name()
export_path = layout_name + ".pdf"
print("Exporting layout {} to {}".format(layout_name, export_path))
exporter.exportToPdf(export_path, QgsLayoutExporter.PdfExportSettings())
# Finally, exitQgis() is called to remove the
# provider and layer registries from memory
qgs.exitQgis()
Adding a few more details about the layers I'm using:
The project CRS is EPSG: 3857, and the map has 2 layers.
The base map is an OpenStreetMap layer:
Property | Value |
---|---|
Name | OpenStreetMap |
Source | crs=EPSG:3857&format&type=xyz&url=https://tile.openstreetmap.org/%7Bz%7D/%7Bx%7D/%7By%7D.png&zmax=19&zmin=0 |
CRS | EPSG:3857 – WGS 84 / Pseudo-Mercator – Projected |
The other layer, the one that doesn't display, is GeoJSON:
Property | Value |
---|---|
Name | interference |
Path | /home/wiseman/src/gnss-interference-map/gnss-interference.json |
Storage | GeoJSON |
Encoding | UTF-8 |
Geometry | Polygon (Polygon) |
CRS | EPSG:4326 – WGS 84 – Geographic |
Unit | degrees |
Feature count | 67,640 |
Best Answer
The solution was to update to QGIS 3.24, which solved the problem.