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


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.

  • 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 9, 2018 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 9, 2018 at 15:18

1 Answer 1


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

  • 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? Dec 19, 2018 at 19:32
  • 1
    What do you mean with "it does not work for me"? Do you get an error message?
    – Blinxen
    Dec 20, 2018 at 10:36
  • I restarted QGIS and now the script works. I think that happens from time to time. Dec 20, 2018 at 14:51

Your Answer

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

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