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:
to add the composer to the QGS file.