3

I am writing a qgis layout script to export my results in a pdf. I am using the tutorial provided here but this tutorial do not teach how to turn the page orientation from landscape to portrait.

my code is like this, it works but creates with a landscape orientation

import os

p = QgsProject()
layout = QgsLayout(p)
layout.initializeDefaults()

# create a map and stretch it over the whole paper size
map = QgsLayoutItemMap(layout)
layout.addItem(map)

# picture
pic = QgsLayoutItemPicture(layout)
pic.setPicturePath("C:\\Users\\c.png")
pic.setLinkedMap(map)
pic.attemptMove(QgsLayoutPoint(1.4, 1.8, QgsUnitTypes.LayoutCentimeters))
pic.attemptResize(QgsLayoutSize(10, 10, QgsUnitTypes.LayoutCentimeters))
layout.addItem(pic)


# label
label = QgsLayoutItemLabel(layout)
label.setText("hello")
label.adjustSizeToText()
label.attemptMove(QgsLayoutPoint(15, 1, QgsUnitTypes.LayoutCentimeters))
layout.addItem(label)


# export the pdf
pdf_path = os.path.join(QgsProject.instance().homePath(), "output.pdf")
exporter = QgsLayoutExporter(layout)
exporter.exportToPdf(pdf_path, QgsLayoutExporter.PdfExportSettings())

How can i change the pages to portrait orientation. And how can i add new pages?

2

I finally figured it out. Open python console in QGis, click show editor to open a new script and execute this script.

# create layout
p = QgsProject()
layout = QgsLayout(p)
layout.initializeDefaults()

# change first page orientation to portrait
pc = layout.pageCollection()
pc.page(0).setPageSize('A4', QgsLayoutItemPage.Orientation.Portrait)

# insert new landscape page
page = QgsLayoutItemPage(layout)
page.setPageSize('A4', QgsLayoutItemPage.Orientation.Landscape)
layout.pageCollection().addPage(page)

# export the pdf
pdf_path = "C:\\Users\\output.pdf"
exporter = QgsLayoutExporter(layout)
exporter.exportToPdf(pdf_path, QgsLayoutExporter.PdfExportSettings())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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