1

I try to follow this example to create a map using PyQGIS in standalone script. But in my case I don't have vector layer but I have raster layer.

Here the code :

qgs = QgsApplication([], True)
QgsApplication.setPrefixPath("/", True)
QgsApplication.initQgis()
project_path = 'single_pdf.qgs'
canvas = QgsMapCanvas()
template_path = 'single_pdf_a4_landscape.qpt'
QgsProject.instance().read(QFileInfo(project_path))
template_file = file(template_path)
template_content = template_file.read()
template_file.close()
document = QDomDocument()
document.setContent(template_content)
composition = QgsComposition(canvas.mapSettings())
substitution_map = {'title': 'hi'}
raster='raster.tif'
fileInfo = QFileInfo(raster)
path = fileInfo.filePath()
baseName = fileInfo.baseName()
layer = QgsRasterLayer(path, baseName)
QgsMapLayerRegistry.instance().addMapLayer(layer)

composition.loadFromTemplate(document, substitution_map)
# You must set the id in the template
map_item = composition.getComposerItemById('Main Map')

layer.loadNamedStyle('NEW.qml')
map_item.setMapCanvas(canvas)
map_item.zoomToExtent(canvas.extent())

legend_item = composition.getComposerItemById('Legend')
legend_item.updateLegend()
composition.refreshItems()
composition.exportAsPDF('export.pdf')
QgsProject.instance().clear()

Legend work fine take legend from style, title work fine but the Main Map where I want to add my raster layer is empty, any idea why? Where I have the wrong in code? The problem is extent or some refresh?

  • 2
    Your code looks fine. Perhaps you are not giving enough time for the map to be rendered in the canvas? This was a problem for me which was solved using the time.sleep() method. You can import it using from time import sleep and then before the line composition.exportAsPDF('export.pdf'), you can add sleep(5) or however long you want just so there's time for the items to be refreshed before being exported to the pdf. Five seconds works for me :) – Joseph Jun 14 '18 at 11:20

Your Answer

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

Browse other questions tagged or ask your own question.