PyQGIS

Tips and tricks, and lots of code scraps for using with Python and Quantum GIS.

Code Scrap for Exporting a QGIS Composer to a Vector PDF

This is the traditional method of Python Scripting to export a QGIS Composer as an Adobe Acrobat PDF file. This produces a vector PDF file regardless of your setting under “Print as a Raster”. This provides the highest quality print output, but may cause incorrect rendering if you use effects like multiply layers. Tomorrow I will post code I use for making PDFs, using compressed (but high resolution) Raster JPEG files embedded in the PDF files.

It’s possible you won’t need to import as many classes as I did. I just didn’t carefully go through the list to remove classes that are unnecessary (as they are neccessary for my plugin code). You will need to adjust the output file name and the window title for the Composer to whatever you named your Composer as. Remember if you use this in a plugin class, to make iface to self.iface or this code won’t work. Stupid stuff like that will trip you up.

from PyQt4.QtCore import QSettings, QTranslator, qVersion, QCoreApplication,QFileInfo,QSizeF
from PyQt4.QtGui import QAction, QIcon, QPrinter,QPainter

composerId = 0
composers = iface.activeComposers()
for item in composers:
	if item.composerWindow().windowTitle() == 'Horizontal':
		break
	composerId += 1

c = composers[composerId].composition()

image = c.printPageAsRaster(True, QSize(),c.printResolution())

printer = QPrinter()
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName("/tmp/"+QgsProject.instance().title()+".pdf")
printer.setPaperSize(QSizeF(c.paperWidth(), c.paperHeight()), QPrinter.Millimeter)
printer.setFullPage(True)
printer.setColorMode(QPrinter.Color)
printer.setResolution(c.printResolution())

pdfPainter = QPainter(printer)
c.renderPage(pdfPainter,0)
pdfPainter.end()

I hope this is helpful. I’m not a real PyQGIS pro, but if you have ideas or comments, please add them below.

Rensslear Plateau

I had trouble finding a clear example online of how to export a composer file as a Vector Adobe Acrobat PDF you have loaded in Quantum GIS via a Python plugin or script. This code that I put together does the trick.