QGIS导出作曲家在python中为pdf


11

我有一个包含作曲家的QGIS项目。当然,如果进入GUI,我可以将其导出为pdf等。对于我的make脚本,尽管我想通过python脚本来完成。通过在线阅读,这是我的尝试:

#!/usr/bin/env python

import sys
from qgis.gui import QgsMapCanvas, QgsLayerTreeMapCanvasBridge
from PyQt4.QtCore import QFileInfo
from PyQt4.QtXml import QDomDocument
from qgis.core import *

qgs = QgsApplication(sys.argv, True) 
QgsApplication.setPrefixPath("/usr", True) 

qgs.initQgis()

def make_pdf():
  canvas = QgsMapCanvas()
  bridge = QgsLayerTreeMapCanvasBridge(
      QgsProject.instance().layerTreeRoot(), canvas)
  bridge.setCanvasLayers()
  QgsProject.instance().read(QFileInfo('../board.qgs'))

  composition = QgsComposition(canvas.mapSettings())
  map_item = composition.getComposerItemById('board36x48')
  map_item.setMapCanvas(canvas)
  map_item.zoomToExtent(canvas.extent())
  composition.refreshItems()
  composition.exportAsPDF('generated/board.pdf')
  QgsProject.instance().clear()

make_pdf()

这将失败,特别是:

i:./assets/generate_board 
QGraphicsScene::addItem: item has already been added to this scene
Traceback (most recent call last):
  File "./assets/generate_board", line 30, in <module>
    make_pdf()
  File "./assets/generate_board", line 24, in make_pdf
    map_item.setMapCanvas(canvas)
AttributeError: 'NoneType' object has no attribute 'setMapCanvas'

我基于使用Python(不更改可见布局中的任何内容)将“打印打印/地图QGIS编辑器”视图保存为PNG / PDF?但对其进行了修改,以尽可能简化。好像我在此过程中破坏了某些东西...我没有此模板文件。我简单地拥有一个带composer board36x48的board.qgs项目文件。有任何想法吗?


尝试更换qgs = QgsApplication(sys.argv, True)app = QtGui.QApplication(sys.argv, True)qgs.initQgis()QgsApplication.initQgis()
约瑟夫

您可能会在Maps_printer插件中找到一些有用的代码:github.com/DelazJ/MapsPrinter/wiki。寻找def saveFile(self):、 def printToRaster(自身,cView,文件夹,名称,ext):、 def exportCompo(自身,cView,文件夹,标题,扩展名):
gisnside

你有工作吗?
Hugo Roussaffa-GeoDatup

Answers:


1

您正在尝试使用完整的作曲家名称创建QgsComposerMap项!

map_item = composition.getComposerItemById('board36x48')

改用您的作曲家中的地图组件的ID(map; map0; map1 ...)。您在创建作曲家时定义了它。

根据另一段代码还可以,您应该使它工作。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.