def test_json_export(self): project = QgsProject() self.assertTrue(project.read(os.path.join(unitTestDataPath('qgis_server'), 'test_project.qgs'))) model = QgsLegendModel(project.layerTreeRoot()) ctx = QgsRenderContext() settings = QgsLegendSettings() renderer = QgsLegendRenderer(model, settings) nodes = renderer.exportLegendToJson(ctx)['nodes'].toVariant() self.assertEqual(len(nodes), 7) self.assertEqual(nodes[0]['type'], 'layer') self.assertEqual(nodes[0]['title'], 'testlayer')
def add_wms_background_map(self, group=None): ''' add b/w terrestris-wms-layer to given group (or root) ''' layer_name = 'OpenStreetMap WMS - by terrestris' remove_layer(layer_name, group) url = ('crs=EPSG:31468&dpiMode=7&format=image/png&layers=OSM-WMS&' 'styles=&url=http://ows.terrestris.de/osm-gray/service') layer = QgsRasterLayer(url, layer_name, 'wms') QgsMapLayerRegistry.instance().addMapLayer(layer, group is None) if group: treelayer = group.addLayer(layer) QgsLegendRenderer.setNodeLegendStyle( treelayer, QgsComposerLegendStyle.Hidden)
def add_xml_background_map(self, xml, layer_name = 'GoogleMaps', group=None, visible=True): ''' add background map from xml file to given group (or root) ''' for child in group.children(): pass layer = QgsRasterLayer(xml, layer_name) #layer = QgsRasterLayer("http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer?f=json&pretty=true", "layer") remove_layer(layer_name, group) QgsMapLayerRegistry.instance().addMapLayer(layer, group is None) if group: treelayer = group.addLayer(layer) QgsLegendRenderer.setNodeLegendStyle( treelayer, QgsComposerLegendStyle.Hidden) iface.legendInterface().setLayerVisible(layer, visible)
def set_legend(layout: QgsPrintLayout, tree: QgsLayerTree, layer: QgsLayer, item_id: str): '''Sets the Legend items''' logging.info(f'setting legend: {item_id}') item = layout.itemById(item_id) # set layer as root for legend tree.addLayer(layer) model = item.model() model.setRootGroup(tree) root = model.rootGroup().findLayer(layer) # hide the node title QgsLegendRenderer.setNodeLegendStyle(root, QgsLegendStyle.Hidden) # hide the node with label: Band 1 (Gray) if isinstance(layer, QgsRasterLayer): nodes = model.layerLegendNodes(root) if nodes[0].data(0) == 'Band 1 (Gray)': indexes = list(range(1, len(nodes))) QgsMapLayerLegendUtils.setLegendNodeOrder(root, indexes) model.refreshLayerLegend(root)
def get_group(groupname, parent_group=None, add_at_index=None, hide_in_composer=True): ''' get a group from qgis-layer-window, if exists, else add it Parameters ---------- groupname: name of group parent_group: optional, parent to look for group in, if not given root add_at_index: optional, add the layer to given index (relative to other siblings) hide_in_composer: optional, if True, hide group in legend, when exporting to pdf ''' if not parent_group: parent_group = QgsProject.instance().layerTreeRoot() group = parent_group.findGroup(groupname) if not group: if add_at_index is not None: group = parent_group.insertGroup(add_at_index, groupname) else: group = parent_group.addGroup(groupname) if hide_in_composer: QgsLegendRenderer.setNodeLegendStyle( group, QgsComposerLegendStyle.Hidden) return group
def qgis_composer_renderer(impact_report, component): """Default Map Report Renderer using QGIS Composer. Render using qgis composer for a given impact_report data and component context. :param impact_report: ImpactReport contains data about the report that is going to be generated. :type impact_report: safe.report.impact_report.ImpactReport :param component: Contains the component metadata and context for rendering the output. :type component: safe.report.report_metadata.QgisComposerComponentsMetadata :return: Whatever type of output the component should be. .. versionadded:: 4.0 """ context = component.context """:type: safe.report.extractors.composer.QGISComposerContext""" qgis_composition_context = impact_report.qgis_composition_context # load composition object composition = QgsComposition(qgis_composition_context.map_settings) # load template main_template_folder = impact_report.metadata.template_folder # we do this condition in case custom template was found if component.template.startswith('../qgis-composer-templates/'): template_path = os.path.join(main_template_folder, component.template) else: template_path = component.template with open(template_path) as template_file: template_content = template_file.read() document = QtXml.QDomDocument() document.setContent(template_content) load_status = composition.loadFromTemplate( document, context.substitution_map) if not load_status: raise TemplateLoadingError( tr('Error loading template: %s') % template_path) # replace image path for img in context.image_elements: item_id = img.get('id') path = img.get('path') image = composition_item(composition, item_id, QgsComposerPicture) """:type: qgis.core.QgsComposerPicture""" if image and path: image.setPicturePath(path) # replace html frame for html_el in context.html_frame_elements: item_id = html_el.get('id') mode = html_el.get('mode') composer_item = composition.getComposerItemById(item_id) try: html_element = composition.getComposerHtmlByItem(composer_item) except: pass """:type: qgis.core.QgsComposerHtml""" if html_element: if mode == 'text': text = html_el.get('text') text = text if text else '' html_element.setContentMode(QgsComposerHtml.ManualHtml) html_element.setHtml(text) html_element.loadHtml() elif mode == 'url': url = html_el.get('url') html_element.setContentMode(QgsComposerHtml.Url) qurl = QUrl.fromLocalFile(url) html_element.setUrl(qurl) original_crs = impact_report.impact_function.crs destination_crs = qgis_composition_context.map_settings.destinationCrs() coord_transform = QgsCoordinateTransform(original_crs, destination_crs) # resize map extent for map_el in context.map_elements: item_id = map_el.get('id') split_count = map_el.get('grid_split_count') layers = [ layer for layer in map_el.get('layers') if isinstance( layer, QgsMapLayer) ] map_extent_option = map_el.get('extent') composer_map = composition_item(composition, item_id, QgsComposerMap) for index, layer in enumerate(layers): # we need to check whether the layer is registered or not registered_layer = ( QgsMapLayerRegistry.instance().mapLayer(layer.id())) if registered_layer: if not registered_layer == layer: layers[index] = registered_layer else: QgsMapLayerRegistry.instance().addMapLayer(layer) """:type: qgis.core.QgsComposerMap""" if composer_map: # Search for specified map extent in the template. min_x = composer_map.extent().xMinimum() if ( impact_report.use_template_extent) else None min_y = composer_map.extent().yMinimum() if ( impact_report.use_template_extent) else None max_x = composer_map.extent().xMaximum() if ( impact_report.use_template_extent) else None max_y = composer_map.extent().yMaximum() if ( impact_report.use_template_extent) else None composer_map.setKeepLayerSet(True) layer_set = [l.id() for l in layers if isinstance(l, QgsMapLayer)] composer_map.setLayerSet(layer_set) map_overview_extent = None if map_extent_option and isinstance( map_extent_option, QgsRectangle): # use provided map extent extent = coord_transform.transform(map_extent_option) for l in [layer for layer in layers if isinstance(layer, QgsMapLayer)]: layer_extent = coord_transform.transform(l.extent()) if l.name() == map_overview['id']: map_overview_extent = layer_extent else: # if map extent not provided, try to calculate extent # from list of given layers. Combine it so all layers were # shown properly extent = QgsRectangle() extent.setMinimal() for l in [layer for layer in layers if isinstance(layer, QgsMapLayer)]: # combine extent if different layer is provided. layer_extent = coord_transform.transform(l.extent()) extent.combineExtentWith(layer_extent) if l.name() == map_overview['id']: map_overview_extent = layer_extent width = extent.width() height = extent.height() longest_width = width if width > height else height half_length = longest_width / 2 margin = half_length / 5 center = extent.center() min_x = min_x or (center.x() - half_length - margin) max_x = max_x or (center.x() + half_length + margin) min_y = min_y or (center.y() - half_length - margin) max_y = max_y or (center.y() + half_length + margin) # noinspection PyCallingNonCallable square_extent = QgsRectangle(min_x, min_y, max_x, max_y) if component.key == 'population-infographic' and ( map_overview_extent): square_extent = map_overview_extent composer_map.zoomToExtent(square_extent) composer_map.renderModeUpdateCachedImage() actual_extent = composer_map.extent() # calculate intervals for grid x_interval = actual_extent.width() / split_count composer_map.grid().setIntervalX(x_interval) y_interval = actual_extent.height() / split_count composer_map.grid().setIntervalY(y_interval) # calculate legend element for leg_el in context.map_legends: item_id = leg_el.get('id') title = leg_el.get('title') layers = [ layer for layer in leg_el.get('layers') if isinstance( layer, QgsMapLayer) ] symbol_count = leg_el.get('symbol_count') column_count = leg_el.get('column_count') legend = composition_item(composition, item_id, QgsComposerLegend) """:type: qgis.core.QgsComposerLegend""" if legend: # set column count if column_count: legend.setColumnCount(column_count) elif symbol_count <= 7: legend.setColumnCount(1) else: legend.setColumnCount(symbol_count / 7 + 1) # set legend title if title is not None and not impact_report.legend_layers: legend.setTitle(title) # set legend root_group = legend.modelV2().rootGroup() for layer in layers: # we need to check whether the layer is registered or not registered_layer = ( QgsMapLayerRegistry.instance().mapLayer(layer.id())) if registered_layer: if not registered_layer == layer: layer = registered_layer else: QgsMapLayerRegistry.instance().addMapLayer(layer) # used for customizations tree_layer = root_group.addLayer(layer) if impact_report.legend_layers or ( not impact_report.multi_exposure_impact_function): QgsLegendRenderer.setNodeLegendStyle( tree_layer, QgsComposerLegendStyle.Hidden) legend.synchronizeWithModel() # process to output # in case output folder not specified if impact_report.output_folder is None: impact_report.output_folder = mkdtemp(dir=temp_dir()) output_format = component.output_format component_output_path = impact_report.component_absolute_output_path( component.key) component_output = None doc_format = QgisComposerComponentsMetadata.OutputFormat.DOC_OUTPUT template_format = QgisComposerComponentsMetadata.OutputFormat.QPT if isinstance(output_format, list): component_output = [] for i in range(len(output_format)): each_format = output_format[i] each_path = component_output_path[i] if each_format in doc_format: result_path = create_qgis_pdf_output( impact_report, each_path, composition, each_format, component) component_output.append(result_path) elif each_format == template_format: result_path = create_qgis_template_output( each_path, composition) component_output.append(result_path) elif isinstance(output_format, dict): component_output = {} for key, each_format in output_format.iteritems(): each_path = component_output_path[key] if each_format in doc_format: result_path = create_qgis_pdf_output( impact_report, each_path, composition, each_format, component) component_output[key] = result_path elif each_format == template_format: result_path = create_qgis_template_output( each_path, composition) component_output[key] = result_path elif (output_format in QgisComposerComponentsMetadata.OutputFormat.SUPPORTED_OUTPUT): component_output = None if output_format in doc_format: result_path = create_qgis_pdf_output( impact_report, component_output_path, composition, output_format, component) component_output = result_path elif output_format == template_format: result_path = create_qgis_template_output( component_output_path, composition) component_output = result_path component.output = component_output return component.output
def getLegendGraphic(self, params): qgsLayer = self.layerRegistry.mapLayer(params.get('layer')) boxSpace = 1 layerSpace = 2 # layerTitleSpace = 3 symbolSpace = 2 iconLabelSpace = 2 symbolWidth = 5 symbolHeight = 3 drawLegendLabel = True rootGroup = QgsLayerTreeGroup() rootGroup.addLayer(qgsLayer) # layer = QgsLayerTreeLayer(qgsLayer) # if qgsLayer.title(): # layer.setLayerName(qgsLayer.title()) legendModel = QgsLayerTreeModel(rootGroup) rootChildren = rootGroup.children() img_tmp = QImage(QSize(1, 1), QImage.Format_ARGB32_Premultiplied) dpm = 1 / 0.00028 img_tmp.setDotsPerMeterX(dpm) img_tmp.setDotsPerMeterY(dpm) dpmm = img_tmp.dotsPerMeterX() / 1000.0 del img_tmp legendSettings = QgsLegendSettings() legendSettings.setTitle('') legendSettings.setBoxSpace(boxSpace) legendSettings.rstyle(QgsComposerLegendStyle.Subgroup).setMargin(QgsComposerLegendStyle.Top, layerSpace) legendSettings.rstyle(QgsComposerLegendStyle.Symbol).setMargin(QgsComposerLegendStyle.Top, symbolSpace) legendSettings.rstyle(QgsComposerLegendStyle.SymbolLabel).setMargin(QgsComposerLegendStyle.Left, iconLabelSpace) legendSettings.setSymbolSize(QSizeF(symbolWidth, symbolHeight)) # legendSettings.rstyle(QgsComposerLegendStyle.Subgroup).setFont(layerFont) # legendSettings.rstyle(QgsComposerLegendStyle.SymbolLabel).setFont(itemFont) # // TODO: not available: layer font color # legendSettings.setFontColor( itemFontColor ); # for node in rootChildren: # if (QgsLayerTree.isLayer(node)): # QgsLegendRenderer.setNodeLegendStyle(node, QgsComposerLegendStyle.Subgroup) # # rule item titles # # if ( !mDrawLegendItemLabel ) # # for legendNode in legendModel.layerLegendNodes(nodeLayer): # # legendNode.setUserLabel(' ') # # } legendRenderer = QgsLegendRenderer(legendModel, legendSettings) minSize = legendRenderer.minimumSize() s = QSize(minSize.width() * dpmm, minSize.height() * dpmm) img = QImage(s, QImage.Format_ARGB32_Premultiplied) # fill in the background color = QColor(0, 0, 0, 0) img.fill(color) p = QPainter() p.begin(img) p.setRenderHint(QPainter.Antialiasing, True) p.scale(dpmm, dpmm) legendRenderer.drawLegend(p) map_buffer = QBuffer() map_buffer.open(QIODevice.ReadWrite) img.save(map_buffer, 'PNG') # clean up map_buffer.close() p.end() # self.layerRegistry.removeAllMapLayers() return map_buffer.data()
def renderer(self): if 'QGIS_AUTH_DB_DIR_PATH' not in os.environ: os.environ['QGIS_AUTH_DB_DIR_PATH'] = '/tmp' qgis = None while True: options, result = self.queue.get() # Don't start QGIS until first request if qgis is None: qgis = QgsApplication([], False) qgis.setPrefixPath(self.settings.get('path'), True) qgis.setDefaultSvgPaths(qgis.svgPaths() + self.settings.get('svgpaths')) qgis.setMaxThreads(1) qgis.initQgis() try: if isinstance(options, LegendOptions): style, = options layer = self._qgs_memory_layer(style) layer.setName(style.parent.display_name) QgsMapLayerRegistry.instance().addMapLayer(layer) root = QgsLayerTreeGroup() root.addLayer(layer) # 'Cannot create a QPixmap when no GUI is being used' # warning occurs here model = QgsLayerTreeModel(root) settings = QgsLegendSettings() settings.setTitle('') settings.setBoxSpace(1) settings.setSymbolSize(QSizeF(5, 3)) settings.setDpi(96) renderer = QgsLegendRenderer(model, settings) # Dots per mm dpmm = settings.dpi() / 25.4 min_size = renderer.minimumSize() size = QSize(dpmm * min_size.width(), dpmm * min_size.height()) img = QImage(size, QImage.Format_ARGB32) img.fill(QColor(0, 0, 0, 0)) painter = QPainter() painter.begin(img) painter.scale(dpmm, dpmm) renderer.drawLegend(painter) painter.end() QgsMapLayerRegistry.instance().removeAllMapLayers() ba = QByteArray() bf = QBuffer(ba) bf.open(QIODevice.WriteOnly) img.save(bf, 'PNG') bf.close() buf = StringIO() buf.write(bf.data()) buf.seek(0) result.put(buf) else: path = features = None if isinstance(options, VectorRenderOptions): style, features, render_size, \ extended, target_box = options layer = self._qgs_memory_layer(style, features=features) elif isinstance(options, RasterRenderOptions): style, path, render_size, \ extended, target_box = options layer = QgsRasterLayer(path) layer.loadNamedStyle( self.env.file_storage.filename(style.qml_fileobj)) settings = QgsMapSettings() settings.setLayers([layer.id()]) settings.setFlag(QgsMapSettings.DrawLabeling) settings.setFlag(QgsMapSettings.Antialiasing) settings.setCrsTransformEnabled(True) settings.setDestinationCrs(layer.crs()) settings.setMapUnits(layer.crs().mapUnits()) settings.setOutputSize(QSize(*render_size)) settings.setExtent(QgsRectangle(*extended)) settings.setOutputImageFormat(QImage.Format_ARGB32) bgcolor = QColor.fromRgba(qRgba(255, 255, 255, 0)) settings.setBackgroundColor(bgcolor) settings.setOutputDpi(96) QgsMapLayerRegistry.instance().addMapLayer(layer) settings.setLayers([layer.id()]) # Create QImage by hand to be able to use # QgsMapRendererCustomPainterJob. Others will not # allow to workaround a bug with overlay rendering. img = QImage(settings.outputSize(), QImage.Format_ARGB32) # These cludges are needed for rendering # on transparent background, otherwise it's a mess. img.fill(QColor.fromRgba(qRgba(255, 255, 255, 255))) img.fill(QColor.fromRgba(qRgba(255, 255, 255, 0))) # DPI should be equal to settings, otherwise an error. # In QImage the resolution is set in dots per meter # for each axis. dpm = settings.outputDpi() / 25.4 * 1000 img.setDotsPerMeterX(dpm) img.setDotsPerMeterY(dpm) painter = QPainter(img) job = QgsMapRendererCustomPainterJob(settings, painter) job.renderSynchronously() painter.end() QgsMapLayerRegistry.instance().removeAllMapLayers() img = self._qimage_to_pil(img) # Clip needed part result.put(img.crop(target_box)) # Cleanup if path is not None: gdal.Unlink(path) except Exception as exc: self.logger.error(exc.message) result.put(exc) qgis.exitQgis()
composition.loadFromTemplate(template_document) # Set up atlas to produce one report per region vector_layer = dataobjects.getObjectFromUri(vector) atlas = composition.atlasComposition() atlas.setCoverageLayer(vector_layer) atlas.setEnabled(True) composition.setAtlasMode(QgsComposition.ExportAtlas) atlas_map = composition.getComposerItemById("atlas_map") atlas_map.setAtlasDriven(True) atlas_map.setLayerSet([vector_layer.id(), raster_layer.id()]) atlas_map.setKeepLayerSet(True) atlas_legend = composition.getComposerItemById("atlas_legend") raster_legend = atlas_legend.modelV2().rootGroup().addLayer(raster_layer) QgsLegendRenderer.setNodeLegendStyle(raster_legend, QgsComposerLegendStyle.Hidden) atlas_legend.updateLegend() # atlas_legend.refreshLayerLegend(raster_legend) stats_table = composition.getComposerItemById("stats_table").multiFrame() stats_table.setContentMode(QgsComposerHtml.ManualHtml) title_label = composition.getComposerItemById("title_label") title_text = title_label.text() description_label = composition.getComposerItemById("description_label") description_text = description_label.text() # Set a rule based style to highlight the atlas feature normal_style = QgsFillSymbolV2().createSimple( { "color": "#000000", "color_border": "#000000", "width_border": "0.25",
def qgis_composer_renderer(impact_report, component): """Default Map Report Renderer using QGIS Composer. Render using qgis composer for a given impact_report data and component context :param impact_report: ImpactReport contains data about the report that is going to be generated :type impact_report: safe.report.impact_report.ImpactReport :param component: Contains the component metadata and context for rendering the output :type component: safe.report.report_metadata.QgisComposerComponentsMetadata :return: whatever type of output the component should be .. versionadded:: 4.0 """ context = component.context """:type: safe.report.extractors.composer.QGISComposerContext""" qgis_composition_context = impact_report.qgis_composition_context inasafe_context = impact_report.inasafe_context # load composition object composition = QgsComposition(qgis_composition_context.map_settings) # load template main_template_folder = impact_report.metadata.template_folder template_path = os.path.join(main_template_folder, component.template) with open(template_path) as template_file: template_content = template_file.read() document = QtXml.QDomDocument() document.setContent(template_content) load_status = composition.loadFromTemplate( document, context.substitution_map) if not load_status: raise TemplateLoadingError( tr('Error loading template: %s') % template_path) # replace image path for img in context.image_elements: item_id = img.get('id') path = img.get('path') image = composition.getComposerItemById(item_id) """:type: qgis.core.QgsComposerPicture""" if image is not None and path is not None: try: image.setPicturePath(path) except: pass # replace html frame for html_el in context.html_frame_elements: item_id = html_el.get('id') mode = html_el.get('mode') html_element = composition.getComposerItemById(item_id) """:type: qgis.core.QgsComposerHtml""" if html_element: if mode == 'text': text = html_el.get('text') text = text if text else '' html_element.setContentMode(QgsComposerHtml.ManualHtml) html_element.setHtml(text) html_element.loadHtml() elif mode == 'url': url = html_el.get('url') html_element.setContentMode(QgsComposerHtml.Url) qurl = QUrl.fromLocalFile(url) html_element.setUrl(qurl) # resize map extent for map_el in context.map_elements: item_id = map_el.get('id') split_count = map_el.get('grid_split_count') layers = map_el.get('layers') map_extent_option = map_el.get('extent') composer_map = composition.getComposerItemById(item_id) """:type: qgis.core.QgsComposerMap""" if isinstance(composer_map, QgsComposerMap): composer_map.setKeepLayerSet(True) layer_set = [l.id() for l in layers if isinstance(l, QgsMapLayer)] composer_map.setLayerSet(layer_set) if map_extent_option and isinstance( map_extent_option, QgsRectangle): # use provided map extent extent = map_extent_option else: # if map extent not provided, try to calculate extent # from list of given layers. Combine it so all layers were # shown properly extent = QgsRectangle() extent.setMinimal() for l in layers: # combine extent if different layer is provided. extent.combineExtentWith(l.extent()) width = extent.width() height = extent.height() longest_width = width if width > height else height half_length = longest_width / 2 margin = half_length / 5 center = extent.center() min_x = center.x() - half_length - margin max_x = center.x() + half_length + margin min_y = center.y() - half_length - margin max_y = center.y() + half_length + margin # noinspection PyCallingNonCallable square_extent = QgsRectangle(min_x, min_y, max_x, max_y) composer_map.zoomToExtent(square_extent) composer_map.renderModeUpdateCachedImage() actual_extent = composer_map.extent() # calculate intervals for grid x_interval = actual_extent.width() / split_count composer_map.grid().setIntervalX(x_interval) y_interval = actual_extent.height() / split_count composer_map.grid().setIntervalY(y_interval) # calculate legend element for leg_el in context.map_legends: item_id = leg_el.get('id') title = leg_el.get('title') layers = leg_el.get('layers') symbol_count = leg_el.get('symbol_count') column_count = leg_el.get('column_count') legend = composition.getComposerItemById(item_id) """:type: qgis.core.QgsComposerLegend""" if isinstance(legend, QgsComposerLegend): # set column count if column_count: legend.setColumnCount(column_count) elif symbol_count <= 5: legend.setColumnCount(1) else: legend.setColumnCount(symbol_count / 5 + 1) # set legend title if title is not None: legend.setTitle(title) # set legend root_group = legend.modelV2().rootGroup() for l in layers: # used for customizations tree_layer = root_group.addLayer(l) QgsLegendRenderer.setNodeLegendStyle( tree_layer, QgsComposerLegendStyle.Hidden) legend.synchronizeWithModel() # process to output # in case output folder not specified if impact_report.output_folder is None: impact_report.output_folder = mkdtemp(dir=temp_dir()) output_format = component.output_format component_output_path = impact_report.component_absolute_output_path( component.key) component_output = None doc_format = QgisComposerComponentsMetadata.OutputFormat.DOC_OUTPUT template_format = QgisComposerComponentsMetadata.OutputFormat.QPT if isinstance(output_format, list): component_output = [] for i in range(len(output_format)): each_format = output_format[i] each_path = component_output_path[i] if each_format in doc_format: result_path = create_qgis_pdf_output( each_path, composition, impact_report.qgis_composition_context, each_format, component) component_output.append(result_path) elif each_format == template_format: result_path = create_qgis_template_output( each_path, composition) component_output.append(result_path) elif isinstance(output_format, dict): component_output = {} for key, each_format in output_format.iteritems(): each_path = component_output_path[key] if each_format in doc_format: result_path = create_qgis_pdf_output( each_path, composition, impact_report.qgis_composition_context, each_format, component) component_output[key] = result_path elif each_format == template_format: result_path = create_qgis_template_output( each_path, composition) component_output[key] = result_path elif (output_format in QgisComposerComponentsMetadata.OutputFormat.SUPPORTED_OUTPUT): component_output = None if output_format in doc_format: result_path = create_qgis_pdf_output( component_output_path, composition, impact_report.qgis_composition_context, output_format, component) component_output = result_path elif output_format == template_format: result_path = create_qgis_template_output( component_output_path, composition) component_output = result_path component.output = component_output return component.output
def qgis_composer_renderer(impact_report, component): """Default Map Report Renderer using QGIS Composer. Render using qgis composer for a given impact_report data and component context. :param impact_report: ImpactReport contains data about the report that is going to be generated. :type impact_report: safe.report.impact_report.ImpactReport :param component: Contains the component metadata and context for rendering the output. :type component: safe.report.report_metadata.QgisComposerComponentsMetadata :return: Whatever type of output the component should be. .. versionadded:: 4.0 """ context = component.context qgis_composition_context = impact_report.qgis_composition_context # load composition object layout = QgsPrintLayout(QgsProject.instance()) # load template main_template_folder = impact_report.metadata.template_folder # we do this condition in case custom template was found if component.template.startswith('../qgis-composer-templates/'): template_path = os.path.join(main_template_folder, component.template) else: template_path = component.template with open(template_path) as template_file: template_content = template_file.read() document = QtXml.QDomDocument() # Replace for k, v in context.substitution_map.items(): template_content = template_content.replace('[{}]'.format(k), v) document.setContent(template_content) rwcontext = QgsReadWriteContext() load_status = layout.loadFromTemplate( document, rwcontext) if not load_status: raise TemplateLoadingError( tr('Error loading template: %s') % template_path) # replace image path for img in context.image_elements: item_id = img.get('id') path = img.get('path') image = layout_item(layout, item_id, QgsLayoutItemPicture) if image and path: image.setPicturePath(path) # replace html frame for html_el in context.html_frame_elements: item_id = html_el.get('id') mode = html_el.get('mode') html_element = layout_item(layout, item_id, QgsLayoutItemHtml) if html_element: if mode == 'text': text = html_el.get('text') text = text if text else '' html_element.setContentMode(QgsLayoutItemHtml.ManualHtml) html_element.setHtml(text) html_element.loadHtml() elif mode == 'url': url = html_el.get('url') html_element.setContentMode(QgsLayoutItemHtml.Url) qurl = QUrl.fromLocalFile(url) html_element.setUrl(qurl) original_crs = impact_report.impact_function.crs destination_crs = qgis_composition_context.map_settings.destinationCrs() coord_transform = QgsCoordinateTransform(original_crs, destination_crs, QgsProject.instance()) # resize map extent for map_el in context.map_elements: item_id = map_el.get('id') split_count = map_el.get('grid_split_count') layers = [ layer for layer in map_el.get('layers') if isinstance( layer, QgsMapLayer) ] map_extent_option = map_el.get('extent') composer_map = layout_item(layout, item_id, QgsLayoutItemMap) for index, layer in enumerate(layers): # we need to check whether the layer is registered or not registered_layer = ( QgsProject.instance().mapLayer(layer.id())) if registered_layer: if not registered_layer == layer: layers[index] = registered_layer else: QgsProject.instance().addMapLayer(layer) """:type: qgis.core.QgsLayoutItemMap""" if composer_map: # Search for specified map extent in the template. min_x = composer_map.extent().xMinimum() if ( impact_report.use_template_extent) else None min_y = composer_map.extent().yMinimum() if ( impact_report.use_template_extent) else None max_x = composer_map.extent().xMaximum() if ( impact_report.use_template_extent) else None max_y = composer_map.extent().yMaximum() if ( impact_report.use_template_extent) else None composer_map.setKeepLayerSet(True) layer_set = [l for l in layers if isinstance(l, QgsMapLayer)] composer_map.setLayers(layer_set) map_overview_extent = None if map_extent_option and isinstance( map_extent_option, QgsRectangle): # use provided map extent extent = coord_transform.transform(map_extent_option) for l in [layer for layer in layers if isinstance(layer, QgsMapLayer)]: layer_extent = coord_transform.transform(l.extent()) if l.name() == map_overview['id']: map_overview_extent = layer_extent else: # if map extent not provided, try to calculate extent # from list of given layers. Combine it so all layers were # shown properly extent = QgsRectangle() extent.setMinimal() for l in [layer for layer in layers if isinstance(layer, QgsMapLayer)]: # combine extent if different layer is provided. layer_extent = coord_transform.transform(l.extent()) extent.combineExtentWith(layer_extent) if l.name() == map_overview['id']: map_overview_extent = layer_extent width = extent.width() height = extent.height() longest_width = width if width > height else height half_length = longest_width / 2 margin = half_length / 5 center = extent.center() min_x = min_x or (center.x() - half_length - margin) max_x = max_x or (center.x() + half_length + margin) min_y = min_y or (center.y() - half_length - margin) max_y = max_y or (center.y() + half_length + margin) # noinspection PyCallingNonCallable square_extent = QgsRectangle(min_x, min_y, max_x, max_y) if component.key == 'population-infographic' and ( map_overview_extent): square_extent = map_overview_extent composer_map.zoomToExtent(square_extent) composer_map.invalidateCache() actual_extent = composer_map.extent() # calculate intervals for grid x_interval = actual_extent.width() / split_count composer_map.grid().setIntervalX(x_interval) y_interval = actual_extent.height() / split_count composer_map.grid().setIntervalY(y_interval) # calculate legend element for leg_el in context.map_legends: item_id = leg_el.get('id') title = leg_el.get('title') layers = [ layer for layer in leg_el.get('layers') if isinstance( layer, QgsMapLayer) ] symbol_count = leg_el.get('symbol_count') column_count = leg_el.get('column_count') legend = layout_item(layout, item_id, QgsLayoutItemLegend) """:type: qgis.core.QgsLayoutItemLegend""" if legend: # set column count if column_count: legend.setColumnCount(column_count) elif symbol_count <= 7: legend.setColumnCount(1) else: legend.setColumnCount(symbol_count / 7 + 1) # set legend title if title is not None and not impact_report.legend_layers: legend.setTitle(title) # set legend root_group = legend.model().rootGroup() for layer in layers: # we need to check whether the layer is registered or not registered_layer = ( QgsProject.instance().mapLayer(layer.id())) if registered_layer: if not registered_layer == layer: layer = registered_layer else: QgsProject.instance().addMapLayer(layer) # used for customizations tree_layer = root_group.addLayer(layer) if impact_report.legend_layers or ( not impact_report.multi_exposure_impact_function): QgsLegendRenderer.setNodeLegendStyle( tree_layer, QgsLegendStyle.Hidden) legend.adjustBoxSize() legend.updateFilterByMap(False) # process to output # in case output folder not specified if impact_report.output_folder is None: impact_report.output_folder = mkdtemp(dir=temp_dir()) output_format = component.output_format component_output_path = impact_report.component_absolute_output_path( component.key) component_output = None doc_format = QgisComposerComponentsMetadata.OutputFormat.DOC_OUTPUT template_format = QgisComposerComponentsMetadata.OutputFormat.QPT if isinstance(output_format, list): component_output = [] for i in range(len(output_format)): each_format = output_format[i] each_path = component_output_path[i] if each_format in doc_format: result_path = create_qgis_pdf_output( impact_report, each_path, layout, each_format, component) component_output.append(result_path) elif each_format == template_format: result_path = create_qgis_template_output( each_path, layout) component_output.append(result_path) elif isinstance(output_format, dict): component_output = {} for key, each_format in list(output_format.items()): each_path = component_output_path[key] if each_format in doc_format: result_path = create_qgis_pdf_output( impact_report, each_path, layout, each_format, component) component_output[key] = result_path elif each_format == template_format: result_path = create_qgis_template_output( each_path, layout) component_output[key] = result_path elif (output_format in QgisComposerComponentsMetadata.OutputFormat.SUPPORTED_OUTPUT): component_output = None if output_format in doc_format: result_path = create_qgis_pdf_output( impact_report, component_output_path, layout, output_format, component) component_output = result_path elif output_format == template_format: result_path = create_qgis_template_output( component_output_path, layout) component_output = result_path component.output = component_output return component.output
def add_db_layer(self, name, schema, tablename, geom, symbology=None, uri=None, key=None, zoom=False, group=None, where='', visible=True, to_shape=False, hide_in_composer=False): """ add a layer with database as source to the qgis-layer-window Parameters ---------- name: layer-label that will be displayed in layer-window schema: name of database schema tablename: name of table in schema where: optional, sql-where-clause to limit the query-response geom: name of the geometry-column to use to display on map key: optional, primary key visible: optional, if True, added layer will be unchecked in layer-window uri: optional, specific uri to source (qgis-style), if not given it will be created from login and database info zoom: optional, zoom to layer after adding, if True to_shape: optional, if True, store the database-layer to a file in the cache- folder, adds the link to this file to layer-window instead of direct link to database group: optional, name of the group to add the layer to, if not given layer is added to root hide_in_composer: optional, if True, the layer will not be displayed in the legend when exporting to pdf """ if not uri: uri = QgsDataSourceURI() uri.setConnection(self.login.host, self.login.port, self.login.db, self.login.user, self.login.password) uri.setDataSource(schema, tablename, geom, aKeyColumn=key, aSql=where) uri = uri.uri(False) layer = QgsVectorLayer(uri, name, "postgres") remove_layer(name, group) if to_shape: path = config.cache_folder if not os.path.exists(path): os.mkdir(path) fn = os.path.join(path, u'{}_{}.shp'.format( self.active_scenario.name, name)) QgsVectorFileWriter.writeAsVectorFormat( layer, fn, 'utf-8', None, 'ESRI Shapefile') layer = QgsVectorLayer(fn, name, "ogr") # if no group is given, add to layer-root QgsMapLayerRegistry.instance().addMapLayer(layer, group is None) #if where: #layer.setSubsetString(where) treelayer = None if group: treelayer = group.addLayer(layer) if symbology: symbology.apply(layer) if zoom: extent = layer.extent() self.canvas.setExtent(extent) iface.legendInterface().setLayerVisible(layer, visible) self.canvas.refresh() if hide_in_composer and treelayer: QgsLegendRenderer.setNodeLegendStyle( treelayer, QgsComposerLegendStyle.Hidden) return layer