[composer] add svg export with layers

This commit is contained in:
vmora 2014-04-15 14:41:16 +02:00 committed by Nyall Dawson
parent e6680a1c71
commit 0c19945c04
10 changed files with 409 additions and 29 deletions

View File

@ -401,6 +401,16 @@ class QgsComposerItem : QObject, QGraphicsRectItem
@note there is not setter since one can't manually set the id*/
QString uuid() const;
/**Get the number of layers that this item exports
@returns 0 if this item is to be placed on the same layer as the previous item
@note this method was added in version 2.4 */
int numberExportLayers() const;
/**Set the layer to export
@param layerIdx can be set to -1 to export all layerr and must be less than numberExportLayers()
@note this method was added in version 2.4 */
void setCurrentExportLayer( int layerIdx = -1 );
public slots:
/**Sets the item rotation
* @deprecated Use setItemRotation( double rotation ) instead

View File

@ -407,6 +407,11 @@ class QgsComposerMap : QgsComposerItem
/** Returns whether updates to the composer map are enabled. */
bool updatesEnabled() const;
/**Get the number of layers that this item exports
@returns 0 if this item is to be placed on the same layer as the previous item
@note this method was added in version 2.4 */
int numberExportLayers() const;
signals:
void extentChanged();

View File

@ -395,6 +395,11 @@ class QgsComposition : QGraphicsScene
/** Sets the current atlas mode of the composition. Returns false if the mode could not be changed. */
bool setAtlasMode( QgsComposition::AtlasMode mode );
/** Return pages in the correct order
@note composerItems(QList< QgsPaperItem* > &) may not return pages in the correct order
@note added in version 2.4*/
QList< QgsPaperItem* > pages();
public slots:
/**Casts object to the proper subclass type and calls corresponding itemAdded signal*/
void sendItemAddedSignal( QgsComposerItem* item );

View File

