[GIS] Writing PDF Output with PyQGIS

pdfpyqgisqgis-3

I am trying to port some code from an older version of QGIS. I have managed to get the map setup fairly to my liking, and can export some content via a command like

iface.mapCanvas().saveAsImage("example.png")

However, I want to export to PDF, and also add a legend for my graduated color scale. I've been rummaging around the documentation online for some time but I can't figure out how these new classes work together.

@JoshC helped me to understand that I need to use the QgsLayout and QgsLayoutExporter classes, not mapCanvas, however I'm not clear on how to use those classes to get out a PDF with a legend.

Best Answer

Here is a small example of how you could use it:

projectInstance = QgsProject.instance()
layoutmanager = projectInstance.layoutManager()
layout_item = layoutmanager.layoutByName("test")  # test is the layout name
export = QgsLayoutExporter(layout_item)
export.exportToImage(filename, QgsLayoutExporter.ImageExportSettings())

layout_item is the reference to your QgsLayout. Hope it helps

Related Question