管道基础大数据平台系统开发-【后端】-Server
1
13693261870
2022-11-07 d8ce4e1d7fe96410a5fab96f46649280024ab2d9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import os
from qgis.core import *
from qgis.gui import *
from qgis.PyQt.QtGui import *
from qgis.PyQt.QtCore import *
from qgis.PyQt.QtWidgets import *
from qgis.PyQt.QtXml import *
 
def finished():
    img = render.renderedImage()
    # QgsProject.instance().homePath()
    image_location = os.path.join("e:/", "render.png")
    # save the image; e.g. img.save("/Users/myuser/render.png","png")
    img.save(image_location, "png")
 
QgsApplication.setPrefixPath("C:/Program Files/QGIS 3.16/bin", True)
qgs = QgsApplication([], True)
qgs.initQgis()
 
# vlayer = iface.activeLayer()
project = QgsProject.instance()
project.read(r'E:/data/1.Natural_Earth/Test.qgz')
 
layers = project.mapLayers().values()
# root = project.layerTreeRoot()
 
# layout = QgsPrintLayout(project)
layout = QgsLayout(project)
layout.initializeDefaults()
 
with open("E:/data/1.Natural_Earth/Layout.qpt", 'r', encoding='utf-8') as f:
    template_content = f.read()
doc = QDomDocument()
doc.setContent(template_content)
# doc = QDomDocument("E:/data/1.Natural_Earth/Layout.qpt")
#ele = layout.writeXml(doc, QgsReadWriteContext())
#layout.readLayoutXml(ele, doc, QgsReadWriteContext())
layout.loadFromTemplate(doc, QgsReadWriteContext(), False)
 
map = QgsLayoutItemMap(layout)
# # map.zoomToExtent(layers[0].extent())
layout.addItem(map)
 
# collection = layout.pageCollection()
# page = QgsLayoutItemPage(layout)
# page.setPageSize('A4')
# collection.addPage(page)
 
layoutView = QgsLayoutView()
layoutView.setPreviewModeEnabled(True)
layoutView.setContentsMargins(0, 0, 0, 0)
layoutView.setCurrentLayout(layout)
 
# map = QgsLayoutItemMap(layout)
# # map.zoomToExtent(layers[0].extent())
# # map.attemptResize(QgsLayoutSize(2480, 1748, QgsUnitTypes.LayoutPixels))
# layout.addItem(map)
 
# collection = layout.pageCollection()
# collection.deletePage(0)
# page = QgsLayoutItemPage(layout)
# page.setPageSize('A5', True)
# collection.addPage(page)
# collection.redraw()
 
# collection = layout.pageCollection()
# page = collection.page(0)
# # QgsUnitTypes.LayoutCentimeters
# # size = QgsLayoutSize(2480, 1748, QgsUnitTypes.LayoutPixels)
# page.setPageSize('A5', True)
 
# imgSetting = QgsLayoutExporter.ImageExportSettings()
# imgSetting.imageSize.width = 4096
# imgSetting.imageSize.heigth = 3507
 
# layout.updateBounds()
# layout.refresh()
# page.redraw()
# collection.redraw()
 
exporter = QgsLayoutExporter(layout)
img_path = os.path.join("e:/", "render.png")
exporter.exportToImage(img_path, QgsLayoutExporter.ImageExportSettings())
 
qgs.exitQgis()