@ -55,6 +55,9 @@
#include "qgscursors.h"
#include "qgsmaplayeractionregistry.h"
#include "qgsgeometry.h"
#include "qgspaperitem.h"
#include "qgsmaplayerregistry.h"
#include "ui_qgssvgexportoptions.h"
#include <QCloseEvent>
#include <QCheckBox>
@ -1748,6 +1751,37 @@ void QgsComposer::on_mActionExportAsSVG_triggered()
exportCompositionAsSVG( QgsComposer::Single );
}
// utility class that will hide all items until it's destroyed
struct QgsItemTempHider
{
explicit QgsItemTempHider( const QList<QGraphicsItem *> & items )
{
QList<QGraphicsItem *>::const_iterator it = items.begin();
for ( ; it != items.end(); ++it )
{
mItemVisibility[*it] = ( *it )->isVisible();
( *it )->hide();
}
}
void hideAll()
{
QgsItemVisibilityHash::iterator it = mItemVisibility.begin();
for ( ; it != mItemVisibility.end(); ++it ) it.key()->hide();
}
~QgsItemTempHider()
{
QgsItemVisibilityHash::iterator it = mItemVisibility.begin();
for ( ; it != mItemVisibility.end(); ++it )
{
it.key()->setVisible( it.value() );
}
}
private:
Q_DISABLE_COPY( QgsItemTempHider )
typedef QHash<QGraphicsItem*, bool> QgsItemVisibilityHash;
QgsItemVisibilityHash mItemVisibility;
};
void QgsComposer::exportCompositionAsSVG( QgsComposer::OutputMode mode )
{
if ( containsWMSLayer() )
@ -1785,6 +1819,7 @@ void QgsComposer::exportCompositionAsSVG( QgsComposer::OutputMode mode )
QString outputFileName;
QString outputDir;
bool groupLayers = false;
if ( mode == QgsComposer::Single )
{
@ -1800,14 +1835,25 @@ void QgsComposer::exportCompositionAsSVG( QgsComposer::OutputMode mode )
outputFileName = file.path();
}
// open file dialog
outputFileName = QFileDialog::getSaveFileName(
this,
tr( "Choose a file name to save the map as" ),
outputFileName,
tr( "SVG Format" ) + " (*.svg *.SVG)" );
if ( outputFileName.isEmpty() )
return;
// open otions dialog
{
QDialog dialog;
Ui::QgsSvgExportOptionsDialog options;
options.setupUi( &dialog );
dialog.exec();
groupLayers = options.chkMapLayersAsGroup->isChecked();
}
if ( !outputFileName.endsWith( ".svg", Qt::CaseInsensitive ) )
{
outputFileName += ".svg";
@ -1834,10 +1880,12 @@ void QgsComposer::exportCompositionAsSVG( QgsComposer::OutputMode mode )
QSettings myQSettings;
QString lastUsedDir = myQSettings.value( "/UI/lastSaveAtlasAsSvgDir", "." ).toString();
// open file dialog
outputDir = QFileDialog::getExistingDirectory( this,
tr( "Directory where to save SVG files" ),
lastUsedDir,
QFileDialog::ShowDirsOnly );
if ( outputDir.isEmpty() )
{
return;
@ -1852,6 +1900,16 @@ void QgsComposer::exportCompositionAsSVG( QgsComposer::OutputMode mode )
return;
}
// open otions dialog
{
QDialog dialog;
Ui::QgsSvgExportOptionsDialog options;
options.setupUi( &dialog );
dialog.exec();
groupLayers = options.chkMapLayersAsGroup->isChecked();
}
myQSettings.setValue( "/UI/lastSaveAtlasAsSvgDir", outputDir );
}
@ -1907,32 +1965,142 @@ void QgsComposer::exportCompositionAsSVG( QgsComposer::OutputMode mode )
outputFileName = QDir( outputDir ).filePath( atlasMap->currentFilename() ) + ".svg";
}
for ( int i = 0; i < mComposition->numPages(); ++i )
if ( !groupLayers )
{
QSvgGenerator generator;
generator.setTitle( QgsProject::instance()->title() );
if ( i == 0 )
for ( int i = 0; i < mComposition->numPages(); ++i )
{
generator.setFileName( outputFileName );
QSvgGenerator generator;
generator.setTitle( QgsProject::instance()->title() );
if ( i == 0 )
{
generator.setFileName( outputFileName );
}
else
{
QFileInfo fi( outputFileName );
generator.setFileName( fi.absolutePath() + "/" + fi.baseName() + "_" + QString::number( i + 1 ) + "." + fi.suffix() );
}
//width in pixel
int width = ( int )( mComposition->paperWidth() * mComposition->printResolution() / 25.4 );
//height in pixel
int height = ( int )( mComposition->paperHeight() * mComposition->printResolution() / 25.4 );
generator.setSize( QSize( width, height ) );
generator.setViewBox( QRect( 0, 0, width, height ) );
generator.setResolution( mComposition->printResolution() ); //because the rendering is done in mm, convert the dpi
QPainter p( &generator );
mComposition->renderPage( &p, i );
p.end();
}
else
}
else
{
//width and height in pixel
const int width = ( int )( mComposition->paperWidth() * mComposition->printResolution() / 25.4 );
const int height = ( int )( mComposition->paperHeight() * mComposition->printResolution() / 25.4 );
QList< QgsPaperItem* > paperItems( mComposition->pages() ) ;
for ( int i = 0; i < mComposition->numPages(); ++i )
{
QDomDocument svg;
QDomNode svgDocRoot;
QgsPaperItem * paperItem = paperItems[i];
const QRectF paperRect = QRectF( paperItem->pos().x(),
paperItem->pos().y(),
paperItem->rect().width(),
paperItem->rect().height() );
QList<QGraphicsItem *> items = mComposition->items( paperRect,
Qt::IntersectsItemBoundingRect,
Qt::AscendingOrder );
if ( ! items.isEmpty()
&& dynamic_cast<QgsPaperGrid*>( items.last() )
&& !mComposition->gridVisible() ) items.pop_back();
QgsItemTempHider itemsHider( items );
int composerItemLayerIdx = 0;
QList<QGraphicsItem *>::const_iterator it = items.begin();
for ( unsigned svgLayerId = 1; it != items.end(); ++svgLayerId )
{
itemsHider.hideAll();
QgsComposerItem * composerItem = dynamic_cast<QgsComposerItem*>( *it );
QString layerName( "Layer " + QString::number( svgLayerId ) );
if ( composerItem && composerItem->numberExportLayers() )
{
composerItem->show();
composerItem->setCurrentExportLayer( composerItemLayerIdx );
++composerItemLayerIdx;
}
else
{
// show all items until the next item that renders on a separate layer
for ( ; it != items.end(); ++it )
{
composerItem = dynamic_cast<QgsComposerMap*>( *it );
if ( composerItem && composerItem->numberExportLayers() )
{
break;
}
else
{
( *it )->show();
}
}
}
QBuffer svgBuffer;
{
QSvgGenerator generator;
generator.setTitle( QgsProject::instance()->title() );
generator.setOutputDevice( &svgBuffer );
generator.setSize( QSize( width, height ) );
generator.setViewBox( QRect( 0, 0, width, height ) );
generator.setResolution( mComposition->printResolution() ); //because the rendering is done in mm, convert the dpi
QPainter p( &generator );
mComposition->renderPage( &p, i );
}
// post-process svg output to create groups in a single svg file
// we create inkscape layers since it's nice and clean and free
// and fully svg compatible
{
svgBuffer.close();
svgBuffer.open( QIODevice::ReadOnly );
QDomDocument doc;
QString errorMsg;
int errorLine;
if ( ! doc.setContent( &svgBuffer, false, &errorMsg, &errorLine ) )
QMessageBox::warning( 0, tr( "Svg error" ), tr( "There was an error in svg ouput for svg layer " ) + layerName + tr( " on page " ) + QString::number( i + 1 ) + "(" + errorMsg + ")" );
if ( 1 == svgLayerId )
{
svg = QDomDocument( doc.doctype() );
svg.appendChild( svg.importNode( doc.firstChild(), false ) );
svgDocRoot = svg.importNode( doc.elementsByTagName( "svg" ).at( 0 ), false );
svgDocRoot.toElement().setAttribute( "xmlns:inkscape", "http://www.inkscape.org/namespaces/inkscape" );
svg.appendChild( svgDocRoot );
}
QDomNode mainGroup = svg.importNode( doc.elementsByTagName( "g" ).at( 0 ), true );
mainGroup.toElement().setAttribute( "id", layerName );
mainGroup.toElement().setAttribute( "inkscape:label", layerName );
mainGroup.toElement().setAttribute( "inkscape:groupmode", "layer" );
QDomNode defs = svg.importNode( doc.elementsByTagName( "defs" ).at( 0 ), true );
svgDocRoot.appendChild( defs );
svgDocRoot.appendChild( mainGroup );
}
if ( composerItem && composerItem->numberExportLayers() && composerItem->numberExportLayers() == composerItemLayerIdx ) // restore and pass to next item
{
composerItem->setCurrentExportLayer();
composerItemLayerIdx = 0;
++it;
}
}
QFileInfo fi( outputFileName );
generator.setFileName( fi.absolutePath() + "/" + fi.baseName() + "_" + QString::number( i + 1 ) + "." + fi.suffix() );
QFile out( i == 0 ? outputFileName : fi.absolutePath() + "/" + fi.baseName() + "_" + QString::number( i + 1 ) + "." + fi.suffix() );
out.open( QIODevice::WriteOnly | QIODevice::Text );
out.write( svg.toByteArray() );
}
//width in pixel
int width = ( int )( mComposition->paperWidth() * mComposition->printResolution() / 25.4 );
//height in pixel
int height = ( int )( mComposition->paperHeight() * mComposition->printResolution() / 25.4 );
generator.setSize( QSize( width, height ) );
generator.setViewBox( QRect( 0, 0, width, height ) );
generator.setResolution( mComposition->printResolution() ); //because the rendering is done in mm, convert the dpi
QPainter p( &generator );
mComposition->renderPage( &p, i );
p.end();
}
featureI++;
}

