QGIS PyQGIS – Setting Print Layout Page Size in Python Console in QGIS

pyqgispyqgis-3pythonqgis

I would like to set the page size of my print layout in QGIS through the python console.

You can see what I tried in the # SET PAGE SIZE HERE section at the end of the code. I either get an error or nothing happens. layout.addLayoutItem(page) adds a page of a given size but then I have two pages rather than just one of the correct size.

#for i in range(0,len(targ)):
for i in (1,2):# Testing
    
    # Load Raster File
    fn = "/".join([fldr, targ[i]])
    fi = QFileInfo(fn)
    fname = fi.baseName()
    rlayer = iface.addRasterLayer(fn, fname)
    
    renderer = QgsSingleBandPseudoColorRenderer(rlayer.dataProvider(), 1, shader)
    rlayer.setRenderer(renderer)
    
    # Create and Export Print Layout
    # Identify Layer for Map
    layers = QgsProject.instance().mapLayersByName(fname)
    layer = layers[0]
    project = QgsProject.instance()
    manager = project.layoutManager()
    layoutName = " ".join(['Temp Pred Maps', str(i)])
    layouts_list = manager.printLayouts()
    
    # Remove any duplicate layouts
    for i in layouts_list:
        if i.name() == layoutName:
            manager.removeLayout(i)
    
    # Add add layout to QGIS
    layout = QgsPrintLayout(project)
    layout.initializeDefaults()
    layout.setName(layoutName)
    manager.addLayout(layout)
    
    # SET PAGE SIZE HERE
    #*** HOW TO SET PAGE SIZE? ***
    page = QgsLayoutItemPage(layout)
    page_size = QgsLayoutSize(200, 200, QgsUnitTypes.LayoutMillimeters)
    #page.QgsPageSize(page_size.size) # Error
    page.attemptResize(page_size) # Does Nothing???
    #layout.addLayoutItem(page) # Adds second page
    #layout.removeLayoutItem(layout)

Best Answer

Rather than making and adding a new page, you can find the existing page like this:

# iterate through layout items and check for a QgsLayoutItemPage
for i,x in enumerate(layout.items()):
    if isinstance(x, QgsLayoutItemPage):
        # print index of page
        print(i,x)

# print out
> 9 <qgis._core.QgsLayoutItemPage object at 0x0000020AD43BDCA0>

Then you can adjust the size of this page:

page = layout.items()[9]
page_size = QgsLayoutSize(200, 200, QgsUnitTypes.LayoutMillimeters)
page.setPageSize(page_size)