3

I am trying to print a pdf map, while using a .qpt template.

I can create a pdf output but I how do I name the created print composer?

Each time I run the tool it creates a new 'Composer 1' then 'Composer 2'... and I need to reference the name of the composer in the print to pdf code for it to work (Composer 14 below).

This is my current code:

import os, sys    
from qgis.core import*    
from PyQt4.QtCore import*    
from qgis.utils import*    
from qgis.gui import*    
import qgis    
from PyQt4.QtXml import*

# Pan to selected feature 
pan_feature = iface.mapCanvas().panToSelected()

#Next Set print composer to map canvas using python:     
canvas = qgis.utils.iface.mapCanvas()
layers = canvas.layers()    
myFile = '/Users/Michael/QGIS_template.qpt'     
myTemplateFile = file(myFile, 'rt')    
myTemplateContent = myTemplateFile.read()    
myTemplateFile.close()    
myDocument=QDomDocument()    
myDocument.setContent(myTemplateContent, False)    
comp = iface.createNewComposer()    
comp.composition().loadFromTemplate(myDocument)    

map_item = comp.composition().getComposerItemById('Map')    
map_item.setMapCanvas(canvas)    
map_item.zoomToExtent(canvas.extent())

# Next Print PDF using the printer plugin:    
composertitle = 'Composer 14'   
folder = '/Users/Michael/Capstone'   
extension = '.pdf'    
mp = qgis.utils.plugins ['MapsPrinter']    
for composer in iface.activeComposers():    
    title = composer.composerWindow().windowTitle()    
    if title == composertitle:    
        mp.exportCompo (composer, folder, title, extension)    
        break

My plugin is useless if the composer Id need to be updated every time I run the tool.

These are the two main Q&As that I used to build my code above:

1
  • As per the Tour there should be only one question asked per question.
    – PolyGeo
    Mar 24, 2017 at 22:33

1 Answer 1

1
comp = iface.createNewComposer('Your composer title here')

This generates a print composer title as shown below:

enter image description here

Your composer name can be user input captured via a UI or a variable from elsewhere in your script.

If you need to remove the composer from the composer manager after exporting the map, you could run this at the end of the script:

for c in iface.activeComposers():
    iface.deleteComposer(c)

This will remove all composers from the manager. This method could be useful if you don't want subsequent runs to fill your composer manager with duplicate entries.

There are a few examples of manipulating items in the composer manager in the thread below:

http://lists.osgeo.org/pipermail/qgis-developer/2013-February/024666.html

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.