View File

@ -64,6 +64,7 @@ QgsComposerItem::QgsComposerItem( QgsComposition* composition, bool manageZValue
, mEffectsEnabled( true )
, mTransparency( 0 )
, mLastUsedPositionMode( UpperLeft )
, mCurrentExportLayer( -1 )
, mId( "" )
, mUuid( QUuid::createUuid().toString() )
{
@ -88,6 +89,7 @@ QgsComposerItem::QgsComposerItem( qreal x, qreal y, qreal width, qreal height, Q
, mEffectsEnabled( true )
, mTransparency( 0 )
, mLastUsedPositionMode( UpperLeft )
, mCurrentExportLayer( -1 )
, mId( "" )
, mUuid( QUuid::createUuid().toString() )
{

View File

@ -361,6 +361,16 @@ class CORE_EXPORT QgsComposerItem: public QObject, public QGraphicsRectItem
@note there is not setter since one can't manually set the id*/
QString uuid() const { return mUuid; }
/**Get the number of layers that this item exports
@returns 0 if this item is to be placed on the same layer as the previous item
@note this method was added in version 2.4 */
virtual int numberExportLayers() const { return 0; }
/**Set the layer to export
@param layerIdx can be set to -1 to export all layerr and must be less than numberExportLayers()
@note this method was added in version 2.4 */
virtual void setCurrentExportLayer( int layerIdx = -1 ) { mCurrentExportLayer = layerIdx; }
public slots:
/**Sets the item rotation
* @deprecated Use setItemRotation( double rotation ) instead
@ -423,6 +433,11 @@ class CORE_EXPORT QgsComposerItem: public QObject, public QGraphicsRectItem
@note: this member was added in version 2.0*/
ItemPositionMode mLastUsedPositionMode;
/**The layer that needs to be exported
@note: if -1, all layers are to be exported
@note: this member was added in version 2.4*/
int mCurrentExportLayer;
/**Draw selection boxes around item*/
virtual void drawSelectionBoxes( QPainter* p );

View File

@ -182,7 +182,16 @@ void QgsComposerMap::draw( QPainter *painter, const QgsRectangle& extent, const
jobMapSettings.setBackgroundColor( Qt::transparent );
//set layers to render
jobMapSettings.setLayers( layersToRender() );
QStringList theLayerSet = layersToRender();
if ( -1 != mCurrentExportLayer )
{
const int layerIdx = mCurrentExportLayer - ( hasBackground() ? 1 : 0 );
theLayerSet =
( layerIdx >= 0 && layerIdx < theLayerSet.length() )
? QStringList( theLayerSet[ theLayerSet.length() - layerIdx - 1 ] )
: QStringList();
}
jobMapSettings.setLayers( theLayerSet );
jobMapSettings.setDestinationCrs( ms.destinationCrs() );
jobMapSettings.setCrsTransformEnabled( ms.hasCrsTransformEnabled() );
jobMapSettings.setFlags( ms.flags() );
@ -355,7 +364,10 @@ void QgsComposerMap::paint( QPainter* painter, const QStyleOptionGraphicsItem* i
}
// Fill with background color
drawBackground( painter );
if ( exportLayer( Background ) )
{
drawBackground( painter );
}
QgsRectangle requestRectangle;
requestedExtent( requestRectangle );
@ -395,16 +407,19 @@ void QgsComposerMap::paint( QPainter* painter, const QStyleOptionGraphicsItem* i
painter->setClipRect( thisPaintRect , Qt::NoClip );
if ( mGridEnabled )
if ( mGridEnabled && exportLayer( Grid ) )
{
drawGrid( painter );
}
if ( mOverviewFrameMapId != -1 )
if ( mOverviewFrameMapId != -1 && exportLayer( OverviewMapExtent ) )
{
drawOverviewMapExtent( painter );
}
drawFrame( painter );
if ( isSelected() )
if ( exportLayer( Frame ) )
{
drawFrame( painter );
}
if ( isSelected() && exportLayer( SelectionBoxes ) )
{
drawSelectionBoxes( painter );
}
@ -412,6 +427,50 @@ void QgsComposerMap::paint( QPainter* painter, const QStyleOptionGraphicsItem* i
painter->restore();
}
int QgsComposerMap::numberExportLayers() const
{
return
( hasBackground() ? 1 : 0 )
+ layersToRender().length()
+ ( mGridEnabled ? 1 : 0 )
+ ( mOverviewFrameMapId != -1 ? 1 : 0 )
+ ( hasFrame() ? 1 : 0 )
+ ( isSelected() ? 1 : 0 )
;
}
bool QgsComposerMap::exportLayer( ItemType type ) const
{
if ( -1 == mCurrentExportLayer ) return true;
int idx = numberExportLayers();
if ( isSelected() )
{
--idx;
if ( SelectionBoxes == type ) return mCurrentExportLayer == idx;
}
if ( hasFrame() )
{
--idx;
if ( Frame == type ) return mCurrentExportLayer == idx;
}
if ( mOverviewFrameMapId )
{
--idx;
if ( OverviewMapExtent == type ) return mCurrentExportLayer == idx;
}
if ( mGridEnabled )
{
--idx;
if ( Grid == type ) return mCurrentExportLayer == idx;
}
if ( hasBackground() )
{
if ( Background == type ) return mCurrentExportLayer == 0;
}
return true; // for Layer
}
void QgsComposerMap::updateCachedImage( void )
{
syncLayerSet(); //layer list may have changed
@ -440,7 +499,7 @@ const QgsMapRenderer *QgsComposerMap::mapRenderer() const
Q_NOWARN_DEPRECATED_POP
}
QStringList QgsComposerMap::layersToRender()
QStringList QgsComposerMap::layersToRender() const
{
//use stored layer set or read current set from main canvas
QStringList renderLayerSet;

View File

@ -445,6 +445,11 @@ class CORE_EXPORT QgsComposerMap : public QgsComposerItem
/** Returns whether updates to the composer map are enabled. */
bool updatesEnabled() const { return mUpdatesEnabled; }
/**Get the number of layers that this item exports
@returns 0 if this item is to be placed on the same layer as the previous item
@note this method was added in version 2.4 */
int numberExportLayers() const;
signals:
void extentChanged();
@ -606,7 +611,7 @@ class CORE_EXPORT QgsComposerMap : public QgsComposerItem
double mAtlasMargin;
/**Returns a list of the layers to render for this map item*/
QStringList layersToRender();
QStringList layersToRender() const;
/**Draws the map grid*/
void drawGrid( QPainter* p );
@ -665,6 +670,18 @@ class CORE_EXPORT QgsComposerMap : public QgsComposerItem
void createDefaultGridLineSymbol();
void initGridAnnotationFormatFromProject();
enum ItemType
{
Background,
Layer,
Grid,
OverviewMapExtent,
Frame,
SelectionBoxes
};
/**Test if this item needs to be exported considering mCurrentExportLayer*/
bool exportLayer( ItemType type ) const;
};
#endif

View File

@ -32,11 +32,11 @@
#include "qgsaddremoveitemcommand.h"
#include "qgscomposeritemcommand.h"
#include "qgsatlascomposition.h"
#include "qgspaperitem.h"
class QgisApp;
class QgsComposerFrame;
class QgsComposerMap;
class QgsPaperItem;
class QGraphicsRectItem;
class QgsMapRenderer;
class QDomElement;
@ -451,6 +451,11 @@ class CORE_EXPORT QgsComposition : public QGraphicsScene
/** Sets the current atlas mode of the composition. Returns false if the mode could not be changed. */
bool setAtlasMode( QgsComposition::AtlasMode mode );
/** Return pages in the correct order
@note composerItems(QList< QgsPaperItem* > &) may not return pages in the correct order
@note added in version 2.4*/
QList< QgsPaperItem* > pages() { return mPages; }
public slots:
/**Casts object to the proper subclass type and calls corresponding itemAdded signal*/
void sendItemAddedSignal( QgsComposerItem* item );

View File

@ -0,0 +1,94 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>QgsSvgExportOptionsDialog</class>
<widget class="QDialog" name="QgsSvgExportOptionsDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>675</width>
<height>170</height>
</rect>
</property>
<property name="windowTitle">
<string>SVG export options</string>
</property>
<widget class="QWidget" name="layoutWidget">
<property name="geometry">
<rect>
<x>10</x>
<y>20</y>
<width>604</width>
<height>101</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QCheckBox" name="chkMapLayersAsGroup">
<property name="text">
<string>Export map layers as svg groups (may affect label placement)</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkTextAsOutline">
<property name="enabled">
<bool>false</bool>
</property>
<property name="text">
<string>Render text as outline</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>QgsSvgExportOptionsDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>QgsSvgExportOptionsDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui>