49 lines
1.5 KiB
Python
49 lines
1.5 KiB
Python
|
|
"""
|
||
|
|
地图导出模块。布局文本更新、比例尺调整、图片导出。
|
||
|
|
"""
|
||
|
|
from qgis.core import QgsLayoutExporter, QgsScaleBarSettings
|
||
|
|
|
||
|
|
from app.config.paths import get_logger
|
||
|
|
|
||
|
|
logger = get_logger("qgis.exporter")
|
||
|
|
|
||
|
|
|
||
|
|
class MapExporter:
|
||
|
|
def __init__(self, config: dict, layout):
|
||
|
|
self.config = config
|
||
|
|
self.layout = layout
|
||
|
|
|
||
|
|
def update_texts(self, model: dict) -> None:
|
||
|
|
"""更新布局中的文本标签"""
|
||
|
|
for key in ["mapTitle", "mapTime", "mapUnit", "info"]:
|
||
|
|
label = self.layout.itemById(key)
|
||
|
|
if label is not None:
|
||
|
|
label.setText(model[key])
|
||
|
|
|
||
|
|
def update_scale_bar(self) -> None:
|
||
|
|
"""调整比例尺为自适应宽度模式"""
|
||
|
|
scale_bar = self.layout.itemById("ScaleBar")
|
||
|
|
if scale_bar is None:
|
||
|
|
logger.warning("比例尺控件不存在")
|
||
|
|
return
|
||
|
|
|
||
|
|
scale_bar.setSegmentSizeMode(
|
||
|
|
QgsScaleBarSettings.SegmentSizeMode.SegmentSizeFitWidth
|
||
|
|
)
|
||
|
|
scale_bar.setMaximumBarWidth(70)
|
||
|
|
scale_bar.setMinimumBarWidth(40)
|
||
|
|
|
||
|
|
def export(self, path: str) -> None:
|
||
|
|
"""导出布局为图片"""
|
||
|
|
dpi = self.config["qgis"]["exportDpi"]
|
||
|
|
|
||
|
|
settings = QgsLayoutExporter.ImageExportSettings()
|
||
|
|
settings.dpi = dpi
|
||
|
|
|
||
|
|
exporter = QgsLayoutExporter(self.layout)
|
||
|
|
result = exporter.exportToImage(path, settings)
|
||
|
|
|
||
|
|
if result != QgsLayoutExporter.Success:
|
||
|
|
raise RuntimeError(f"图片导出失败: {path}")
|
||
|
|
|
||
|
|
logger.info(f"图片已导出: {path}")
|