QGIS API Documentation 4.3.0-Master (d3b565c628d)
Loading...
Searching...
No Matches
qgsalgorithmlayouttopdf.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmlayouttopdf.cpp
3 ---------------------
4 begin : June 2020
5 copyright : (C) 2020 by Nyall Dawson
6 email : nyall dot dawson 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
20#include "qgslayout.h"
21#include "qgslayoutexporter.h"
22#include "qgslayoutitemmap.h"
23#include "qgsprintlayout.h"
25
26#include <QString>
27
28using namespace Qt::StringLiterals;
29
31
32QString QgsLayoutToPdfAlgorithm::name() const
33{
34 return u"printlayouttopdf"_s;
35}
36
37QString QgsLayoutToPdfAlgorithm::displayName() const
38{
39 return QObject::tr( "Export print layout as PDF" );
40}
41
42QStringList QgsLayoutToPdfAlgorithm::tags() const
43{
44 return QObject::tr( "layout,composer,composition,save" ).split( ',' );
45}
46
47QString QgsLayoutToPdfAlgorithm::group() const
48{
49 return QObject::tr( "Cartography" );
50}
51
52QString QgsLayoutToPdfAlgorithm::groupId() const
53{
54 return u"cartography"_s;
55}
56
57QString QgsLayoutToPdfAlgorithm::shortDescription() const
58{
59 return QObject::tr( "Exports a print layout as a PDF." );
60}
61
62QString QgsLayoutToPdfAlgorithm::shortHelpString() const
63{
64 return QObject::tr( "This algorithm outputs a print layout as a PDF file." );
65}
66
67void QgsLayoutToPdfAlgorithm::initAlgorithm( const QVariantMap & )
68{
69 addParameter( new QgsProcessingParameterLayout( u"LAYOUT"_s, QObject::tr( "Print layout" ) ) );
70
71 auto layersParam
72 = std::make_unique<QgsProcessingParameterMultipleLayers>( u"LAYERS"_s, QObject::tr( "Map layers to assign to unlocked map item(s)" ), Qgis::ProcessingSourceType::MapLayer, QVariant(), true );
73 layersParam->setFlags( layersParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
74 addParameter( layersParam.release() );
75
76 auto dpiParam = std::make_unique<QgsProcessingParameterNumber>( u"DPI"_s, QObject::tr( "DPI (leave blank for default layout DPI)" ), Qgis::ProcessingNumberParameterType::Double, QVariant(), true, 0 );
77 dpiParam->setFlags( dpiParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
78 addParameter( dpiParam.release() );
79
80 auto forceVectorParam = std::make_unique<QgsProcessingParameterBoolean>( u"FORCE_VECTOR"_s, QObject::tr( "Always export as vectors" ), false );
81 forceVectorParam->setFlags( forceVectorParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
82 addParameter( forceVectorParam.release() );
83
84 auto forceRasterParam = std::make_unique<QgsProcessingParameterBoolean>( u"FORCE_RASTER"_s, QObject::tr( "Always export as raster" ), false );
85 forceRasterParam->setFlags( forceRasterParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
86 addParameter( forceRasterParam.release() );
87
88 auto appendGeorefParam = std::make_unique<QgsProcessingParameterBoolean>( u"GEOREFERENCE"_s, QObject::tr( "Append georeference information" ), true );
89 appendGeorefParam->setFlags( appendGeorefParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
90 addParameter( appendGeorefParam.release() );
91
92 auto exportRDFParam = std::make_unique<QgsProcessingParameterBoolean>( u"INCLUDE_METADATA"_s, QObject::tr( "Export RDF metadata (title, author, etc.)" ), true );
93 exportRDFParam->setFlags( exportRDFParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
94 addParameter( exportRDFParam.release() );
95
96 auto disableTiled = std::make_unique<QgsProcessingParameterBoolean>( u"DISABLE_TILED"_s, QObject::tr( "Disable tiled raster layer exports" ), false );
97 disableTiled->setFlags( disableTiled->flags() | Qgis::ProcessingParameterFlag::Advanced );
98 addParameter( disableTiled.release() );
99
100 auto simplify = std::make_unique<QgsProcessingParameterBoolean>( u"SIMPLIFY"_s, QObject::tr( "Simplify geometries to reduce output file size" ), true );
101 simplify->setFlags( simplify->flags() | Qgis::ProcessingParameterFlag::Advanced );
102 addParameter( simplify.release() );
103
104 const QStringList
105 textExportOptions { QObject::tr( "Always Export Text as Paths (Recommended)" ), QObject::tr( "Always Export Text as Text Objects" ), QObject::tr( "Prefer Exporting Text as Text Objects" ) };
106
107 auto textFormat = std::make_unique<QgsProcessingParameterEnum>( u"TEXT_FORMAT"_s, QObject::tr( "Text export" ), textExportOptions, false, 0 );
108 textFormat->setFlags( textFormat->flags() | Qgis::ProcessingParameterFlag::Advanced );
109 addParameter( textFormat.release() );
110
111 const QStringList imageCompressionOptions { QObject::tr( "Lossy (JPEG)" ), QObject::tr( "Lossless" ) };
112
113 auto imageCompression = std::make_unique<QgsProcessingParameterEnum>( u"IMAGE_COMPRESSION"_s, QObject::tr( "Image compression" ), imageCompressionOptions, false, 0 );
114 imageCompression->setFlags( imageCompression->flags() | Qgis::ProcessingParameterFlag::Advanced );
115 addParameter( imageCompression.release() );
116
117 auto layeredExport = std::make_unique<QgsProcessingParameterBoolean>( u"SEPARATE_LAYERS"_s, QObject::tr( "Export layers as separate PDF files" ), false );
118 layeredExport->setFlags( layeredExport->flags() | Qgis::ProcessingParameterFlag::Advanced );
119 addParameter( layeredExport.release() );
120
121 addParameter( new QgsProcessingParameterFileDestination( u"OUTPUT"_s, QObject::tr( "PDF file" ), QObject::tr( "PDF Format" ) + " (*.pdf *.PDF)" ) );
122}
123
124Qgis::ProcessingAlgorithmFlags QgsLayoutToPdfAlgorithm::flags() const
125{
127}
128
129QgsLayoutToPdfAlgorithm *QgsLayoutToPdfAlgorithm::createInstance() const
130{
131 return new QgsLayoutToPdfAlgorithm();
132}
133
134QVariantMap QgsLayoutToPdfAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
135{
136 QGS_MARK_ALGORITHM_SOURCE
137
138 // this needs to be done in main thread, layouts are not thread safe
139 QgsPrintLayout *l = parameterAsLayout( parameters, u"LAYOUT"_s, context );
140 if ( !l )
141 throw QgsProcessingException( QObject::tr( "Cannot find layout with name \"%1\"" ).arg( parameters.value( u"LAYOUT"_s ).toString() ) );
142 std::unique_ptr<QgsPrintLayout> layout( l->clone() );
143
144 const QList<QgsMapLayer *> layers = parameterAsLayerList( parameters, u"LAYERS"_s, context );
145 if ( layers.size() > 0 )
146 {
147 const QList<QGraphicsItem *> items = layout->items();
148 for ( QGraphicsItem *graphicsItem : items )
149 {
150 QgsLayoutItem *item = dynamic_cast<QgsLayoutItem *>( graphicsItem );
151 QgsLayoutItemMap *map = dynamic_cast<QgsLayoutItemMap *>( item );
152 if ( map && !map->followVisibilityPreset() && !map->keepLayerSet() )
153 {
154 map->setKeepLayerSet( true );
155 map->setLayers( layers );
156 }
157 }
158 }
159
160 const QString dest = parameterAsFileOutput( parameters, u"OUTPUT"_s, context );
161
162 QgsLayoutExporter exporter( layout.get() );
164
165 if ( parameters.value( u"DPI"_s ).isValid() )
166 {
167 settings.dpi = parameterAsDouble( parameters, u"DPI"_s, context );
168 }
169
170 settings.forceVectorOutput = parameterAsBool( parameters, u"FORCE_VECTOR"_s, context );
171 settings.rasterizeWholeImage = parameterAsBool( parameters, u"FORCE_RASTER"_s, context );
172 settings.appendGeoreference = parameterAsBool( parameters, u"GEOREFERENCE"_s, context );
173 settings.exportMetadata = parameterAsBool( parameters, u"INCLUDE_METADATA"_s, context );
174 settings.simplifyGeometries = parameterAsBool( parameters, u"SIMPLIFY"_s, context );
175 const int textFormat = parameterAsEnum( parameters, u"TEXT_FORMAT"_s, context );
176 switch ( textFormat )
177 {
178 case 0:
180 break;
181 case 1:
183 break;
184 case 2:
186 break;
187 default:
188 break;
189 }
190 settings.exportLayersAsSeperateFiles = parameterAsBool( parameters, u"SEPARATE_LAYERS"_s, context ); //#spellok
191
192 if ( parameterAsBool( parameters, u"DISABLE_TILED"_s, context ) )
194 else
195 settings.flags = settings.flags & ~static_cast< int >( Qgis::LayoutRenderFlag::DisableTiledRasterLayerRenders );
196
197 if ( parameterAsEnum( parameters, u"IMAGE_COMPRESSION"_s, context ) == 1 )
199 else
200 settings.flags = settings.flags & ~static_cast< int >( Qgis::LayoutRenderFlag::LosslessImageRendering );
201
202 switch ( exporter.exportToPdf( dest, settings ) )
203 {
205 {
206 feedback->pushInfo( QObject::tr( "Successfully exported layout to %1" ).arg( QDir::toNativeSeparators( dest ) ) );
207 break;
208 }
209
212 !exporter.errorMessage().isEmpty() ? exporter.errorMessage() : QObject::tr( "Cannot write to %1.\n\nThis file may be open in another application." ).arg( QDir::toNativeSeparators( dest ) )
213 );
214
216 throw QgsProcessingException( !exporter.errorMessage().isEmpty() ? exporter.errorMessage() : QObject::tr( "Could not create print device." ) );
217
220 !exporter.errorMessage().isEmpty() ? exporter.errorMessage()
221 : QObject::tr(
222 "Exporting the PDF "
223 "resulted in a memory overflow.\n\n"
224 "Please try a lower resolution or a smaller paper size."
225 )
226 );
227
231 // no meaning for PDF exports, will not be encountered
232 break;
233 }
234
235 feedback->setProgress( 100 );
236
237 QVariantMap outputs;
238 outputs.insert( u"OUTPUT"_s, dest );
239 return outputs;
240}
241
@ MapLayer
Any map layer type (raster, vector, mesh, point cloud, annotation or plugin layer).
Definition qgis.h:3748
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3826
@ PreferText
Render text as text objects, unless doing so results in rendering artifacts or poor quality rendering...
Definition qgis.h:3028
@ AlwaysOutlines
Always render text using path objects (AKA outlines/curves). This setting guarantees the best quality...
Definition qgis.h:3022
@ AlwaysText
Always render text as text objects. While this mode preserves text objects as text for post-processin...
Definition qgis.h:3025
@ NoThreading
Algorithm is not thread safe and cannot be run in a background thread, e.g. for algorithms which mani...
Definition qgis.h:3805
@ RequiresProject
The algorithm requires that a valid QgsProject is available from the processing context in order to e...
Definition qgis.h:3813
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3982
@ Double
Double/float values.
Definition qgis.h:4023
@ DisableTiledRasterLayerRenders
If set, then raster layers will not be drawn as separate tiles. This may improve the appearance in ex...
Definition qgis.h:5745
@ LosslessImageRendering
Render images losslessly whenever possible, instead of the default lossy jpeg rendering used for some...
Definition qgis.h:5749
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:65
Handles rendering and exports of layouts to various formats.
@ 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.
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.
Print layout, a QgsLayout subclass for static or atlas-based layouts.
virtual Qgis::ProcessingAlgorithmFlags 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.
Base class for providing feedback from a processing algorithm.
virtual void pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
A generic file based destination parameter, for specifying the destination path for a file (non-map l...
A print layout parameter, allowing users to select a print layout.
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 rasterizeWholeImage
Set to true to force whole layout to be rasterized while exporting.
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.
Qgis::LayoutRenderFlags 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.
bool exportLayersAsSeperateFiles
true if individual layers from the layout should be rendered to separate PDF files.
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....