My Python script freezes in the middle of execution when trying to export a QGIS layer as a PDF with a page per feature. It gets to the following line, and then the script simply crashes:
result = exporter.exportToPdf(atlas, os.path.join(arbeidsmappe_path, output_pdf), QgsLayoutExporter.PdfExportSettings()).
I have a try, except block after this, which it never gets to.
Here is the full code block. I have changed some variable names to be more generic. Also some variables like directory and arbeidsmappe_path, it is being passed from another script.
# -*- 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()
The script is supposed to create one PDF consisting of multiple pages per data layer in my .QGS project file, but it simply crashes out during the first layer it gets to.
EDIT: I ended up abandoning the idea to use atlas outside of QGIS and instead used PyQGIS which I turned into a plugin. I'll share the code with anyone if they're curious.