QGIS API Documentation  3.24.2-Tisler (13c1a02865)
qgsalgorithmlayoutatlastopdf.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsalgorithmlayoutatlastopdf.cpp
3  ---------------------
4  begin : August 2020
5  copyright : (C) 2020 by Mathieu Pellerin
6  email : nirvn dot asia at gmail dot com
7  ***************************************************************************/
8 
9 /***************************************************************************
10  * *
11  * This program is free software; you can redistribute it and/or modify *
12  * it under the terms of the GNU General Public License as published by *
13  * the Free Software Foundation; either version 2 of the License, or *
14  * (at your option) any later version. *
15  * *
16  ***************************************************************************/
17 
19 #include "qgslayout.h"
20 #include "qgslayoutatlas.h"
21 #include "qgslayoutitemmap.h"
22 #include "qgslayoututils.h"
23 #include "qgsprintlayout.h"
24 #include "qgsprocessingoutputs.h"
25 #include "qgslayoutexporter.h"
26 
28 
29 // QgsLayoutAtlasToPdfAlgorithmBase
30 
31 QStringList QgsLayoutAtlasToPdfAlgorithmBase::tags() const
32 {
33  return QObject::tr( "layout,atlas,composer,composition,save" ).split( ',' );
34 }
35 
36 QString QgsLayoutAtlasToPdfAlgorithmBase::group() const
37 {
38  return QObject::tr( "Cartography" );
39 }
40 
41 QString QgsLayoutAtlasToPdfAlgorithmBase::groupId() const
42 {
43  return QStringLiteral( "cartography" );
44 }
45 
46 QgsProcessingAlgorithm::Flags QgsLayoutAtlasToPdfAlgorithmBase::flags() const
47 {
48  return QgsProcessingAlgorithm::flags() | FlagNoThreading;
49 }
50 
51 void QgsLayoutAtlasToPdfAlgorithmBase::initAlgorithm( const QVariantMap & )
52 {
53  addParameter( new QgsProcessingParameterLayout( QStringLiteral( "LAYOUT" ), QObject::tr( "Atlas layout" ) ) );
54 
55  addParameter( new QgsProcessingParameterVectorLayer( QStringLiteral( "COVERAGE_LAYER" ), QObject::tr( "Coverage layer" ), QList< int >(), QVariant(), true ) );
56  addParameter( new QgsProcessingParameterExpression( QStringLiteral( "FILTER_EXPRESSION" ), QObject::tr( "Filter expression" ), QString(), QStringLiteral( "COVERAGE_LAYER" ), true ) );
57  addParameter( new QgsProcessingParameterExpression( QStringLiteral( "SORTBY_EXPRESSION" ), QObject::tr( "Sort expression" ), QString(), QStringLiteral( "COVERAGE_LAYER" ), true ) );
58  addParameter( new QgsProcessingParameterBoolean( QStringLiteral( "SORTBY_REVERSE" ), QObject::tr( "Reverse sort order (used when a sort expression is provided)" ), false, true ) );
59 
60  std::unique_ptr< QgsProcessingParameterMultipleLayers > layersParam = std::make_unique< QgsProcessingParameterMultipleLayers>( QStringLiteral( "LAYERS" ), QObject::tr( "Map layers to assign to unlocked map item(s)" ), QgsProcessing::TypeMapLayer, QVariant(), true );
61  layersParam->setFlags( layersParam->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
62  addParameter( layersParam.release() );
63 
64  std::unique_ptr< QgsProcessingParameterNumber > dpiParam = std::make_unique< QgsProcessingParameterNumber >( QStringLiteral( "DPI" ), QObject::tr( "DPI (leave blank for default layout DPI)" ), QgsProcessingParameterNumber::Double, QVariant(), true, 0 );
65  dpiParam->setFlags( dpiParam->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
66  addParameter( dpiParam.release() );
67 
68  std::unique_ptr< QgsProcessingParameterBoolean > forceVectorParam = std::make_unique< QgsProcessingParameterBoolean >( QStringLiteral( "FORCE_VECTOR" ), QObject::tr( "Always export as vectors" ), false );
69  forceVectorParam->setFlags( forceVectorParam->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
70  addParameter( forceVectorParam.release() );
71 
72  std::unique_ptr< QgsProcessingParameterBoolean > appendGeorefParam = std::make_unique< QgsProcessingParameterBoolean >( QStringLiteral( "GEOREFERENCE" ), QObject::tr( "Append georeference information" ), true );
73  appendGeorefParam->setFlags( appendGeorefParam->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
74  addParameter( appendGeorefParam.release() );
75 
76  std::unique_ptr< QgsProcessingParameterBoolean > exportRDFParam = std::make_unique< QgsProcessingParameterBoolean >( QStringLiteral( "INCLUDE_METADATA" ), QObject::tr( "Export RDF metadata (title, author, etc.)" ), true );
77  exportRDFParam->setFlags( exportRDFParam->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
78  addParameter( exportRDFParam.release() );
79 
80  std::unique_ptr< QgsProcessingParameterBoolean > disableTiled = std::make_unique< QgsProcessingParameterBoolean >( QStringLiteral( "DISABLE_TILED" ), QObject::tr( "Disable tiled raster layer exports" ), false );
81  disableTiled->setFlags( disableTiled->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
82  addParameter( disableTiled.release() );
83 
84  std::unique_ptr< QgsProcessingParameterBoolean > simplify = std::make_unique< QgsProcessingParameterBoolean >( QStringLiteral( "SIMPLIFY" ), QObject::tr( "Simplify geometries to reduce output file size" ), true );
85  simplify->setFlags( simplify->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
86  addParameter( simplify.release() );
87 
88  const QStringList textExportOptions
89  {
90  QObject::tr( "Always Export Text as Paths (Recommended)" ),
91  QObject::tr( "Always Export Text as Text Objects" )
92  };
93 
94  std::unique_ptr< QgsProcessingParameterEnum > textFormat = std::make_unique< QgsProcessingParameterEnum >( QStringLiteral( "TEXT_FORMAT" ), QObject::tr( "Text export" ), textExportOptions, false, 0 );
95  textFormat->setFlags( textFormat->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
96  addParameter( textFormat.release() );
97 }
98 
99 QVariantMap QgsLayoutAtlasToPdfAlgorithmBase::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
100 {
101  // this needs to be done in main thread, layouts are not thread safe
102  QgsPrintLayout *l = parameterAsLayout( parameters, QStringLiteral( "LAYOUT" ), context );
103  if ( !l )
104  throw QgsProcessingException( QObject::tr( "Cannot find layout with name \"%1\"" ).arg( parameters.value( QStringLiteral( "LAYOUT" ) ).toString() ) );
105 
106  std::unique_ptr< QgsPrintLayout > layout( l->clone() );
107  QgsLayoutAtlas *atlas = layout->atlas();
108 
109  QString expression, error;
110  QgsVectorLayer *layer = parameterAsVectorLayer( parameters, QStringLiteral( "COVERAGE_LAYER" ), context );
111  if ( layer )
112  {
113  atlas->setEnabled( true );
114  atlas->setCoverageLayer( layer );
115 
116  expression = parameterAsString( parameters, QStringLiteral( "FILTER_EXPRESSION" ), context );
117  atlas->setFilterExpression( expression, error );
118  atlas->setFilterFeatures( !expression.isEmpty() && error.isEmpty() );
119  if ( !expression.isEmpty() && !error.isEmpty() )
120  {
121  throw QgsProcessingException( QObject::tr( "Error setting atlas filter expression" ) );
122  }
123  error.clear();
124 
125  expression = parameterAsString( parameters, QStringLiteral( "SORTBY_EXPRESSION" ), context );
126  if ( !expression.isEmpty() )
127  {
128  const bool sortByReverse = parameterAsBool( parameters, QStringLiteral( "SORTBY_REVERSE" ), context );
129  atlas->setSortFeatures( true );
130  atlas->setSortExpression( expression );
131  atlas->setSortAscending( !sortByReverse );
132  }
133  else
134  {
135  atlas->setSortFeatures( false );
136  }
137  }
138  else if ( !atlas->enabled() )
139  {
140  throw QgsProcessingException( QObject::tr( "Selected layout does not have atlas functionality enabled" ) );
141  }
142 
143  const QgsLayoutExporter exporter( layout.get() );
145 
146  if ( parameters.value( QStringLiteral( "DPI" ) ).isValid() )
147  {
148  settings.dpi = parameterAsDouble( parameters, QStringLiteral( "DPI" ), context );
149  }
150  settings.forceVectorOutput = parameterAsBool( parameters, QStringLiteral( "FORCE_VECTOR" ), context );
151  settings.appendGeoreference = parameterAsBool( parameters, QStringLiteral( "GEOREFERENCE" ), context );
152  settings.exportMetadata = parameterAsBool( parameters, QStringLiteral( "INCLUDE_METADATA" ), context );
153  settings.simplifyGeometries = parameterAsBool( parameters, QStringLiteral( "SIMPLIFY" ), context );
154  settings.textRenderFormat = parameterAsEnum( parameters, QStringLiteral( "TEXT_FORMAT" ), context ) == 0 ? Qgis::TextRenderFormat::AlwaysOutlines : Qgis::TextRenderFormat::AlwaysText;
155 
156  if ( parameterAsBool( parameters, QStringLiteral( "DISABLE_TILED" ), context ) )
158  else
159  settings.flags = settings.flags & ~QgsLayoutRenderContext::FlagDisableTiledRasterLayerRenders;
160 
161  settings.predefinedMapScales = QgsLayoutUtils::predefinedScales( layout.get() );
162 
163  const QList< QgsMapLayer * > layers = parameterAsLayerList( parameters, QStringLiteral( "LAYERS" ), context );
164  if ( layers.size() > 0 )
165  {
166  const QList<QGraphicsItem *> items = layout->items();
167  for ( QGraphicsItem *graphicsItem : items )
168  {
169  QgsLayoutItem *item = dynamic_cast<QgsLayoutItem *>( graphicsItem );
170  QgsLayoutItemMap *map = dynamic_cast<QgsLayoutItemMap *>( item );
171  if ( map && !map->followVisibilityPreset() && !map->keepLayerSet() )
172  {
173  map->setKeepLayerSet( true );
174  map->setLayers( layers );
175  }
176  }
177  }
178 
179  return exportAtlas( atlas, exporter, settings, parameters, context, feedback );
180 }
181 
182 //
183 // QgsLayoutAtlasToPdfAlgorithm
184 //
185 
186 QString QgsLayoutAtlasToPdfAlgorithm::name() const
187 {
188  return QStringLiteral( "atlaslayouttopdf" );
189 }
190 
191 QString QgsLayoutAtlasToPdfAlgorithm::displayName() const
192 {
193  return QObject::tr( "Export atlas layout as PDF (single file)" );
194 }
195 
196 QString QgsLayoutAtlasToPdfAlgorithm::shortDescription() const
197 {
198  return QObject::tr( "Exports an atlas layout as a single PDF file." );
199 }
200 
201 QString QgsLayoutAtlasToPdfAlgorithm::shortHelpString() const
202 {
203  return QObject::tr( "This algorithm outputs an atlas layout as a single PDF file.\n\n"
204  "If a coverage layer is set, the selected layout's atlas settings exposed in this algorithm "
205  "will be overwritten. In this case, an empty filter or sort by expression will turn those "
206  "settings off." );
207 }
208 
209 void QgsLayoutAtlasToPdfAlgorithm::initAlgorithm( const QVariantMap & )
210 {
211  QgsLayoutAtlasToPdfAlgorithmBase::initAlgorithm();
212  addParameter( new QgsProcessingParameterFileDestination( QStringLiteral( "OUTPUT" ), QObject::tr( "PDF file" ), QObject::tr( "PDF Format" ) + " (*.pdf *.PDF)" ) );
213 }
214 
215 QgsLayoutAtlasToPdfAlgorithm *QgsLayoutAtlasToPdfAlgorithm::createInstance() const
216 {
217  return new QgsLayoutAtlasToPdfAlgorithm();
218 }
219 
220 QVariantMap QgsLayoutAtlasToPdfAlgorithm::exportAtlas( QgsLayoutAtlas *atlas, const QgsLayoutExporter &exporter, const QgsLayoutExporter::PdfExportSettings &settings,
221  const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
222 {
223  Q_UNUSED( exporter )
224 
225  const QString dest = parameterAsFileOutput( parameters, QStringLiteral( "OUTPUT" ), context );
226 
227  QString error;
228  if ( atlas->updateFeatures() )
229  {
230  feedback->pushInfo( QObject::tr( "Exporting %n atlas feature(s)", "", atlas->count() ) );
231  switch ( QgsLayoutExporter::exportToPdf( atlas, dest, settings, error, feedback ) )
232  {
234  {
235  feedback->pushInfo( QObject::tr( "Successfully exported atlas to %1" ).arg( QDir::toNativeSeparators( dest ) ) );
236  break;
237  }
238 
240  throw QgsProcessingException( QObject::tr( "Cannot write to %1.\n\nThis file may be open in another application." ).arg( QDir::toNativeSeparators( dest ) ) );
241 
243  throw QgsProcessingException( QObject::tr( "Could not create print device." ) );
244 
246  throw QgsProcessingException( QObject::tr( "Trying to create the image "
247  "resulted in a memory overflow.\n\n"
248  "Please try a lower resolution or a smaller paper size." ) );
249 
251  throw QgsProcessingException( QObject::tr( "Error encountered while exporting atlas." ) );
252 
255  // no meaning for PDF exports, will not be encountered
256  break;
257  }
258  }
259  else
260  {
261  feedback->reportError( QObject::tr( "No atlas features found" ) );
262  }
263 
264  feedback->setProgress( 100 );
265 
266  QVariantMap outputs;
267  outputs.insert( QStringLiteral( "OUTPUT" ), dest );
268  return outputs;
269 }
270 
271 //
272 // QgsLayoutAtlasToMultiplePdfAlgorithm
273 //
274 
275 QString QgsLayoutAtlasToMultiplePdfAlgorithm::name() const
276 {
277  return QStringLiteral( "atlaslayouttomultiplepdf" );
278 }
279 
280 QString QgsLayoutAtlasToMultiplePdfAlgorithm::displayName() const
281 {
282  return QObject::tr( "Export atlas layout as PDF (multiple files)" );
283 }
284 
285 QString QgsLayoutAtlasToMultiplePdfAlgorithm::shortDescription() const
286 {
287  return QObject::tr( "Exports an atlas layout to multiple PDF files." );
288 }
289 
290 QString QgsLayoutAtlasToMultiplePdfAlgorithm::shortHelpString() const
291 {
292  return QObject::tr( "This algorithm outputs an atlas layout to multiple PDF files.\n\n"
293  "If a coverage layer is set, the selected layout's atlas settings exposed in this algorithm "
294  "will be overwritten. In this case, an empty filter or sort by expression will turn those "
295  "settings off.\n"
296  );
297 }
298 
299 void QgsLayoutAtlasToMultiplePdfAlgorithm::initAlgorithm( const QVariantMap & )
300 {
301  QgsLayoutAtlasToPdfAlgorithmBase::initAlgorithm();
302  addParameter( new QgsProcessingParameterExpression( QStringLiteral( "OUTPUT_FILENAME" ), QObject::tr( "Output filename" ), QString(), QStringLiteral( "COVERAGE_LAYER" ), true ) );
303  addParameter( new QgsProcessingParameterFile( QStringLiteral( "OUTPUT_FOLDER" ), QObject::tr( "Output folder" ), QgsProcessingParameterFile::Folder ) );
304 }
305 
306 QgsLayoutAtlasToMultiplePdfAlgorithm *QgsLayoutAtlasToMultiplePdfAlgorithm::createInstance() const
307 {
308  return new QgsLayoutAtlasToMultiplePdfAlgorithm();
309 }
310 
311 QVariantMap QgsLayoutAtlasToMultiplePdfAlgorithm::exportAtlas( QgsLayoutAtlas *atlas, const QgsLayoutExporter &exporter, const QgsLayoutExporter::PdfExportSettings &settings,
312  const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
313 {
314  Q_UNUSED( exporter )
315 
316  QString error;
317 
318  const QString filename = parameterAsString( parameters, QStringLiteral( "OUTPUT_FILENAME" ), context );
319  const QString destFolder = parameterAsFile( parameters, QStringLiteral( "OUTPUT_FOLDER" ), context );
320 
321  // the "atlas.pdf" part will be overridden, only the folder is important
322  const QString dest = QStringLiteral( "%1/atlas.pdf" ).arg( destFolder );
323 
324  if ( atlas->updateFeatures() )
325  {
326  feedback->pushInfo( QObject::tr( "Exporting %n atlas feature(s)", "", atlas->count() ) );
327 
329  if ( atlas->filenameExpression().isEmpty() && filename.isEmpty() )
330  {
331  atlas->setFilenameExpression( QStringLiteral( "'output_'||@atlas_featurenumber" ), error );
332  }
333  else if ( !filename.isEmpty() )
334  {
335  if ( !atlas->setFilenameExpression( filename, error ) )
336  {
337  throw QgsProcessingException( QObject::tr( "Output file name expression is not valid: %1" ).arg( error ) );
338  }
339  }
340 
341  result = QgsLayoutExporter::exportToPdfs( atlas, dest, settings, error, feedback );
342 
343  switch ( result )
344  {
346  {
347  feedback->pushInfo( QObject::tr( "Successfully exported atlas to %1" ).arg( QDir::toNativeSeparators( destFolder ) ) );
348  break;
349  }
350 
352  throw QgsProcessingException( QObject::tr( "Cannot write to %1.\n\nThis file may be open in another application." ).arg( QDir::toNativeSeparators( dest ) ) );
353 
355  throw QgsProcessingException( QObject::tr( "Could not create print device." ) );
356 
358  throw QgsProcessingException( QObject::tr( "Trying to create the image "
359  "resulted in a memory overflow.\n\n"
360  "Please try a lower resolution or a smaller paper size." ) );
361 
363  throw QgsProcessingException( QObject::tr( "Error encountered while exporting atlas." ) );
364 
367  // no meaning for PDF exports, will not be encountered
368  break;
369  }
370  }
371  else
372  {
373  feedback->reportError( QObject::tr( "No atlas features found" ) );
374  }
375 
376  feedback->setProgress( 100 );
377 
378  QVariantMap outputs;
379  outputs.insert( QStringLiteral( "OUTPUT_FOLDER" ), destFolder );
380  return outputs;
381 }
382 
384 
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition: qgsfeedback.h:63
Class used to render QgsLayout as an atlas, by iterating over the features from an associated vector ...
QString filenameExpression() const
Returns the filename expression used for generating output filenames for each atlas page.
void setCoverageLayer(QgsVectorLayer *layer)
Sets the coverage layer to use for the atlas features.
bool setFilterExpression(const QString &expression, QString &errorString)
Sets the expression used for filtering features in the coverage layer.
void setSortAscending(bool ascending)
Sets whether features should be sorted in an ascending order.
void setEnabled(bool enabled)
Sets whether the atlas is enabled.
bool enabled() const
Returns whether the atlas generation is enabled.
bool setFilenameExpression(const QString &expression, QString &errorString)
Sets the filename expression used for generating output filenames for each atlas page.
void setSortFeatures(bool enabled)
Sets whether features should be sorted in the atlas.
int count() const override
Returns the number of features to iterate over.
void setSortExpression(const QString &expression)
Sets the expression (or field name) to use for sorting features.
void setFilterFeatures(bool filtered)
Sets whether features should be filtered in the coverage layer.
int updateFeatures()
Requeries the current atlas coverage layer and applies filtering and sorting.
Handles rendering and exports of layouts to various formats.
ExportResult exportToPdf(const QString &filePath, const QgsLayoutExporter::PdfExportSettings &settings)
Exports the layout as a PDF to the filePath, using the specified export settings.
ExportResult
Result codes for exporting layouts.
@ Canceled
Export was canceled.
@ MemoryError
Unable to allocate memory required to export.
@ PrintError
Could not start printing to destination device.
@ IteratorError
Error iterating over layout.
@ FileError
Could not write to destination file, likely due to a lock held by another application.
@ Success
Export was successful.
@ SvgLayerError
Could not create layered SVG file.
static ExportResult exportToPdfs(QgsAbstractLayoutIterator *iterator, const QString &baseFilePath, const QgsLayoutExporter::PdfExportSettings &settings, QString &error, QgsFeedback *feedback=nullptr)
Exports a layout iterator to multiple PDF files, with the specified export settings.
Layout graphical items for displaying a map.
bool keepLayerSet() const
Returns whether a stored layer set should be used or the current layer set from the project associate...
void setKeepLayerSet(bool enabled)
Sets whether the stored layer set should be used or the current layer set of the associated project.
bool followVisibilityPreset() const
Returns whether the map should follow a map theme.
void setLayers(const QList< QgsMapLayer * > &layers)
Sets the stored layers set.
Base class for graphical items within a QgsLayout.
Stores information relating to the current rendering settings for a layout.
@ FlagDisableTiledRasterLayerRenders
If set, then raster layers will not be drawn as separate tiles. This may improve the appearance in ex...
static QVector< double > predefinedScales(const QgsLayout *layout)
Returns a list of predefined scales associated with a layout.
Print layout, a QgsLayout subclass for static or atlas-based layouts.
QgsPrintLayout * clone() const override
Creates a clone of the layout.
virtual Flags flags() const
Returns the flags indicating how and when the algorithm operates and should be exposed to users.
Contains information about the context in which a processing algorithm is executed.
Custom exception class for processing related exceptions.
Definition: qgsexception.h:83
Base class for providing feedback from a processing algorithm.
virtual void pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
virtual void reportError(const QString &error, bool fatalError=false)
Reports that the algorithm encountered an error while executing.
A boolean parameter for processing algorithms.
@ FlagAdvanced
Parameter is an advanced parameter which should be hidden from users by default.
An expression parameter for processing algorithms.
A generic file based destination parameter, for specifying the destination path for a file (non-map l...
An input file or folder parameter for processing algorithms.
A print layout parameter, allowing users to select a print layout.
A vector layer (with or without geometry) parameter for processing algorithms.
@ TypeMapLayer
Any map layer type (raster, vector, mesh, point cloud, annotation or plugin layer)
Definition: qgsprocessing.h:47
Represents a vector layer which manages a vector based data sets.
Contains settings relating to exporting layouts to PDF.
bool forceVectorOutput
Set to true to force vector object exports, even when the resultant appearance will differ from the l...
bool exportMetadata
Indicates whether PDF export should include metadata generated from the layout's project's metadata.
bool appendGeoreference
Indicates whether PDF export should append georeference data.
QgsLayoutRenderContext::Flags flags
Layout context flags, which control how the export will be created.
double dpi
Resolution to export layout at. If dpi <= 0 the default layout dpi will be used.
QVector< qreal > predefinedMapScales
A list of predefined scales to use with the layout.
bool simplifyGeometries
Indicates whether vector geometries should be simplified to avoid redundant extraneous detail,...
Qgis::TextRenderFormat textRenderFormat
Text rendering format, which controls how text should be rendered in the export (e....