6

I am trying to automate the printing of maps based on different attribute classifications using Python in QGIS. Everything is okay except for when I open the printed image, the labels are blurry. Manually, I can fix this problem by clicking the "Refresh View" button in the print composer window, but I cannot find the right way to automatically refresh the map in the print composer based on the QGIS API. Here is printing part of this code:

def printMyMap(canvas, field, itemp):
    canvas.refresh()
    mapRenderer = canvas.mapRenderer()
    c = QgsComposition(mapRenderer)
    myFile = 'C:/Users/User1/'+itemp
    myTemplateFile = file(myFile, 'rt')
    myTemplateContent = myTemplateFile.read()
    myTemplateFile.close()
    myDocument = QDomDocument()
    myDocument.setContent(myTemplateContent)
    c.loadFromTemplate(myDocument)

    #Map
    cmaps =  c.composerMapItems()
    cmaps[0].updateCachedImage()
    cmaps[1].updateCachedImage()

    #Legend Titles
    #legend = c.getComposerItemById("3")
    #legend.setTitle(ltitle)

    #Show Composer
    #iface.actionPrintComposer().trigger()
    composerList=iface.activeComposers()
    composerView=composerList[composerList.index(max(composerList))]
    composer = composerView.composerWindow()
    composer.show()

    #Save out
    dpi = c.printResolution()
    dpmm = dpi / 25.4
    width = int(dpmm * c.paperWidth())
    height = int(dpmm * c.paperHeight())

    image = QImage(QSize(width, height), QImage.Format_ARGB32)
    image.setDotsPerMeterX(dpmm * 1000)
    image.setDotsPerMeterY(dpmm * 1000)
    image.fill(0)

    imagePainter = QPainter(image)
    sourceArea = QRectF(0, 0, c.paperWidth(), c.paperHeight())
    targetArea = QRectF(0, 0, width, height)
    c.render(imagePainter, targetArea, sourceArea)
    imagePainter.end()
    image.save("F:/Maps/"+field+".png", "png")

1 Answer 1

2

You're very close - you need to change:

sourceArea = QRectF(0, 0, c.paperWidth(), c.paperHeight())
targetArea = QRectF(0, 0, width, height)
c.render(imagePainter, targetArea, sourceArea)

to

c.renderPage( imagePainter, 0 )

As the renderPage method automatically handles a lot of output setup.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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