4

Is there a way to write a print composer to a QGS project file via PyQGIS, so that when the project file is opened later, that print composer is available?

I am able to successfully do the following:

  • load and manipulate a project (load layers, etc)
  • load a print composer template (QPT file) and manipulate the composer elements
  • save the modified QGS file
  • export the print composer map to PDF

However, I can't figure out how to save that print composer to the QGS file.

Essentially that means that if I want to go into the QGS file afterwards and make edits to the map generated from the print composer, I need to load a new print composer from template and redo all the edits from scratch (map title, extents, map notes, etc).

The following code works to load a composer from a QPT template file and export the map as PDF, but does not save the composer with the QGS file:

#initialize QGIS
app = QgsApplication([], True)
app.initQgis()

#set project and template paths
project_path = "/mypath/myproject.qgs"
template_path = "/mypath/mytemplate.qpt"

#get canvas and load project
canvas = QgsMapCanvas()
project = QgsProject.instance()
project.read(QFileInfo(project_path))

#load print composer template
template_file = file(template_path)
template_content = template_file.read()
template_file.close()

document = QDomDocument()
document.setContent(template_content)
composition = QgsComposition(canvas.mapSettings())
composition.loadFromTemplate(document)

#refresh after manipulating composer elements
composition.refreshItems()

#export to PDF and also save a QGS file
composition.exportAsPDF('myfile.pdf')
project.write(QFileInfo('myfile.qgs'))

I believe I must be missing something either in, or prior to, the last line of code:

project.write(QFileInfo('myfile.qgs'))

to add the composer to the QGS file.

0

1 Answer 1

1

QgsLayoutManager handles compositions stored directly in a project rather than as template files

layoutManager=project.layoutManager()

#add a composition
layoutManager.addComposition(composition)

#print composition names
comps=layoutManager.compositions()
for comp in comps:
    print ('Layout: {}'.format(comp.name()))

#load a composition by name
composition=layoutManager.compositionByName('My Composition')

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.