Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mdouchin/6d7408980f737959075b to your computer and use it in GitHub Desktop.
Save mdouchin/6d7408980f737959075b to your computer and use it in GitHub Desktop.
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
c = QgsComposition(QgsMapSettings())
c.setPaperSize(290, 210)
c.setPrintResolution(100)
c.setSnapGridOffsetX(3.5)
c.setSnapGridOffsetY(0)
c.setSnapGridResolution(2.5)
c.setNumPages(1)
cl = QgsComposerLabel(c)
cl.setItemPosition(0, 10, 100, 100)
content = 'test'
cl.setText(content)
cl.setFrameEnabled(False)
c.addItem(cl)
method2(c)
def method0(c):
c.exportAsPDF('/tmp/test.pdf')
def method1(c):
printer = QPrinter()
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName("/tmp/out.pdf")
printer.setPaperSize(QSizeF(c.paperWidth(), c.paperHeight()), QPrinter.Millimeter)
printer.setFullPage(True)
printer.setColorMode(QPrinter.Color)
printer.setResolution(c.printResolution())
pdfPainter = QPainter(printer)
paperRectMM = printer.pageRect(QPrinter.Millimeter)
paperRectPixel = printer.pageRect(QPrinter.DevicePixel)
c.render(pdfPainter, paperRectPixel, paperRectMM)
pdfPainter.end()
def method2(c):
dpi = c.printResolution()
dpmm = dpi / 25.4
width = int(dpmm * c.paperWidth())
height = int(dpmm * c.paperHeight())
# create output image and initialize it
image = QImage(QSize(width, height), QImage.Format_ARGB32)
image.setDotsPerMeterX(dpmm * 1000)
image.setDotsPerMeterY(dpmm * 1000)
image.fill(0)
# render the composition
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("/tmp/out.png", "png")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment