1

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:

enter image description here

What the image exported by my code looks like:

enter image description here

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

2 Answers 2

1

The solution was to update to QGIS 3.24, which solved the problem.

0

This plugin will help you export layouts (python API supported):

https://delazj.github.io/MapsPrinter/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.