Code Scrap for Exporting a Map to a Raster PDF

I don’t like the vector Adobe Acrobat PDF that Quantum GIS exports by default if you don’t specifically check “Export as Raster” in the Composer View. It’s true that Vector PDF is a higher quality, but the files are much larger and slower loading. A 300 DPI raster PDF file will suffice for most printing needs.

I struggled for a number of days to figure out the best way to export a Raster PDF from Quantum GIS with PyQGIS. I ended up giving up, preferring to just export a high-resolution JPEG and convert the JPEG to a Adobe PDF using ImageMagick’s convert command. It gave me much smaller PDF files due to higher compression then what you get through the PDF export built into QGIS’s Composers with the “Export as Raster” checked.

When you use printPageAsRaster(0), all settings related to resolution are preserved in the exported file (such as 300 DPI format and 8×10 page size), so ImageMagick automatically converts it over.

You don’t have to include all the libraries that are listed below, I was lazy, and I needed all of them for my map automation plugin, so I left them in. You should remove the ones you don’t use. Don’t forget to change the composer name from Horizontal to the composer you use, and adjust the output paths accordingly.

It may not be elegant, but it works well. This is my solution, it may not be yours.

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

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

c = composers[composerId].composition()

image = c.printPageAsRaster(0)
image.save("/tmp/"+QgsProject.instance().title()+".jpg", "jpg")
os.system('convert "/tmp/'+QgsProject.instance().title()+'.jpg" "/tmp/'+QgsProject.instance().title()+'.pdf"')

Evening Down in the Ravine

Leave a Reply

Your email address will not be published. Required fields are marked *