I am interested in making reproducible PDF figures in QGIS3, and therefore want to work from the console/PyQGIS.
Using some previous helpful advice from PDF Output with Python the problem is successfully reduced to setting up the QgsPrintLayout. I am not sure how to do this, below is my best attempt so far:
#setup the background classes for managing the project
canvas =iface.mapCanvas()
manager = project.layoutManager()
#new layout
layout = QgsPrintLayout(project)
layout.initializeDefaults()
layout.setName('console')
itemMap = QgsLayoutItemMap(layout)
itemMap.setExtent(canvas.extent())
layout.addLayoutItem(itemMap)
#add the layout to the manager
manager.addLayout(layout)
The "console" layout is successfully added to QGIS 3 and I can open it to see if the content is satisfactory. The map does not render and its extent is nan,nan,nan,nan.
How do I setup the extent and size of the map object in the layout?
SOLVED. The following code produces a map without issues.
#get a reference to the layout manager
manager = project.layoutManager()
#make a new print layout object
layout = QgsPrintLayout(project)
#needs to call this according to API documentaiton
layout.initializeDefaults()
#cosmetic
layout.setName('console')
#add layout to manager
manager.addLayout(layout)
#create a map item to add
itemMap = QgsLayoutItemMap.create(layout)
#using ndawson's answer below, do this before setting extent
itemMap.attemptResize(QgsLayoutSize(6,4, QgsUnitTypes.LayoutInches))
#set an extent
itemMap.setExtent(canvas.extent())
#add the map to the layout
layout.addLayoutItem(itemMap)
initializeDefaults()
is required, but try this example without it: gis.stackexchange.com/a/309551/75563 I found that not only is the PDF way off, but QGIS crashed as well when pressingExport to PDF ...