4

I work on QGIS plugin in python, in my plugin I load several print layout in a project print layout manager. These print layouts are either A4 or A3. I would like to get the size value (A4 or A3) of each print layout of my project print layout manager. I tried this code but it only returns the size in millimeters of the page.

project = QgsProject.instance()
composition = QgsPrintLayout(project)
document = QDomDocument()
template_file = open('C:/Users/Thysma/Documents/Stage/Composeurs/A4 Portrait.qpt')
template_content = template_file.read()
template_file.close()
document.setContent(template_content)
composition.loadFromTemplate(document, QgsReadWriteContext()) 
project.layoutManager().addLayout(composition)

layout = project.layoutManager().layoutByName('A4 Portrait')
page_size = layout.pageSize()
print (page_size)

1 Answer 1

7

You can find the page type (if exists) with the following code :

project = QgsProject.instance()
composition = QgsPrintLayout(project)
document = QDomDocument()
template_file = open("C:/Users/Thysma/Documents/Stage/Composeurs/A4 Portrait.qpt")
template_content = template_file.read()
template_file.close()
document.setContent(template_content)
composition.loadFromTemplate(document, QgsReadWriteContext()) 
project.layoutManager().addLayout(composition)

layout = project.layoutManager().layoutByName("A4 Portrait")
layout_pages = layout.pageCollection()
first_layout_page = layout_pages.page(0)

page_size_registry = QgsApplication.pageSizeRegistry()
page_size = page_size_registry.find(first_layout_page.pageSize())

if first_layout_page.orientation() == QgsLayoutItemPage.Portrait:
    page_size += " Portrait"
if first_layout_page.orientation() == QgsLayoutItemPage.Landscape:
    page_size += " Landscape"

print(page_size)

EDIT : orientation added

Your Answer

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

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