6

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.

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
lobgoblin
  • 113
  • 1
  • 7
  • 1
    There's nothing for PDFs that references mapCanvas, but if you use the QgsLayout and QgsLayoutExporter classes, you should be able to add the legend and call exportToPdf. – jcarlson Mar 09 '18 at 15:12
  • Thanks. I guess my next question then is how to use the QgsLayout class. In particular, how do I transform what's on the mapCanvas into the layout that I can export? – lobgoblin Mar 09 '18 at 15:18

1 Answers1

6

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

Blinxen
  • 703
  • 5
  • 22
  • I've tried using this to export a map layout, but it does not work for me. My "filename" is a path to my desktop. I'm saving it as a .jpg file. Is this exactly the code you use to export a Print Layout? – Erich Purpur Dec 19 '18 at 19:32
  • 1
    What do you mean with "it does not work for me"? Do you get an error message? – Blinxen Dec 20 '18 at 10:36
  • I restarted QGIS and now the script works. I think that happens from time to time. – Erich Purpur Dec 20 '18 at 14:51