19.3. Criando um arquivo de Saída

Fig. 19.62 shows an example print layout including all the types of layout items described in the previous section.

../../../_images/print_composer_complete.png

Fig. 19.62 Print Layout with map view, legend, image, scale bar, coordinates, text and HTML frame added

From the Layout menu or toolbar, you can output the print layout to different file formats, and it is possible to modify the resolution (print quality) and paper size:

  • The filePrint Print icon allows you to print the layout to a connected printer or a PostScript file, depending on the installed printer drivers.

  • The salvarMapaComoImagem Export as image icon exports the print layout image formats such as PNG, BMP, TIF, JPG, and many others…

  • The salvarComoSVG Export as SVG icon saves the print layout as an SVG (Scalable Vector Graphic).

  • O ícone salvarComoPDF Exportar como PDF salva o layout de impressão definido diretamente como um arquivo PDF (Portable Document Format).

19.3.1. Definições para exportação

Whenever you export a print layout, there are a selection of export settings QGIS needs to check in order to produce the most appropriate output. These configurations are:

19.3.2. Exportar como Imagem

Para exportar um layout como uma imagem:

  1. Clique no ícone salvarMapaComoImagem Exportar como imagem

  2. Select the image format, the folder and filename (e.g. myill.png) to use. If the layout contains more than one page, each page will be exported to a file with the given filename with the page number appended (e.g. myill_2.png).

  3. Na próxima caixa de diálogo (Opções de Exportação de Imagem):

    • You can override the print layout Export resolution and the exported page dimensions (as set in Layout panel).

    • Image rendering can also be improved with the Enable antialiasing option.

    • If you want to export your layout as a georeferenced image (e.g., to share with other projects), check the desmarcado Generate world file option, and an ESRI World File with the same name as the exported image, but a different extension (.tfw for TIFF, .pnw for PNG, jgw for JPEG, …) will be created when exporting. This option can also be checked by default in the layout panel.

      Nota

      For multi-page output, only the page that contains the reference map will get a world file (assuming that the Generate world file option is checked).

    • By checking caixa de seleção Crop to content option, the image output by the layout will include the minimal area enclosing all the items (map, legend, scale bar, shapes, label, image…) of each page of the composition:

      • Se a composição incluir uma única página, a saída será redimensionada para incluir TUDO na composição. A página pode ser reduzida ou estendida a todos os itens, dependendo da sua posição (na, acima, abaixo, esquerda ou direita da página).

      • In case of a multi-page layout, each page will be resized to include items in its area (left and right sides for all pages, plus top for the first page and bottom for the last page). Each resized page is exported to a separate file.

      The Crop to content dialog also lets you add margins around the cropped bounds.

../../../_images/image_export_options.png

Fig. 19.63 Opções de Exportação de Imagens, a saída é redimensionada para itens

Dica

Use formatos de imagem compatíveis com transparência quando os itens ultrapassarem a extensão do papel

Layout items may be placed outside the paper extent. When exporting with the Crop to content option, the resulting image may therefore extend beyond the paper extent. Since the background outside of the paper extent will be transparent, for image formats that do not support transparency (e.g. BMP and JPG) the transparent background will be rendered as full black, “corrupting” the image. Use transparency-compatible formats (e.g. TIFF and PNG) in such cases.

Nota

When supported by the format (e.g. PNG) and the underlying Qt library, the exported image may include project metadata (author, title, date, description…)

19.3.3. Exportar como SVG

Para exportar um layout como SVG:

  1. Clique no ícone salvarComoSVG Exportar como SVG

  2. Fill in the path and filename (used as a base name for all the files in case of multi-page composition, as for image export)

  3. In the next SVG Export Options dialog, you can override the layout default export settings or configure new ones:

    • desmarcado Export map layers as SVG groups: exported items are grouped within layers whose name matches the layer names from QGIS, making it much easier to understand the contents of the document.

    • desmarcado Always export as vectors: some rendering options require items to be rasterized for a better rendering. Check this option to keep the objects as vectors with the risk that the appearance of the output file may not match the print layout preview (for more details, see Definições para exportação).

    • caixa de seleção Exportar metadados RDF do documento, como título, autor, data, descrição…

    • caixa de seleção Simplify geometries to reduce output file size: this avoids exporting ALL geometry vertices, which can result in a ridiculously complex and large export file size that could fail to load in other applications. Geometries will be simplified while exporting the layout in order to remove any redundant vertices which are not discernably different at the export resolution (e.g. if the export resolution is 300 dpi, vertices that are less than 1/600 inch apart will be removed).

    • Defina a Exportação de texto: controla se os rótulos de texto são exportados como objetos de texto adequados (Sempre exportar textos como objetos de texto) ou apenas como caminhos (Sempre exportar textos como caminhos). Se forem exportados como objetos de texto, poderão ser editados em aplicativos externos (por exemplo, Inkscape) como texto normal. MAS o efeito colateral é que a qualidade da renderização é reduzida E há problemas com a renderização quando determinadas configurações de texto, como buffers, estão em vigor. É por isso que a exportação como caminhos é recomendada.

    • Apply caixa de seleção Crop to content option

    • desmarcado Disable tiled raster layer exports: When exporting files, QGIS uses a built-in raster layer tiled rendering that saves memory. Sometimes, this can cause visible “seams” in the rasters for generated files. Checking this option would fix that, at the cost of a higher memory usage during exports.

