For each new QGIS project, I want to add a few layouts from prepared templates.
All templates are vertically oriented (A4 portrait). Inspecting the templates (the XML contents), I can see a <LayoutItem>
with a proper size="210,297,mm"
, as in this example:
<LayoutItem positionLock="false" zValue="0" frame="false" referencePoint="0" itemRotation="0" id="" size="210,297,mm" outlineWidthM="0.3,mm" positionOnPage="0,0,mm" position="0,0,mm" visibility="1" type="65638" frameJoinStyle="miter" opacity="1" background="true" blendMode="0" uuid="{3156912c-ce6e-4d02-8dfc-bc7c36b8f738}" templateUuid="{3156912c-ce6e-4d02-8dfc-bc7c36b8f738}" groupUuid="" excludeFromExports="0">
Adding templates manually
If I add the templates using the GUI, it works. The template is added and I get a new layout, with the correct page orientation, as expected.
Adding templates with PyQGIS
Since I want to add a few templates, I would like to add them using PyQGIS.
The minimal code is this:
project = QgsProject.instance()
layout = QgsPrintLayout(project)
layout.initializeDefaults()
with open('/home/jgr/Templates/reserva.qpt') as f:
template_content = f.read()
doc = QDomDocument()
doc.setContent(template_content)
items, ok = layout.loadFromTemplate(doc, QgsReadWriteContext(), False)
layout.setName('reserva')
project.layoutManager().addLayout(layout)
The layout is created without the proper orientation. The generated layout from the templates is horizontally oriented, but the template is vertically oriented.
What am I missing in this PyQGIS script?