31 #include <QTextStream>
50 const QList< QgsMapLayer * > layers = ms.
layers();
53 VectorComponentDetail detail;
54 detail.name = layer->name();
55 detail.mapLayerId = layer->id();
56 if (
const QgsVectorLayer *vl = qobject_cast< const QgsVectorLayer * >( layer ) )
58 detail.displayAttribute = vl->displayField();
60 mLayerDetails[ layer->id() ] = detail;
68 return mLayerDetails.value( layerId );
71 QMap< QString, VectorComponentDetail > mLayerDetails;
79 QgsMapRendererTaskRenderedFeatureHandler( QgsMapRendererTaskGeoPdfExporter *exporter,
const QgsMapSettings &settings )
80 : mExporter( exporter )
81 , mMapSettings( settings )
84 const double pageHeightPdfUnits = settings.
outputSize().height() * 72.0 / settings.
outputDpi();
85 mTransform = QTransform::fromTranslate( 0, pageHeightPdfUnits ).scale( 72.0 / mMapSettings.outputDpi(), -72.0 / mMapSettings.outputDpi() );
111 QgsMapRendererTaskGeoPdfExporter *mExporter =
nullptr;
114 QTransform mTransform;
122 :
QgsTask( fileFormat == QLatin1String(
"PDF" ) ? tr(
"Saving as PDF" ) : tr(
"Saving as image" ) )
124 , mFileName( fileName )
125 , mFileFormat( fileFormat )
126 , mForceRaster( forceRaster )
128 , mGeoPdfExportDetails( geoPdfExportDetails )
134 :
QgsTask( tr(
"Rendering to painter" ) )
145 qDeleteAll( mAnnotations );
146 mAnnotations.clear();
148 const auto constAnnotations = annotations;
151 mAnnotations << a->clone();
157 mDecorations = decorations;
165 mJob->cancelWithoutBlocking();
181 QList< QgsAbstractGeoPdfExporter::ComponentLayerDetail > pdfComponents;
189 component.
name = QStringLiteral(
"layer_%1" ).arg( outputLayer );
193 component.
sourcePdfPath = mGeoPdfExporter->generateTemporaryFilepath( QStringLiteral(
"layer_%1.pdf" ).arg( outputLayer ) );
194 pdfComponents << component;
198 printer.setOutputFormat( QPrinter::PdfFormat );
199 printer.setOrientation( QPrinter::Portrait );
201 QSizeF outputSize = mMapSettings.
outputSize();
202 printer.setPaperSize( outputSize * 25.4 / mMapSettings.
outputDpi(), QPrinter::Millimeter );
203 printer.setPageMargins( 0, 0, 0, 0, QPrinter::Millimeter );
204 printer.setResolution( mMapSettings.
outputDpi() );
206 QPainter p( &printer );
214 const double pageWidthMM = mMapSettings.
outputSize().width() * 25.4 / mMapSettings.
outputDpi();
215 const double pageHeightMM = mMapSettings.
outputSize().height() * 25.4 / mMapSettings.
outputDpi();
216 exportDetails.
pageSizeMm = QSizeF( pageWidthMM, pageHeightMM );
222 if ( mSaveWorldFile )
236 const bool res = mGeoPdfExporter->finalize( pdfComponents, mFileName, exportDetails );
237 mGeoPdfExporter.reset();
238 mTempPainter.reset();
247 mJob.reset(
nullptr );
256 const auto constMDecorations = mDecorations;
259 decoration->render( mMapSettings, context );
262 const auto constMAnnotations = mAnnotations;
268 if ( !annotation || !annotation->isVisible() )
272 if ( annotation->mapLayer() && !mMapSettings.
layers().contains( annotation->mapLayer() ) )
281 if ( annotation->hasFixedMapPosition() )
288 itemX = annotation->relativePosition().x() * mMapSettings.
outputSize().width();
289 itemY = annotation->relativePosition().y() * mMapSettings.
outputSize().height();
292 context.
painter()->translate( itemX, itemY );
294 annotation->render( context );
297 if ( !mFileName.isEmpty() )
301 if ( mFileFormat == QLatin1String(
"PDF" ) )
303 #ifndef QT_NO_PRINTER
307 pp.begin( mPrinter.get() );
308 QRectF rect( 0, 0, mImage.width(), mImage.height() );
309 pp.drawImage( rect, mImage, rect );
313 if ( mSaveWorldFile || mExportMetadata )
315 CPLSetThreadLocalConfigOption(
"GDAL_PDF_DPI", QString::number( mMapSettings.
outputDpi() ).toLocal8Bit().constData() );
319 if ( mSaveWorldFile )
321 double a, b,
c, d, e, f;
327 double geoTransform[6] = {
c, a, b, f, d, e };
328 GDALSetGeoTransform( outputDS.get(), geoTransform );
332 if ( mExportMetadata )
334 QString creationDateString;
336 if ( creationDateTime.isValid() )
338 creationDateString = QStringLiteral(
"D:%1" ).arg( mGeoPdfExportDetails.
creationDateTime.toString( QStringLiteral(
"yyyyMMddHHmmss" ) ) );
339 if ( creationDateTime.timeZone().isValid() )
341 int offsetFromUtc = creationDateTime.timeZone().offsetFromUtc( creationDateTime );
342 creationDateString += ( offsetFromUtc >= 0 ) ?
'+' :
'-';
343 offsetFromUtc = std::abs( offsetFromUtc );
344 int offsetHours = offsetFromUtc / 3600;
345 int offsetMins = ( offsetFromUtc % 3600 ) / 60;
346 creationDateString += QStringLiteral(
"%1'%2'" ).arg( offsetHours ).arg( offsetMins );
349 GDALSetMetadataItem( outputDS.get(),
"CREATION_DATE", creationDateString.toUtf8().constData(),
nullptr );
351 GDALSetMetadataItem( outputDS.get(),
"AUTHOR", mGeoPdfExportDetails.
author.toUtf8().constData(),
nullptr );
352 const QString creator = QStringLiteral(
"QGIS %1" ).arg(
Qgis::version() );
353 GDALSetMetadataItem( outputDS.get(),
"CREATOR", creator.toUtf8().constData(),
nullptr );
354 GDALSetMetadataItem( outputDS.get(),
"PRODUCER", creator.toUtf8().constData(),
nullptr );
355 GDALSetMetadataItem( outputDS.get(),
"SUBJECT", mGeoPdfExportDetails.
subject.toUtf8().constData(),
nullptr );
356 GDALSetMetadataItem( outputDS.get(),
"TITLE", mGeoPdfExportDetails.
title.toUtf8().constData(),
nullptr );
359 QStringList allKeywords;
360 for (
auto it = keywords.constBegin(); it != keywords.constEnd(); ++it )
362 allKeywords.append( QStringLiteral(
"%1: %2" ).arg( it.key(), it.value().join(
',' ) ) );
364 const QString keywordString = allKeywords.join(
';' );
365 GDALSetMetadataItem( outputDS.get(),
"KEYWORDS", keywordString.toUtf8().constData(),
nullptr );
368 CPLSetThreadLocalConfigOption(
"GDAL_PDF_DPI",
nullptr );
375 else if ( mFileFormat != QLatin1String(
"PDF" ) )
377 bool success = mImage.save( mFileName, mFileFormat.toLocal8Bit().data() );
384 if ( mSaveWorldFile )
386 QFileInfo info = QFileInfo( mFileName );
389 QString outputSuffix = info.suffix();
390 bool skipWorldFile =
false;
391 if ( outputSuffix == QLatin1String(
"tif" ) || outputSuffix == QLatin1String(
"tiff" ) )
396 skipWorldFile =
true;
397 double a, b,
c, d, e, f;
403 double geoTransform[] = {
c, a, b, f, d, e };
404 GDALSetGeoTransform( outputDS.get(), geoTransform );
409 if ( !skipWorldFile )
411 QString worldFileName = info.absolutePath() +
'/' + info.completeBaseName() +
'.'
412 + outputSuffix.at( 0 ) + outputSuffix.at( info.suffix().size() - 1 ) +
'w';
413 QFile worldFile( worldFileName );
415 if ( worldFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
417 QTextStream stream( &worldFile );
425 mTempPainter.reset();
426 #ifndef QT_NO_PRINTER
435 qDeleteAll( mAnnotations );
436 mAnnotations.clear();
444 void QgsMapRendererTask::prepare()
448 mGeoPdfExporter = qgis::make_unique< QgsMapRendererTaskGeoPdfExporter >( mMapSettings );
451 mRenderedFeatureHandler = qgis::make_unique< QgsMapRendererTaskRenderedFeatureHandler >(
static_cast< QgsMapRendererTaskGeoPdfExporter *
>( mGeoPdfExporter.get() ), mMapSettings );
455 const QList< QgsMapLayer * > layers = mMapSettings.
layers();
458 mLayerIdToLayerNameMap.insert( layer->id(), layer->name() );
459 mMapLayerOrder << layer->id();
467 mDestPainter = mPainter;
469 if ( mFileFormat == QLatin1String(
"PDF" ) )
471 #ifndef QT_NO_PRINTER
472 mPrinter.reset(
new QPrinter() );
473 mPrinter->setOutputFileName( mFileName );
474 mPrinter->setOutputFormat( QPrinter::PdfFormat );
475 mPrinter->setOrientation( QPrinter::Portrait );
477 QSizeF outputSize = mMapSettings.
outputSize();
478 mPrinter->setPaperSize( outputSize * 25.4 / mMapSettings.
outputDpi(), QPrinter::Millimeter );
479 mPrinter->setPageMargins( 0, 0, 0, 0, QPrinter::Millimeter );
480 mPrinter->setResolution( mMapSettings.
outputDpi() );
484 mTempPainter.reset(
new QPainter( mPrinter.get() ) );
485 mDestPainter = mTempPainter.get();
495 mImage = QImage( mMapSettings.
outputSize(), QImage::Format_ARGB32 );
496 if ( mImage.isNull() )
503 mImage.setDotsPerMeterX( 1000 * mMapSettings.
outputDpi() / 25.4 );
504 mImage.setDotsPerMeterY( 1000 * mMapSettings.
outputDpi() / 25.4 );
506 mTempPainter.reset(
new QPainter( &mImage ) );
507 mDestPainter = mTempPainter.get();
static QString version()
Version string.
Abstract base class for GeoPDF exporters.
Abstract base class for annotation items which are drawn over a map.
@ WKT_PREFERRED_GDAL
Preferred format for conversion of CRS to WKT for use with the GDAL library.
QString toWkt(WktVariant variant=WKT1_GDAL, bool multiline=false, int indentationWidth=4) const
Returns a WKT representation of this CRS.
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.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
A geometry is the spatial representation of a feature.
OperationResult transform(const QgsCoordinateTransform &ct, QgsCoordinateTransform::TransformDirection direction=QgsCoordinateTransform::ForwardTransform, bool transformZ=false) SIP_THROW(QgsCsException)
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.
Base class for all map layer types.
Job implementation that renders everything sequentially using a custom painter.
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.
@ ImageUnsupportedFormat
Format is unsupported on the platform.
@ ImageSaveFail
Image save failure.
@ ImageAllocationFail
Image allocation failure.
QgsMapRendererTask(const QgsMapSettings &ms, const QString &fileName, const QString &fileFormat=QString("PNG"), bool forceRaster=false, bool geoPdf=false, const QgsAbstractGeoPdfExporter::ExportDetails &geoPdfExportDetails=QgsAbstractGeoPdfExporter::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.
The QgsMapSettings class contains configuration for rendering of 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.
QgsRectangle extent() const
Returns geographical coordinates of the rectangle that should be rendered.
const QgsMapToPixel & mapToPixel() const
QList< QgsMapLayer * > layers() const
Returns the list of layers which will be rendered in the map.
double outputDpi() const
Returns the DPI (dots per inch) used for conversion between real world units (e.g.
QgsCoordinateReferenceSystem destinationCrs() const
Returns the destination coordinate reference system for the map render.
QgsPointXY toMapCoordinates(int x, int y) const
Transform device coordinates to map (world) coordinates.
A class to represent a 2D point.
A rectangle specified with double values.
double xMinimum() const SIP_HOLDGIL
Returns the x minimum value (left side of rectangle).
double yMinimum() const SIP_HOLDGIL
Returns the y minimum value (bottom side of rectangle).
double height() const SIP_HOLDGIL
Returns the height of the rectangle.
double width() const SIP_HOLDGIL
Returns the width of the rectangle.
Contains information about the context of a rendering operation.
QPainter * painter()
Returns the destination QPainter for the render operation.
QgsExpressionContext & expressionContext()
Gets the expression context.
void setPainterFlagsUsingContext(QPainter *painter=nullptr) const
Sets relevant flags on a destination painter, using the flags and settings currently defined for the ...
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 provider custom handlers for features rendered as part of a map render...
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.
virtual QSet< QString > usedAttributes(QgsVectorLayer *layer, const QgsRenderContext &context) const
Returns a list of attributes required by this handler, for the specified layer.
Scoped object for saving and restoring a QPainter object's state.
Abstract base class for long running background tasks.
virtual void cancel()
Notifies the task that it should terminate.
bool isCanceled() const
Will return true if task should terminate ASAP.
Represents a vector layer which manages a vector based data sets.
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
Contains details of a particular input component to be used during PDF composition.
QString sourcePdfPath
File path to the (already created) PDF to use as the source for this component layer.
QString mapLayerId
Associated map layer ID, or an empty string if this component layer is not associated with a map laye...
QPainter::CompositionMode compositionMode
Component composition mode.
QString name
User-friendly name for the generated PDF layer.
double opacity
Component opacity.
Contains details of a control point used during georeferencing GeoPDF outputs.
QgsAbstractMetadataBase::KeywordMap keywords
Metadata keyword map.
QMap< QString, QString > layerIdToPdfLayerTreeNameMap
Optional map of map layer ID to custom layer tree name to show in the created PDF file.
QDateTime creationDateTime
Metadata creation datetime.
QSizeF pageSizeMm
Page size, in millimeters.
QList< QgsAbstractGeoPdfExporter::GeoReferencedSection > georeferencedSections
List of georeferenced sections.
QString author
Metadata author tag.
bool includeFeatures
true if feature vector information (such as attributes) should be exported.
QStringList layerOrder
Optional list of layer IDs, in the order desired to appear in the generated GeoPDF file.
QString subject
Metadata subject tag.
QString title
Metadata title tag.
QgsRectangle pageBoundsMm
Bounds of the georeferenced section on the page, in millimeters.
QgsCoordinateReferenceSystem crs
Coordinate reference system for georeferenced section.
QList< QgsAbstractGeoPdfExporter::ControlPoint > controlPoints
List of control points corresponding to this georeferenced section.
Contains information about a feature rendered inside the PDF.
Contains information relating to a single PDF layer in the GeoPDF export.
const QgsRenderContext & renderContext
The render context which was used while rendering feature.