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.
2 Comments
Why does this code not produce a map but only the legend?
from qgis.core import *
from PyQt4 import QtGui
from qgis.core import *
from qgis.gui import *
from qgis.utils import iface
from qgis.core import *
from PyQt4.QtXml import QDomDocument
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import pyodbc
import os
import sys
import socket
import csv
import processing
systemName = socket.gethostname()
SQLName = ‘ba-rmsdb-nc’
dataBaseName = ‘RMS_NBIC_2016_EDM’
connectString = ‘DRIVER={2}; SERVER=ba-rmsdb-nc; DATABASE={1};Trusted_Connection=yes’.format(systemName, dataBaseName, ‘{SQL Server}’, SQLName)
conn = pyodbc.connect(connectString)
curs = conn.cursor()
selectSQL = ”’ select countycode, county, STATE, COUNTRY, sum(VALUEAMT) as TIV,
lower(state)+’_’+countycode as state_coun
from Loc
join loccvg on loc.locid=loccvg.locid
group by countycode, county, STATE, COUNTRY
”’
selectQ = curs.execute(selectSQL)
headers = [column[0] for column in curs.description]
records = selectQ.fetchall()
csvpath = ‘O:/Broker Support/Cat Modeling/ArcGIS/’
f = open(csvpath + ‘NBIC_TIV_County1.csv’, ‘wb’)
wrtr = csv.writer(f)
wrtr.writerow(headers)
for row in records:
wrtr.writerow(row)
f.close()
county_uri = ‘O:/Broker Support/Cat Modeling/QGIS/Shapefiles/US Counties/UScounties.shp’
shp = QgsVectorLayer(county_uri, ‘UScounties’, ‘ogr’)
QgsMapLayerRegistry.instance().addMapLayer(shp)
csv_uri = “file:///O:/Broker Support/Cat Modeling/ArcGIS/NBIC_TIV_County1.csv?delimeter=,”
csv = QgsVectorLayer(csv_uri, “NBIC_TIV_County1”, “delimitedtext”)
QgsMapLayerRegistry.instance().addMapLayer(csv)
shpField=’state_coun’
csvField=’state_coun’
joinObject = QgsVectorJoinInfo()
joinObject.joinLayerId = csv.id()
joinObject.joinFieldName = csvField
joinObject.targetFieldName = shpField
joinObject.memoryCache = True
shp.addJoin(joinObject)
True
colorRamp = QgsVectorGradientColorRampV2.create({‘color1′:’188,255,255,255’, ‘color2′:’0,0,128,255′,’stops’:’0.25;176,196,222,255:0.50;70,130,180,255:0.75;65,105,225,255′})
#
#shpField = ‘state_coun’
#csvField = ‘state_coun’
#JoinedMap = processing.runandload(‘qgis:joinattributestable’, shp, csv, shpField, csvField, None)
renderer = QgsGraduatedSymbolRendererV2.createRenderer(shp, ‘NBIC_TIV_County1_TIV’, 6, QgsGraduatedSymbolRendererV2.Jenks, QgsSymbolV2.defaultSymbol( shp.geometryType() ), colorRamp )
shp.setRendererV2( renderer )
QgsMapLayerRegistry.instance().addMapLayer(shp)
qgis.utils.iface.activeLayer()
#zooms to layer
qgis.utils.iface.actionZoomToLayer().trigger()
def savePDF():
mapRenderer = iface.mapCanvas().mapRenderer()
c = QgsComposition(mapRenderer)
c.setPlotStyle(QgsComposition.Print)
x, y = 0, 0
w, h = c.paperWidth(), c.paperHeight()
composerMap = QgsComposerMap(c, x ,y, w, h)
rect = iface.mapCanvas().currentLayer().extent()
composerMap.setNewExtent(rect)
print composerMap.currentMapExtent()
c.addItem(composerMap)
legend = QgsComposerLegend(c)
legend.model().setLayerSet(mapRenderer.layerSet())
c.addItem(legend)
outpath = “\\\\ba-fs-nc\\data\\Broker Support\\Cat Modeling\\QGIS\\NBIC_2.pdf”
printer = QPrinter()
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName(outpath)
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()
QTimer.singleShot(3000, savePDF)
ignore the first part as I am just pulling data from SQL to use for my CSV