You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

QGIS Atlas Python脚本导出PDF崩溃生成损坏文件求助

QGIS批量导出按要素分页PDF脚本崩溃问题

我编写的Python脚本在尝试将QGIS图层导出为按要素分页的PDF时,执行到代码行result = exporter.exportToPdf(atlas, os.path.join(arbeidsmappe_path, output_pdf), QgsLayoutExporter.PdfExportSettings())直接崩溃,后续的try-except块无法捕获异常。脚本本应为.QGS项目中的每个数据层生成多页PDF,但处理第一个图层时就崩溃了。

原脚本代码

# -*- coding: UTF-8 -*-
import os
import sys
from qgis.PyQt.QtXml import QDomDocument
from qgis.core import (
    QgsApplication, QgsProject, QgsPrintLayout, QgsLayoutExporter,
    QgsReadWriteContext
)

# Check for command line arguments for paths
if len(sys.argv) > 2:
    directory = sys.argv[1]
    arbeidsmappe_path = sys.argv[2]
else:
    print("Directory and arbeidsmappe path were not provided.")
    sys.exit(1)

# Set up the QGIS application
QgsApplication.setPrefixPath(r"C:\Program Files\QGIS 3.30.3\bin", True)
qgs = QgsApplication([], False)
qgs.initQgis()

# Function to generate atlas from a .qpt file
def generate_atlas_from_template(qpt_file, output_pdf, layout_name):
    print(f"Starting to generate atlas from template: {qpt_file}", flush=True)
    # Load the project file
    project = QgsProject.instance()
    if not project.read(os.path.join(directory, 'Presentasjon_analyse_NIS-FKB_test.qgs')):
        print(f"Failed to read the project file: {os.path.join(directory, 'Presentasjon_analyse_NIS-FKB_test.qgs')}", flush=True)
        return
    
    project.read(os.path.join(directory, 'Presentasjon_analyse_NIS-FKB_test.qgs'))
    print("Project file loaded successfully", flush=True)

    # Read in the .qpt file
    template_path = os.path.join(directory, qpt_file)
    try:
        with open(template_path) as f:
            template_content = f.read()
    except Exception as e:
        print(f"Failed to read the template file: {template_path}. Error: {e}", flush=True)
        return
    
    print("Template file read successfully", flush=True)
    template_content = open(template_path).read()
    document = QDomDocument()
    document.setContent(template_content)

    # Create a new layout
    layout = QgsPrintLayout(project)
    layout.initializeDefaults()
    if not layout.loadFromTemplate(document, QgsReadWriteContext()):
        print(f"Failed to load layout from the template", flush=True)
        return
    
    print("Layout loaded from template successfully", flush=True)
    layout.loadFromTemplate(document, QgsReadWriteContext())

    # Assume layout and atlas are already configured in the .qpt file
    atlas = layout.atlas()
    atlas.setEnabled(True)  # Just ensure atlas is enabled, in case it's not set in the template

    # Proceed to export the atlas to a PDF  
    exporter = QgsLayoutExporter(layout)
    print(arbeidsmappe_path)
    try:
        print(f"Exporting atlas to {output_pdf}...", flush=True)
        result = exporter.exportToPdf(atlas, os.path.join(arbeidsmappe_path, output_pdf), QgsLayoutExporter.PdfExportSettings())

        if result != QgsLayoutExporter.Success:
            print(f"Failed to export atlas for {output_pdf}")
        else:
            print(f"Atlas successfully exported to {output_pdf}")

    except Exception as e:
        print(f"An error occurred while exporting atlas for {output_pdf}: {e}")


# Generate atlas for each template
generate_atlas_from_template(r'C:\\Atlas_template\template1.qpt', '1.pdf', '1_layout')
generate_atlas_from_template(r'C:\Atlas_template\template2.qpt', '2.pdf', '2_layout')
generate_atlas_from_template(r'C:\Atlas_template\template3', '3.pdf', '3_layout')

# Clean up the QGIS application
qgs.exitQgis()

最终解决方式

改为在QGIS内使用PyQGIS制作插件实现了需求,可分享插件代码。

内容的提问来源于stack exchange,提问作者jespergeospatial

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 19:44:54