36#include <QImageWriter>
42#include "moc_qgsmaprenderertask.cpp"
44using namespace Qt::StringLiterals;
53 QgsMapRendererTaskGeospatialPdfExporter(
const QgsMapSettings &ms )
56 const QList< QgsMapLayer * > layers = ms.
layers();
57 for (
const QgsMapLayer *layer : layers )
59 VectorComponentDetail detail;
60 detail.name = layer->name();
61 detail.mapLayerId = layer->id();
62 if (
const QgsVectorLayer *vl = qobject_cast< const QgsVectorLayer * >( layer ) )
64 detail.displayAttribute = vl->displayField();
66 mLayerDetails[ layer->id() ] = detail;
72 QgsAbstractGeospatialPdfExporter::VectorComponentDetail componentDetailForLayerId(
const QString &layerId )
override
74 return mLayerDetails.value( layerId );
77 QMap< QString, VectorComponentDetail > mLayerDetails;
85 QgsMapRendererTaskRenderedFeatureHandler( QgsMapRendererTaskGeospatialPdfExporter *exporter,
const QgsMapSettings &settings )
86 : mExporter( exporter )
87 , mMapSettings( settings )
90 const double pageHeightPdfUnits = settings.
outputSize().height() * 72.0 / settings.
outputDpi();
91 mTransform = QTransform::fromTranslate( 0, pageHeightPdfUnits ).scale( 72.0 / mMapSettings.outputDpi(), -72.0 / mMapSettings.outputDpi() );
94 void handleRenderedFeature(
const QgsFeature &feature,
const QgsGeometry &renderedBounds,
const QgsRenderedFeatureHandlerInterface::RenderedFeatureContext &context )
override
101 QgsGeometry transformed = renderedBounds;
107 mExporter->pushRenderedFeature( layerId, QgsAbstractGeospatialPdfExporter::RenderedFeature( feature, transformed ) );
110 QSet<QString>
usedAttributes( QgsVectorLayer *,
const QgsRenderContext & )
const override
117 QgsMapRendererTaskGeospatialPdfExporter *mExporter =
nullptr;
118 QgsMapSettings mMapSettings;
120 QTransform mTransform;
128 :
QgsTask( fileFormat ==
"PDF"_L1 ? tr(
"Saving as PDF" ) : tr(
"Saving as image" ),
flags )
130 , mFileName( fileName )
131 , mFileFormat( fileFormat )
132 , mForceRaster( forceRaster )
134 , mGeospatialPdfExportDetails( geospatialPdfExportDetails )
136 if ( mFileFormat ==
"PDF"_L1 && !
qgsDoubleNear( mMapSettings.devicePixelRatio(), 1.0 ) )
138 mMapSettings.setOutputSize( mMapSettings.outputSize() * mMapSettings.devicePixelRatio() );
139 mMapSettings.setOutputDpi( mMapSettings.outputDpi() * mMapSettings.devicePixelRatio() );
140 mMapSettings.setDevicePixelRatio( 1.0 );
146 :
QgsTask( tr(
"Rendering to painter" ) )
157 qDeleteAll( mAnnotations );
158 mAnnotations.clear();
160 const auto constAnnotations = annotations;
163 mAnnotations << a->clone();
169 mDecorations = decorations;
177 mJob->cancelWithoutBlocking();
188 if ( mGeospatialPDF )
190 QList< QgsAbstractGeospatialPdfExporter::ComponentLayerDetail > pdfComponents;
198 component.
name = u
"layer_%1"_s.arg( outputLayer );
202 component.
sourcePdfPath = mGeospatialPdfExporter->generateTemporaryFilepath( u
"layer_%1.pdf"_s.arg( outputLayer ) );
203 pdfComponents << component;
206 pdfWriter.setPageOrientation( QPageLayout::Orientation::Portrait );
208 const QSizeF outputSize = mMapSettings.outputSize();
209 const QPageSize pageSize( outputSize * 25.4 / mMapSettings.outputDpi(), QPageSize::Unit::Millimeter );
210 pdfWriter.setPageSize( pageSize );
211 pdfWriter.setPageMargins( QMarginsF( 0, 0, 0, 0 ) );
212 pdfWriter.setResolution(
static_cast<int>( mMapSettings.outputDpi() ) );
214 QPainter p( &pdfWriter );
222 const double pageWidthMM = mMapSettings.outputSize().width() * 25.4 / mMapSettings.outputDpi();
223 const double pageHeightMM = mMapSettings.outputSize().height() * 25.4 / mMapSettings.outputDpi();
224 exportDetails.
pageSizeMm = QSizeF( pageWidthMM, pageHeightMM );
225 exportDetails.
dpi = mMapSettings.outputDpi();
230 if ( mSaveWorldFile )
234 georef.
crs = mMapSettings.destinationCrs();
244 const bool res = mGeospatialPdfExporter->finalize( pdfComponents, mFileName, exportDetails );
245 mGeospatialPdfExporter.reset();
246 mTempPainter.reset();
254 mJob.reset(
nullptr );
263 const auto constMDecorations = mDecorations;
266 decoration->render( mMapSettings, context );
269 const auto constMAnnotations = mAnnotations;
275 if ( !annotation || !annotation->isVisible() )
279 if ( annotation->mapLayer() && !mMapSettings.layers().contains( annotation->mapLayer() ) )
288 if ( annotation->hasFixedMapPosition() )
290 itemX = mMapSettings.outputSize().width() * ( annotation->mapPosition().x() - mMapSettings.extent().xMinimum() ) / mMapSettings.extent().width();
291 itemY = mMapSettings.outputSize().height() * ( 1 - ( annotation->mapPosition().y() - mMapSettings.extent().yMinimum() ) / mMapSettings.extent().height() );
295 itemX = annotation->relativePosition().x() * mMapSettings.outputSize().width();
296 itemY = annotation->relativePosition().y() * mMapSettings.outputSize().height();
299 context.
painter()->translate( itemX, itemY );
301 annotation->render( context );
304 if ( !mFileName.isEmpty() )
308 if ( mFileFormat ==
"PDF"_L1 )
313 pp.begin( mPdfWriter.get() );
314 const QRectF rect( 0, 0, mImage.width(), mImage.height() );
315 pp.drawImage( rect, mImage, rect );
319 if ( mSaveWorldFile || mExportMetadata )
321 CPLSetThreadLocalConfigOption(
"GDAL_PDF_DPI", QString::number( mMapSettings.outputDpi() ).toLocal8Bit().constData() );
325 if ( mSaveWorldFile )
327 double a, b,
c, d, e, f;
333 double geoTransform[6] = {
c, a, b, f, d, e };
334 GDALSetGeoTransform( outputDS.get(), geoTransform );
338 if ( mExportMetadata )
340 QString creationDateString;
341 const QDateTime creationDateTime = mGeospatialPdfExportDetails.creationDateTime;
342#if QT_FEATURE_timezone > 0
343 if ( creationDateTime.isValid() )
345 creationDateString = u
"D:%1"_s.arg( mGeospatialPdfExportDetails.creationDateTime.toString( u
"yyyyMMddHHmmss"_s ) );
346 if ( creationDateTime.timeZone().isValid() )
348 int offsetFromUtc = creationDateTime.timeZone().offsetFromUtc( creationDateTime );
349 creationDateString += ( offsetFromUtc >= 0 ) ?
'+' :
'-';
350 offsetFromUtc = std::abs( offsetFromUtc );
351 const int offsetHours = offsetFromUtc / 3600;
352 const int offsetMins = ( offsetFromUtc % 3600 ) / 60;
353 creationDateString += u
"%1'%2'"_s.arg( offsetHours ).arg( offsetMins );
357 QgsDebugError( u
"Qt is built without timezone support, skipping timezone for pdf export"_s );
359 GDALSetMetadataItem( outputDS.get(),
"CREATION_DATE", creationDateString.toUtf8().constData(),
nullptr );
361 GDALSetMetadataItem( outputDS.get(),
"AUTHOR", mGeospatialPdfExportDetails.author.toUtf8().constData(),
nullptr );
363 GDALSetMetadataItem( outputDS.get(),
"CREATOR", creator.toUtf8().constData(),
nullptr );
364 GDALSetMetadataItem( outputDS.get(),
"PRODUCER", creator.toUtf8().constData(),
nullptr );
365 GDALSetMetadataItem( outputDS.get(),
"SUBJECT", mGeospatialPdfExportDetails.subject.toUtf8().constData(),
nullptr );
366 GDALSetMetadataItem( outputDS.get(),
"TITLE", mGeospatialPdfExportDetails.title.toUtf8().constData(),
nullptr );
369 QStringList allKeywords;
370 for (
auto it = keywords.constBegin(); it != keywords.constEnd(); ++it )
372 allKeywords.append( u
"%1: %2"_s.arg( it.key(), it.value().join(
',' ) ) );
374 const QString keywordString = allKeywords.join(
';' );
375 GDALSetMetadataItem( outputDS.get(),
"KEYWORDS", keywordString.toUtf8().constData(),
nullptr );
378 CPLSetThreadLocalConfigOption(
"GDAL_PDF_DPI",
nullptr );
381 else if ( mFileFormat !=
"PDF"_L1 )
383 QImageWriter writer( mFileName, mFileFormat.toLocal8Bit().data() );
384 if ( mFileFormat.compare(
"TIF"_L1, Qt::CaseInsensitive ) == 0 || mFileFormat.compare(
"TIFF"_L1, Qt::CaseInsensitive ) == 0 )
387 writer.setCompression( 1 );
389 const bool success = writer.write( mImage );
396 if ( mSaveWorldFile )
398 const QFileInfo info = QFileInfo( mFileName );
401 const QString outputSuffix = info.suffix();
402 bool skipWorldFile =
false;
403 if ( outputSuffix.compare(
"TIF"_L1, Qt::CaseInsensitive ) == 0 || outputSuffix.compare(
"TIFF"_L1, Qt::CaseInsensitive ) == 0 )
408 skipWorldFile =
true;
409 double a, b,
c, d, e, f;
415 double geoTransform[] = {
c, a, b, f, d, e };
416 GDALSetGeoTransform( outputDS.get(), geoTransform );
421 if ( !skipWorldFile )
423 const QString worldFileName = info.absolutePath() +
'/' + info.completeBaseName() +
'.'
424 + outputSuffix.at( 0 ) + outputSuffix.at( info.suffix().size() - 1 ) +
'w';
425 QFile worldFile( worldFileName );
427 if ( worldFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
429 QTextStream stream( &worldFile );
437 mTempPainter.reset();
445 qDeleteAll( mAnnotations );
446 mAnnotations.clear();
454void QgsMapRendererTask::prepare()
456 if ( mGeospatialPDF )
458 mGeospatialPdfExporter = std::make_unique< QgsMapRendererTaskGeospatialPdfExporter >( mMapSettings );
461 mRenderedFeatureHandler = std::make_unique< QgsMapRendererTaskRenderedFeatureHandler >(
static_cast< QgsMapRendererTaskGeospatialPdfExporter *
>( mGeospatialPdfExporter.get() ), mMapSettings );
465 const QList< QgsMapLayer * > layers = mMapSettings.layers();
466 for (
const QgsMapLayer *layer : layers )
468 mLayerIdToLayerNameMap.insert( layer->id(), layer->name() );
469 mMapLayerOrder << layer->id();
477 mDestPainter = mPainter;
479 if ( mFileFormat ==
"PDF"_L1 )
481 mPdfWriter = std::make_unique<QPdfWriter>( mFileName );
482 mPdfWriter->setPageOrientation( QPageLayout::Orientation::Portrait );
484 const QSizeF outputSize = mMapSettings.outputSize();
485 const QPageSize pageSize( outputSize * 25.4 / mMapSettings.outputDpi(), QPageSize::Unit::Millimeter );
486 mPdfWriter->setPageSize( pageSize );
487 mPdfWriter->setPageMargins( QMarginsF( 0, 0, 0, 0 ) );
488 mPdfWriter->setResolution(
static_cast<int>( mMapSettings.outputDpi() ) );
492 mTempPainter = std::make_unique<QPainter>( mPdfWriter.get() );
493 mDestPainter = mTempPainter.get();
500 mImage = QImage( mMapSettings.outputSize() * mMapSettings.devicePixelRatio(), QImage::Format_ARGB32 );
501 if ( mImage.isNull() )
508 mImage.setDevicePixelRatio( mMapSettings.devicePixelRatio() );
509 mImage.setDotsPerMeterX( 1000 * mMapSettings.outputDpi() / 25.4 );
510 mImage.setDotsPerMeterY( 1000 * mMapSettings.outputDpi() / 25.4 );
512 mTempPainter = std::make_unique<QPainter>( &mImage );
513 mDestPainter = mTempPainter.get();
522 mJob = std::make_unique<QgsMapRendererCustomPainterJob>( mMapSettings, mDestPainter );
523 static_cast< QgsMapRendererCustomPainterJob *
>( mJob.get() )->prepare();
static QString version()
Version string.
@ PreferredGdal
Preferred format for conversion of CRS to WKT for use with the GDAL library.
Abstract base class for Geospatial PDF exporters.
Abstract base class for annotation items which are drawn over a map.
QVariant variable(const QString &name) const
Fetches a matching variable from the context.
static const QString ALL_ATTRIBUTES
A special attribute that if set matches all attributes.
Qgis::GeometryOperationResult transform(const QgsCoordinateTransform &ct, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool transformZ=false)
Transforms this geometry as described by the coordinate transform ct.
bool convertToMultiType()
Converts single type geometry into multitype geometry e.g.
Interface for map decorations.
Job implementation that renders everything sequentially using a custom painter.
void renderPrepared()
Render a pre-prepared job.
Render job implementation that renders maps in stages, allowing different stages (e....
double currentLayerOpacity() const
Returns the opacity for the current layer about to be rendered in the next render operation.
@ RenderLabelsByMapLayer
Labels should be rendered in individual stages by map layer. This allows separation of labels belongi...
QPainter::CompositionMode currentLayerCompositionMode() const
Returns the composition mode for the current layer about to be rendered in the next render operation.
QString currentLayerId() const
Returns the ID of the current layer about to be rendered in the next render operation.
bool isFinished() const
Returns true if the job is finished, and nothing remains to render.
bool nextPart()
Iterates to the next part to render.
bool renderCurrentPart(QPainter *painter)
Renders the current part of the map to the specified painter.
void addDecorations(const QList< QgsMapDecoration * > &decorations)
Adds decorations to be rendered on the map.
bool run() override
Performs the task's operation.
void errorOccurred(int error)
Emitted when map rendering failed.
@ ImageSaveFail
Image save failure.
@ ImageAllocationFail
Image allocation failure.
QgsMapRendererTask(const QgsMapSettings &ms, const QString &fileName, const QString &fileFormat=QString("PNG"), bool forceRaster=false, QgsTask::Flags flags=QgsTask::CanCancel, bool geospatialPdf=false, const QgsAbstractGeospatialPdfExporter::ExportDetails &geospatialPdfExportDetails=QgsAbstractGeospatialPdfExporter::ExportDetails())
Constructor for QgsMapRendererTask to render a map to an image file.
void addAnnotations(const QList< QgsAnnotation * > &annotations)
Adds annotations to be rendered on the map.
void finished(bool result) override
If the task is managed by a QgsTaskManager, this will be called after the task has finished (whether ...
~QgsMapRendererTask() override
void cancel() override
Notifies the task that it should terminate.
void renderingComplete()
Emitted when the map rendering is successfully completed.
static void worldFileParameters(const QgsMapSettings &mapSettings, double &a, double &b, double &c, double &d, double &e, double &f)
Computes the six parameters of a world file.
static QString worldFileContent(const QgsMapSettings &mapSettings)
Creates the content of a world file.
Contains configuration for rendering maps.
QList< QgsMapLayer * > layers(bool expandGroupLayers=false) const
Returns the list of layers which will be rendered in the map.
void addRenderedFeatureHandler(QgsRenderedFeatureHandlerInterface *handler)
Adds a rendered feature handler to use while rendering the map settings.
QSize outputSize() const
Returns the size of the resulting map image, in pixels.
double outputDpi() const
Returns the DPI (dots per inch) used for conversion between real world units (e.g.
A rectangle specified with double values.
Contains information about the context of a rendering operation.
QPainter * painter()
Returns the destination QPainter for the render operation.
void setPainterFlagsUsingContext(QPainter *painter=nullptr) const
Sets relevant flags on a destination painter, using the flags and settings currently defined for the ...
QgsExpressionContext & expressionContext()
Gets the expression context.
void setPainter(QPainter *p)
Sets the destination QPainter for the render operation.
static QgsRenderContext fromMapSettings(const QgsMapSettings &mapSettings)
create initialized QgsRenderContext instance from given QgsMapSettings
An interface for classes which provide custom handlers for features rendered as part of a map render ...
virtual QSet< QString > usedAttributes(QgsVectorLayer *layer, const QgsRenderContext &context) const
Returns a list of attributes required by this handler, for the specified layer.
virtual void handleRenderedFeature(const QgsFeature &feature, const QgsGeometry &renderedBounds, const QgsRenderedFeatureHandlerInterface::RenderedFeatureContext &context)=0
Called whenever a feature is rendered during a map render job.
Scoped object for saving and restoring a QPainter object's state.
Flags flags() const
Returns the flags associated with the task.
virtual void cancel()
Notifies the task that it should terminate.
QgsTask(const QString &description=QString(), QgsTask::Flags flags=AllFlags)
Constructor for QgsTask.
bool isCanceled() const
Will return true if task should terminate ASAP.
std::unique_ptr< std::remove_pointer< GDALDatasetH >::type, GDALDatasetCloser > dataset_unique_ptr
Scoped GDAL dataset.
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into c
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
#define QgsDebugError(str)
Contains details of a particular input component to be used during PDF composition.
QString mapLayerId
Associated map layer ID, or an empty string if this component layer is not associated with a map laye...
double opacity
Component opacity.
QString name
User-friendly name for the generated PDF layer.
QPainter::CompositionMode compositionMode
Component composition mode.
QString sourcePdfPath
File path to the (already created) PDF to use as the source for this component layer.
Contains details of a control point used during georeferencing Geospatial PDF outputs.
QList< QgsAbstractGeospatialPdfExporter::GeoReferencedSection > georeferencedSections
List of georeferenced sections.
QStringList layerOrder
Optional list of layer IDs, in the order desired to appear in the generated Geospatial PDF file.
QMap< QString, QString > layerIdToPdfLayerTreeNameMap
Optional map of map layer ID to custom layer tree name to show in the created PDF file.
QSizeF pageSizeMm
Page size, in millimeters.
bool includeFeatures
true if feature vector information (such as attributes) should be exported.
QgsRectangle pageBoundsMm
Bounds of the georeferenced section on the page, in millimeters.
QgsCoordinateReferenceSystem crs
Coordinate reference system for georeferenced section.
QList< QgsAbstractGeospatialPdfExporter::ControlPoint > controlPoints
List of control points corresponding to this georeferenced section.
const QgsRenderContext & renderContext
The render context which was used while rendering feature.