Skip to main content
1 of 2
ia200
  • 367
  • 1
  • 10

How do I set the print layout page size in Python consol in QGIS?

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)
ia200
  • 367
  • 1
  • 10