1

I have been developing this code, based on the official documentation of QGIS and some codes in gis.stackexchange. But my problem is that I don't know where to establish my height and width to make a A4 size.. I am using the Text Editor of QGIS, version 2.14 (QgsComposition using the constructor with mapRenderer has been working before)

from qgis.core import *
from qgis.utils import iface
from PyQt4.QtGui import QColor
from PyQt4 import Qt

municipios = QgsVectorLayer("MyLayer\\MUNICIPIOS.shp","Municipios","ogr")
l = QgsMapLayerRegistry.instance().addMapLayer(municipios)

el_renderer = iface.mapCanvas().mapRenderer()
composition = QgsComposition(el_renderer) 
composition.setPlotStyle(QgsComposition.Print)

lst = [municipios.id()]  # add ID of every layer
el_renderer.setLayerSet(lst)
el_renderer.setOutputSize(QSize(composition.paperWidth(), composition.paperHeight()), composition.printResolution())

x, y = 0,0
w, h = composition.paperWidth(), composition.paperHeight()
composer_map = QgsComposerMap(composition, x ,y, w, h)
composer_map.setNewExtent(el_renderer.extent())
composition.addComposerMap(composer_map)
composition.addItem(composer_map)

print "\n QgsComposerMap funciona"

printer = QPrinter()
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName("C:\\output\\my_pdf.pdf")
printer.setPaperSize(QSizeF(composition.paperWidth(), composition.paperHeight()), QPrinter.Millimeter)
printer.setFullPage(True)
printer.setColorMode(QPrinter.Color)
printer.setResolution(composition.printResolution())

pdfPainter = QPainter(printer)
paperRectMM = printer.pageRect(QPrinter.Millimeter)
paperRectPixel = printer.pageRect(QPrinter.DevicePixel)
composition.render(pdfPainter, paperRectPixel, paperRectMM)
pdfPainter.end()


print "\n se ha exportado a PDF"
0

Perhaps there is a solution to this on qtcentre.org: http://www.qtcentre.org/threads/32665-How-do-I-set-a-custom-page-paper-size-in-QPrinter (which can be easily ported to python)

I think this is set up in the code line

printer.setPaperSize(QSizeF(210,297), QPrinter.Millimeter)
  • Thank you. Now I have a problem, when I type in my_canvas = iface.mapCanvas() and then my_canvas.size(), returns a size that doesn't fix my paper. But now I can't find a size according to A4 (my map is shown unplaced) Thank you – user64823 Apr 29 '16 at 7:27
1

Use QgsComposition.setPaperSize( width, height ). See https://qgis.org/api/classQgsComposition.html#a512d7c89fa0e76abb13b5395fae57069

  • That was I tried to carry out, but I don't know which previous method was "overlaping" this one. The answer below makes this more understandeable. – user64823 Apr 29 '16 at 7:21

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.