Advertisements

A common topic for automation is exporting print layouts (formerly known as print compositions). This example shows you how to export a print layout to PDF. This code can be easily adapted to export to image or SVG as well.

We already used the QgsProject object in the previous example to add Processing results to our project. Now, we use the QgsProject to access the corresponding QgsLayoutManager which takes care of managing all configured layouts in a project.

If we open a project that has a print layout configured and run the following two lines of code in the Python console:

manager = QgsProject.instance().layoutManager()
print(manager.printLayouts())

we get a list of QgsPrintLayout objects. If the project has just one layout, the list will only contain one item, like this:

[<qgis._core.QgsPrintLayout object at 0x000001D288C020D8>]

Of course, we can also print out the names of the layouts in our project using our favorite loop, the for loop:

for layout in manager.printLayouts():
    print(layout.name())

These names can be used to access specific layouts. So, for example, to get the layout named “my_layout”, we use the layoutByName() function:

layout = manager.layoutByName("my_layout")

So far so good! Now there’s just one issue: layout objects do not have an export function! Instead, the documentation of QgsLayout (which is the base class of QgsPrintLayout*) tells us:

While the raw QGraphicsScene API can be used to render the contents of a QgsLayout to a QPainter, it is recommended to instead use a QgsLayoutExporter to handle rendering layouts instead.

So to export our layout, we need a QgsLayoutExporter. These exporters can export to image, SVG, and PDF. To create an exporter for our layout object, we use:

exporter = QgsLayoutExporter(layout)

Finally, we can export the layout, for example, to PDF:

exporter.exportToPdf("C:/temp/layout.pdf",QgsLayoutExporter.PdfExportSettings())

* Before we wrap up this example, there was this notion of QgsLayout being the base class of QgsPrintLayout or conversely, as stated in the QgsPrintLayout  documentation:

Print layout [is] a QgsLayout subclass for static or atlas-based layouts.

A class is like a “blueprint” for creating objects. The class defines which attributes and functions an object has. In this example, our layout is a QgsPrintLayout object. It therefore has all the functions and attributes defined by the QgsLayout class, as well as the QgsPrintLayout class. This concept is called inheritance and you can read more about it, for example, at python-course.eu.

These are the basics of exporting map layouts to PDF. You also saw an example of inheritance with QgsLayout as the base class and QgsPrintLayout as the subclass.


PyQGIS 101 is a work in progress. I’d appreciate any feedback, particularly from beginners!

Advertisements
%d bloggers like this: