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 * QgsApplication.setPrefixPath(r"C:/Program Files/QGIS 3.16/bin", True) qgs = QgsApplication([], True) qgs.initQgis() project = QgsProject.instance() project.read(r'E:/terrait/TianJin/LFServer/QGIS/Test.qgz') print("FileName: " + project.fileName()) # layers = project.mapLayers().values() # root = project.layerTreeRoot() # layout = QgsPrintLayout(project) layout = QgsLayout(project) layout.initializeDefaults() with open(r"E:/terrait/TianJin/LFServer/QGIS/Template.qpt", 'r', encoding='utf-8') as f: template_content = f.read() doc = QDomDocument() doc.setContent(template_content) layout.loadFromTemplate(doc, QgsReadWriteContext(), True) # map = QgsLayoutItemMap(layout) # # map.zoomToExtent(layers[0].extent()) # 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('A3', True) # imgSetting = QgsLayoutExporter.ImageExportSettings() # imgSetting.imageSize.width = 4096 # imgSetting.imageSize.heigth = 3507 exporter = QgsLayoutExporter(layout) img_path = os.path.join(r"E:/terrait/TianJin/LFServer/QGIS", "render.png") exporter.exportToImage(img_path, QgsLayoutExporter.ImageExportSettings()) qgs.exitQgis()