rdesign/scripts/export_document.py

116 lines
3.6 KiB
Python

#!/usr/bin/env python3
"""
Scribus headless export script.
Called via: scribus -g -ns -py export_document.py -- [args]
Exports a .sla template to PDF or PNG, optionally substituting variables.
"""
import sys
import os
# Parse args after '--' separator
def parse_args():
args = {}
variables = {}
argv = sys.argv[1:] # Scribus passes script args after '--'
i = 0
while i < len(argv):
if argv[i] == "--input" and i + 1 < len(argv):
args["input"] = argv[i + 1]
i += 2
elif argv[i] == "--output" and i + 1 < len(argv):
args["output"] = argv[i + 1]
i += 2
elif argv[i] == "--format" and i + 1 < len(argv):
args["format"] = argv[i + 1]
i += 2
elif argv[i] == "--dpi" and i + 1 < len(argv):
args["dpi"] = int(argv[i + 1])
i += 2
elif argv[i] == "--var" and i + 1 < len(argv):
key, _, value = argv[i + 1].partition("=")
variables[key] = value
i += 2
else:
i += 1
args["variables"] = variables
return args
def main():
try:
import scribus
except ImportError:
print("ERROR: This script must be run inside Scribus (scribus -g -py)")
sys.exit(1)
args = parse_args()
input_file = args.get("input")
output_file = args.get("output")
fmt = args.get("format", "pdf")
dpi = args.get("dpi", 300)
variables = args.get("variables", {})
if not input_file or not output_file:
print("ERROR: --input and --output required")
sys.exit(1)
# Open the document
try:
scribus.openDoc(input_file)
except Exception as e:
print(f"ERROR: Could not open {input_file}: {e}")
sys.exit(1)
# Substitute variables in text frames
if variables:
page_count = scribus.pageCount()
for page_num in range(1, page_count + 1):
scribus.gotoPage(page_num)
items = scribus.getPageItems()
for item_name, item_type, _ in items:
# item_type 4 = text frame
if item_type == 4:
try:
text = scribus.getText(item_name)
modified = False
for key, value in variables.items():
placeholder = f"%{key}%"
if placeholder in text:
text = text.replace(placeholder, value)
modified = True
if modified:
scribus.selectText(0, scribus.getTextLength(item_name), item_name)
scribus.deleteText(item_name)
scribus.insertText(text, 0, item_name)
except Exception:
continue
# Export
if fmt == "pdf":
pdf = scribus.PDFfile()
pdf.file = output_file
pdf.quality = 0 # Maximum quality
pdf.resolution = dpi
pdf.version = 14 # PDF 1.4
pdf.compress = True
pdf.compressmtd = 0 # Automatic
pdf.save()
elif fmt == "png":
# Export each page as PNG
scribus.savePageAsEPS(output_file.replace(".png", ".eps"))
# Note: for PNG, we rely on post-processing with ghostscript/imagemagick
print(f"EPS exported to {output_file.replace('.png', '.eps')}")
print("Convert with: convert -density {dpi} file.eps file.png")
elif fmt == "svg":
# Scribus can export to SVG
scribus.saveDoc()
scribus.closeDoc()
print(f"Exported: {output_file}")
if __name__ == "__main__":
main()