../../../_images/svg_export_options.png

Fig. 19.64 Opções de Exportação SVG

Nota

Currently, the SVG output is very basic. This is not a QGIS problem, but a problem with the underlying Qt library. This will hopefully be sorted out in future versions.

19.3.4. Exportar como PDF

Para exportar um layout como PDF:

  1. Click the salvarComoPDF Export as PDF icon

  2. Preencha o caminho e o nome do arquivo: diferente da exportação de imagem e SVG, todas as páginas do layout são exportadas para um único arquivo PDF.

  3. In the next PDF Export Options dialog, you can override the layout default export settings or configure new ones:

    • desmarcado Always export as vectors: some rendering options require items to be rasterized for a better rendering. Check this option to keep the objects as vectors with the risk that the appearance of the output file may not match the print layout preview (for more details, see Definições para exportação).

    • caixa de seleção Append georeference information: available only if the reference map, from which the information is taken, is on the first page.

    • caixa de seleção Exportar metadados RDF do documento, como título, autor, data, descrição…

    • Defina :guilabel: Exportar texto`: controla se os rótulos de texto são exportados como objetos de texto adequados (Sempre exportar textos como objetos de texto) ou apenas como caminhos (Sempre exporta textos como caminhos). Se eles forem exportados como objetos de texto, poderão ser editados em aplicativos externos (por exemplo, Inkscape) como texto normal. MAS o efeito colateral é que a qualidade da renderização diminui E há problemas com a renderização quando determinadas configurações de texto, como buffers, estão em vigor. É por isso que a exportação como caminhos é recomendada.

    • Control the PDF Image compression using:

      • Lossy (JPEG), which is the default compression mode

      • or Lossless, which creates bigger files in most cases, but is much more suitable for printing outputs or for post-production in external applications (requires Qt 5.13 or later).

    • desmarcado Create Geospatial PDF (GeoPDF): Generate a georeferenced PDF file (requires GDAL version 3 or later).

    • desmarcado Disable tiled raster layer exports: When exporting files, QGIS uses tiled based rendering that saves memory. Sometimes, this can cause visible “seams” in the rasters for generated files. Checking this option would fix that, at the cost of a higher memory usage during exports.

    • caixa de seleção Simplify geometries to reduce output file size: Geometries will be simplified while exporting the layout by removing vertices that are not discernably different at the export resolution (e.g. if the export resolution is 300 dpi, vertices that are less than 1/600 inch apart will be removed). This can reduce the size and complexity of the export file (very large files can fail to load in other applications).

../../../_images/pdf_export_options.png

Fig. 19.65 Opções de exportação de PDF

Nota

Since QGIS 3.10, with GDAL 3, GeoPDF export is supported, and a number of GeoPDF specific options are available:

  • Format (GeoPDF format - there are some GeoPDF variations),

  • Include multiple map themes (specify map themes to include),

  • Include vector feature information (choose the layers and group them into logical PDF groups).

Nota

A exportação de um layout de impressão para formatos que suportam georreferenciamento (por exemplo PDF e TIFF) cria uma saída georreferenciada por padrão.

19.3.5. Gerar um Atlas

Atlas functions allow you to create map books in an automated way. Atlas uses the features of a table or vector layer (Coverage layer) to create an output for each feature (atlas feature) in the table / layer. The most common usage is to zoom a map item to the current atlas feature. Further use cases include:

  • um item de mapa mostrando, para outra camada, apenas feições que compartilham o mesmo atributo que a feição atlas ou estão dentro de sua geometria.

  • um rótulo ou item HTML cujo texto é substituído à medida que as feições são iteradas

  • a table item showing attributes of associated parent or children features of the current atlas feature…

Para cada feição, a saída é processada para todas as páginas e itens de acordo com suas configurações de exportação.

Dica

Usar variáveis para maior flexibilidade

QGIS provides a large panel of functions and variables, including atlas related ones, that you can use to manipulate the layout items, but also the symbology of the layers, according to atlas status. Combining these features gives you a lot of flexibility and helps you easily produce advanced maps.

To enable the generation of an atlas and access atlas parameters, refer to the Atlas panel. This panel contains the following (see Fig. 19.66):

../../../_images/atlas_properties.png

Fig. 19.66 Atlas Panel

  • caixa de seleção Gerar um atlas habilita ou desabilita a geração de atlas.

  • Configuração

    • A Coverage layer selecionarTexto combo box that allows you to choose the table or vector layer containing the features to iterate over.

    • An optional caixa de seleção Hidden coverage layer that, if checked, will hide the coverage layer (but not the other layers) during the generation.

    • An optional Page name combo box to specify the name for the feature page(s). You can select a field of the coverage layer or set an expression. If this option is empty, QGIS will use an internal ID, according to the filter and/or the sort order applied to the layer.

    • An optional caixa de seleção Filter with text area that allows you to specify an expression for filtering features from the coverage layer. If the expression is not empty, only features that evaluate to True will be processed.

    • An optional caixa de seleção Sort by that allows you to sort features of the coverage layer (and the output), using a field of the coverage layer or an expression. The sort order (either ascending or descending) is set by the two-state Sort direction button that displays an up or a down arrow.

  • Output - this is where the output of the atlas can be configured:

    • An Output filename expression textbox that is used to generate a filename for each atlas feature. It is based on expressions. is meaningful only for rendering to multiple files.

    • A caixa de seleção Single file export when possible that allows you to force the generation of a single file if this is possible with the chosen output format (PDF, for instance). If this field is checked, the value of the Output filename expression field is meaningless.

    • Uma lista drop-down Formato de exportação de imagem para selecionar o formato de saída quando usar o botão salvarMapaComoImagem Exportar atlas como Imagens ….

19.3.5.1. Control map by atlas

The most common usage of atlas is with the map item, zooming to the current atlas feature, as iteration goes over the coverage layer. This behavior is set in the Controlled by atlas group properties of the map item. See Controlado por atlas for different settings you can apply on the map item.

19.3.5.2. Customizar rótulos com expressão

Para adaptar rótulos ao recurso em que o atlas repete, você pode incluir expressões. Certifique-se de colocar a parte da expressão (incluindo funções, campos ou variáveis) entre [% e %] (veja A rotulagem de item para mais detalhes).

For example, for a city layer with fields CITY_NAME and ZIPCODE, you could insert this:

The area of [% concat( upper(CITY_NAME), ',', ZIPCODE, ' is ',
format_number($area/1000000, 2) ) %] km2

ou outra combinação:

The area of [% upper(CITY_NAME)%],[%ZIPCODE%] is
[%format_number($area/1000000,2) %] km2

The information [% concat( upper(CITY_NAME), ',', ZIPCODE, ' is ',  format_number($area/1000000, 2) ) %] is an expression used inside the label. Both expressions would result in the following type of label in the generated atlas:

The area of PARIS,75001 is 1.94 km2

19.3.5.3. Explore Data-defined override buttons with atlas

There are several places where you can use a definirDados Data defined override button to override the selected setting. This is particularly useful with atlas generation. See Data defined override setup for more details on this widget.

For the following examples the Regions layer of the QGIS sample dataset is used and selected as Coverage layer for the atlas generation. We assume that it is a single page layout containing a map item and a label item.

When the height (north-south) of a region extent is greater than its width (east-west), you should use Portrait instead of Landscape orientation to optimize the use of paper. With a definirDados Data Defined Override button you can dynamically set the paper orientation.

Right-click on the page and select Page Properties to open the panel. We want to set the orientation dynamically, using an expression depending on the region geometry, so press the definirDados button of field Orientation, select Edit… to open the Expression string builder dialog and enter the following expression:

CASE WHEN bounds_width(@atlas_geometry) > bounds_height(@atlas_geometry)
THEN 'Landscape' ELSE 'Portrait' END

Now if you preview the atlas, the paper orients itself automatically, but item placements may not be ideal. For each Region you need to reposition the location of the layout items as well. For the map item you can use the definirDados button of its Width property to set it dynamic using the following expression:

@layout_pagewidth - 20

Likewise, use the definirDados button of the Height property to provide the following expression to constrain map item size:

@layout_pageheight - 20

To ensure the map item is centered in the page, set its Reference point to the upper left radio button and enter 10 for its X and Y positions.

Let’s add a title above the map in the center of the page. Select the label item and set the horizontal alignment to radioButtonOn Center. Next move the label to the right position, choose the middle button for the Reference point, and provide the following expression for field X:

@layout_pagewidth / 2

For all other layout items you can set the position in a similar way so they are correctly positioned both for portrait and landscape. You can also do more tweaks such as customizing the title with feature attributes (see Customizar rótulos com expressão example), changing images, resizing the number of legend columns number according to page orientation, …

The information provided here is an update of the excellent blog (in English and Portuguese) on the Data Defined Override options Multiple_format_map_series_using_QGIS_2.6 .

Another example for using data-defined override buttons is the usage of a dynamic picture. For the following examples we use a geopackage layer containing a BLOB field called logo with the field type binary (see Criando uma nova camada GeoPackage). For every feature there is defined a different picture so that the atlas can iterate over as described in Pré-visualizar e gerar um atlas. All you need to do is add a picture in the print layout and go to its Item properties in the atlas context. There you can find a data-defined override button in the Image source section of the Main Properties.

../../../_images/picture_image_source.png

In the following window choose Edit so that the Expression String Builder opens. From the Fields and values section you can find the BLOB field that was defined in the geopackage layer. Double-click the field name logo and click OK.

../../../_images/expression_blob_picture_atlas.png

The atlas iterates over the entries in the BLOB field provided that you choose the geopackage layer as Coverage layer (further instructions you can find in Pré-visualizar e gerar um atlas).

Estes são apenas dois exemplos de como você pode usar algumas configurações avançadas com o atlas.

19.3.5.4. Pré-visualizar e gerar um atlas

../../../_images/atlas_preview.png

Fig. 19.67 Barra de ferramentas de pré-visualização do Atlas

Once the atlas settings have been configured, and layout items (map, table, image…) linked to it, you can create a preview of all the pages by choosing Atlas ► Preview Atlas or clicking the atlas Preview Atlas icon. You can then use the arrows to navigate through all the features:

  • atlasFirst First feature

  • atlasPrev Previous feature

  • atlasNext Next feature

  • atlasLast Last feature

You can also use the combo box to select and preview a specific feature. The combo box shows atlas feature names according to the expression set in the atlas Page name option.

As for simple compositions, an atlas can be generated in different ways (see Criando um arquivo de Saída for more information - just use tools from the Atlas menu or toolbar instead of the Layout menu.

This means that you can directly print your compositions with Atlas ► Print Atlas. You can also create a PDF using Atlas ► Export Atlas as PDF…: You will be asked for a directory to save all the generated PDF files, except if the caixa de seleção Single file export when possible has been selected. In that case, you’ll be prompted to give a filename.

With Atlas ► Export Atlas as Images… or Atlas ► Export Atlas as SVG… tool, you’re also prompted to select a folder. Each page of each atlas feature composition is exported to the image file format set in Atlas panel or to SVG.

Nota

With multi-page output, an atlas behaves like a layout in that only the page that contains the Configurações Gerais will get a world file (for each feature output).

Dica

Imprimir uma feição específica do atlas*

If you want to print or export the composition of only one feature of the atlas, simply start the preview, select the desired feature in the drop-down list and click on Layout ► Print (or Export… to any supported file format).

19.3.5.5. Utilizar as relações definidas pelo projeto para a criação do atlas

For users with HTML and Javascript knowledge it is possible to operate on GeoJSON objects and use project defined relations from the QGIS project. The difference between this approach and using expressions directly inserted into the HTML is that it gives you a full, unstructured GeoJSON feature to work with. This means that you can use existing Javascript libraries and functions that operate on GeoJSON feature representations.

The following code includes all related child features from the defined relation. Using the JavaScript setFeature function it allows you to make flexible HTML which represents relations in whatever format you like (lists, tables, etc). In the code sample, we create a dynamic bullet list of the related child features.

// Declare the two HTML div elements we will use for the parent feature id
// and information about the children
<div id="parent"></div>
<div id="my_children"></div>

<script type="text/javascript">
   function setFeature(feature)
   {
     // Show the parent feature's identifier (using its "ID" field)
     document.getElementById('parent').innerHTML = feature.properties.ID;
     //clear the existing relation contents
     document.getElementById('my_children').innerHTML = '';
     feature.properties.my_relation.forEach(function(child_feature) {
     // for each related child feature, create a list element
     // with the feature's name (using its "NAME" field)
       var node = document.createElement("li");
       node.appendChild(document.createTextNode(child_feature.NAME));
       document.getElementById('my_children').appendChild(node);
     });
   }
</script>

During atlas creation there will be an iteration over the coverage layer containing the parent features. On each page, you will see a bullet list of the related child features following the parent’s identifier.