-
Notifications
You must be signed in to change notification settings - Fork 5
/
create_print_layout_and_export_map.py
305 lines (246 loc) · 13 KB
/
create_print_layout_and_export_map.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# -*- coding: utf-8 -*-
"""
/***************************************************************************
EcoValuator
A QGIS plugin
Calculate ecosystem service values for a given area
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2018-04-02
copyright : (C) 2018 by Key-Log Economics
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
__author__ = 'Key-Log Economics'
__date__ = '2018-04-02'
__copyright__ = '(C) 2018 by Key-Log Economics'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import os
import csv
import processing
import numpy
from PyQt5.QtGui import *
from qgis.core import (QgsProcessing,
QgsProcessingAlgorithm,
QgsProcessingParameterString,
QgsProcessingParameterFileDestination,
QgsProcessingParameterEnum,
QgsProcessingOutputLayerDefinition,
QgsRasterLayer,
QgsProject,
QgsPrintLayout,
QgsLayoutItemMap,
QgsUnitTypes,
QgsLayoutPoint,
QgsLayoutSize,
QgsLayoutItemLegend,
QgsLayoutItemLabel,
QgsLayerTree,
QgsRasterBandStats,
QgsLayoutExporter,
QgsColorRampShader,
QgsRasterShader,
QgsSingleBandPseudoColorRenderer
)
from qgis.utils import *
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
class CreatePrintLayoutAndExportMap(QgsProcessingAlgorithm):
# Constants used to refer to parameters and outputs. They will be
# used when calling the algorithm from another algorithm, or when
# calling from the QGIS console.
INPUT_VECTOR = 'INPUT_VECTOR'
INPUT_TITLE = 'INPUT_TITLE'
INPUT_SUBTITLE = 'INPUT_SUBTITLE'
INPUT_CREDIT_TEXT = 'INPUT_CREDIT_TEXT'
OUTPUT_PDF_PATH = 'OUTPUT_PDF_PATH'
OUTPUT_PDF_FILENAME_DEFAULT = 'Choose file path for pdf output'
def initAlgorithm(self, config):
"""
Here we define the inputs and output of the algorithm
"""
#Add String as input
self.addParameter(
QgsProcessingParameterString(
self.INPUT_TITLE,
self.tr('Input title string (Optional)'),
" " #this is in place of making the dialog box "optional". Instead just gives default value as blank string
)
)
#Add String as input
self.addParameter(
QgsProcessingParameterString(
self.INPUT_SUBTITLE,
self.tr('Input Subtitle (Optional)'),
" "
)
)
#Add String as input
self.addParameter(
QgsProcessingParameterString(
self.INPUT_CREDIT_TEXT,
self.tr('Input Credit Text (Optional)'),
" "
)
)
#Add file path as input
self.addParameter(
QgsProcessingParameterFileDestination(
self.OUTPUT_PDF_PATH,
self.tr(self.OUTPUT_PDF_FILENAME_DEFAULT),
".pdf"
)
)
def processAlgorithm(self, parameters, context, feedback):
"""This actually creates the print layout and exporting as .pdf document"""
log = feedback.setProgressText
input_title = self.parameterAsString(parameters, self.INPUT_TITLE, context)
input_subtitle = self.parameterAsString(parameters, self.INPUT_SUBTITLE, context)
input_credit_text = self.parameterAsString(parameters, self.INPUT_CREDIT_TEXT, context)
output_pdf_path = self.parameterAsString(parameters, self.OUTPUT_PDF_PATH, context)
log(f"Title: {input_title}")
log(f"Subtitle: {input_subtitle}")
log(f"Credit Text: {input_credit_text}")
log(f"Output pdf path: {output_pdf_path}")
#This creates a new print layout
project = context.project()
manager = project.layoutManager()
layout = QgsPrintLayout(project)
layoutName = 'EcoValuator Layout' #layoutName is going to be name of Title. Change this later
layouts_list = manager.printLayouts()
for layout in layouts_list:
if layout.name() == layoutName:
manager.removeLayout(layout)
layout = QgsPrintLayout(project)
layout.initializeDefaults() #create default map canvas
layout.setName(layoutName)
manager.addLayout(layout)
#This adds a map item to the Print Layout
map = QgsLayoutItemMap(layout)
map.setRect(20, 20, 20, 20)
#Set Extent
canvas = iface.mapCanvas()
map.setExtent(canvas.extent()) #sets map extent to current map canvas
layout.addLayoutItem(map)
#Move & Resize
map.attemptMove(QgsLayoutPoint(5, 27, QgsUnitTypes.LayoutMillimeters))
map.attemptResize(QgsLayoutSize(218, 178, QgsUnitTypes.LayoutMillimeters))
#Gather visible layers in project layer tree and create a list of the map layer objects
#Those which are not active (layers_to_remove) will subsequently remove from the legend model
tree_layers = project.layerTreeRoot().children()
active_layers = [layer.name() for layer in tree_layers if layer.isVisible()]
layers_to_remove = [layer for layer in project.mapLayers().values() if layer.name() not in active_layers]
#This adds a legend item to the Print Layout
legend = QgsLayoutItemLegend(layout)
layout.addLayoutItem(legend)
legend.attemptMove(QgsLayoutPoint(219, 5, QgsUnitTypes.LayoutMillimeters))
#Get reference to existing legend model and root group then remove the unchecked layers
legend.setAutoUpdateModel(False) #not sure if this line is required
model = legend.model()
group = model.rootGroup()
for layer in layers_to_remove:
group.removeLayer(layer)
legend.adjustBoxSize()
#This adds labels to the map
title = QgsLayoutItemLabel(layout)
title.setText(input_title)
title.setFont(QFont("Arial", 28))
title.adjustSizeToText()
layout.addLayoutItem(title)
title.attemptMove(QgsLayoutPoint(10, 4, QgsUnitTypes.LayoutMillimeters))
subtitle = QgsLayoutItemLabel(layout)
subtitle.setText(input_subtitle)
subtitle.setFont(QFont("Arial", 17))
subtitle.adjustSizeToText()
layout.addLayoutItem(subtitle)
subtitle.attemptMove(QgsLayoutPoint(11, 20, QgsUnitTypes.LayoutMillimeters))
credit_text = QgsLayoutItemLabel(layout)
credit_text.setText(input_credit_text)
credit_text.setFont(QFont("Arial", 10))
credit_text.adjustSizeToText()
layout.addLayoutItem(credit_text)
credit_text.attemptMove(QgsLayoutPoint(219, 190, QgsUnitTypes.LayoutMillimeters))
#this creates credit text (line1) in bottom right corner of map layout giving credit to Key-Log Economics
keylog_credits1 = QgsLayoutItemLabel(layout)
keylog_credits1.setText("Created using EcoValuator Plugin")
keylog_credits1.setFont(QFont("Arial", 10))
keylog_credits1.adjustSizeToText()
layout.addLayoutItem(keylog_credits1)
keylog_credits1.attemptMove(QgsLayoutPoint(219, 195, QgsUnitTypes.LayoutMillimeters))
#this creates credit text (line2) in bottom right corner of map layout giving credit to Key-Log Economics
keylog_credits2 = QgsLayoutItemLabel(layout)
keylog_credits2.setText("by Key-Log Economics")
keylog_credits2.setFont(QFont("Arial", 10))
keylog_credits2.adjustSizeToText()
layout.addLayoutItem(keylog_credits2)
keylog_credits2.attemptMove(QgsLayoutPoint(219, 200, QgsUnitTypes.LayoutMillimeters))
#This exports a Print Layout as an image
manager = QgsProject.instance().layoutManager() #this is a reference to the layout Manager, which contains a list of print layouts
layout = manager.layoutByName(layoutName) #this accesses a specific layout, by name (which is a string)
exporter = QgsLayoutExporter(layout) #this creates a QgsLayoutExporter object
exporter.exportToPdf(output_pdf_path, QgsLayoutExporter.PdfExportSettings())
log("Done!")
result = {} #The processAlgorithm wants to return a dictionary. We don't actually need to do this so instead we return an empty one
return result
def flags(self):
"""
From documentation: Algorithm is not thread safe and cannot be run in a
background thread, e.g. algorithms which manipulate the current project,
layer selections, or with external dependencies which are not thread safe.
"""
return super().flags() | QgsProcessingAlgorithm.FlagNoThreading
def name(self):
"""
Returns the algorithm name, used for identifying the algorithm. This
string should be fixed for the algorithm, and must not be localised.
The name should be unique within each provider. Names should contain
lowercase alphanumeric characters only and no spaces or other
formatting characters.
"""
return 'Step 3: Create Print Layout and Export as .pdf'
def displayName(self):
"""
Returns the translated algorithm name, which should be used for any
user-visible display of the algorithm name.
"""
return self.tr(self.name())
def group(self):
"""
Returns the name of the group this algorithm belongs to. This string
should be localised.
"""
return self.tr(self.groupId())
def groupId(self):
"""
Returns the unique ID of the group this algorithm belongs to. This
string should be fixed for the algorithm, and must not be localised.
The group id should be unique within each provider. Group id should
contain lowercase alphanumeric characters only and no spaces or other
formatting characters.
"""
return 'EcoValuator'
def shortHelpString(self):
"""
Returns a localised short helper string for the algorithm. This string
should provide a basic description about what the algorithm does and the
parameters and outputs associated with it..
"""
return self.tr("This step produces a finished map output as a .pdf. The output will contain the map, legend, title, subtitle, and credit text. \n *The map will display the extent of the active window in your project. If you are zoomed out, your map will be small. Experiment to get the right size. \n *The legend will contain all active layers in your project (including tables). To remove something from the legend, turn it off in the layers panel or remove it from the project. \n Title: Add a title to your map. This will appear in the top left corner of the output. [This is optional] \n Subtitle: Add a subtitle to the map. This will appear in the output directly below the title. [This is optional] \n Credit Text: Add credits text to the map. This will appear in the bottom right corner of the output. [This is Optional] \n Choose file path for pdf output: Choose file path for pdf output. Make sure to specify .pdf file extension for output. \n *Note: You can customize your own print layout. At the top of the screen look under 'Project' and 'Layouts'. You will have a print layout titled 'EcoValuator Layout', which you can modify. ")
def tr(self, string):
return QCoreApplication.translate('Processing', string)
def helpUrl(self):
"""
Returns the location of the help file for this algorithm. This is the
location that will be followed when the user clicks the Help button
in the algorithm's UI.
"""
return "http://www.keylogeconomics.com/ecovaluator.html"
def createInstance(self):
return CreatePrintLayoutAndExportMap()