#!/usr/bin/env python3 """Export PPTX to PDF/PNG with DeckCraft, or PDF to PNG with PdfCraft.""" import argparse import json import os from pathlib import Path import re import shutil import subprocess import sys import tempfile def status(message, level='info'): stream = sys.stderr if level in ('warning', 'error') else sys.stdout label, color = { 'info': ('INFO', '36'), 'success': ('OK', '32'), 'warning': ('WARN', '33'), 'error': ('ERROR', '31'), }[level] prefix = f'[{label}]' if stream.isatty() and 'NO_COLOR' not in os.environ and os.environ.get('TERM') != 'dumb': prefix = f'\033[{color}m{prefix}\033[0m' print(f'{prefix} {message}', file=stream, flush=True) def output_formats(value): formats = list(dict.fromkeys(item.strip().lower() for item in value.split(','))) if any(item not in ('pdf', 'images') for item in formats): raise argparse.ArgumentTypeError('Output must be pdf, images, or pdf,images.') return formats def positive_int(value): number = int(value) if number <= 0: raise argparse.ArgumentTypeError('Must be a positive integer.') return number def run(command, **kwargs): result = subprocess.run([str(arg) for arg in command], capture_output=True, text=True, errors='replace', **kwargs) if result.returncode: detail = result.stderr.strip() or result.stdout.strip() or f'exit code {result.returncode}' raise RuntimeError(f'{Path(command[0]).name}: {detail}') if result.stderr.strip(): for line in result.stderr.strip().splitlines(): status(line, 'warning' if re.search(r'\b(warning|error)\b', line, re.I) else 'info') return result.stdout def find_cli(app, override, work): """Use PATH first, then a local AppImage's bundled CLI (no FUSE needed).""" candidate = override or os.environ.get(app.upper() + '_CLI') if candidate: path = Path(candidate).expanduser() if not path.is_file(): found = shutil.which(candidate) if not found: raise RuntimeError(f'Cannot find {app} executable: {candidate}') path = Path(found) else: found = shutil.which(f'{app}-cli') if found: path = Path(found) else: images = list((Path.home() / 'Applications').glob(f'{app}-*.AppImage')) # Natural version ordering: 0.10 follows 0.9. images.sort(key=lambda p: [int(n) for n in re.findall(r'\d+', p.name)], reverse=True) if not images: raise RuntimeError( f'{app}-cli not found. Install {app}, place its AppImage in ~/Applications, ' f'or pass --{app}-cli PATH (CLI executable or AppImage).') path = images[0] path = path.resolve() if path.suffix.lower() == '.appimage': status(f'Loading bundled {app}-cli from {path.name}...') unpack = work / app unpack.mkdir() run([path, '--appimage-extract', f'usr/bin/{app}-cli'], cwd=unpack) path = unpack / 'squashfs-root' / 'usr' / 'bin' / f'{app}-cli' if not path.is_file() or not os.access(path, os.X_OK): raise RuntimeError(f'CLI is missing or not executable: {path}') status(f'Using {app}: {path.name}') return path def export(source, formats, destination, dpi, overwrite, cli_override): is_deck = source.suffix.lower() == '.pptx' if not is_deck and 'pdf' in formats: status(f'Already PDF; nothing to convert: {source}', 'success') formats = [format for format in formats if format != 'pdf'] if not formats: return pdf_target = destination / f'{source.stem}.pdf' images_target = destination / 'images' targets = ([pdf_target] if 'pdf' in formats else []) + ([images_target] if 'images' in formats else []) for target in targets: if target.is_symlink(): raise RuntimeError(f'Refusing to write through an output symlink: {target}') if target.exists() and not overwrite: raise RuntimeError(f'Output already exists: {target}. Use --overwrite to replace generated files.') if target.exists() and (target == images_target) != target.is_dir(): raise RuntimeError(f'Output has the wrong file type: {target}') if target.resolve() == source: raise RuntimeError(f'Output would replace the input: {source}') app = 'deckcraft' if is_deck else 'pdfcraft' with tempfile.TemporaryDirectory(prefix='exporter-') as temp: work = Path(temp) cli = find_cli(app, cli_override, work) rendered = work / 'images' if 'pdf' in formats: status('Exporting presentation to PDF...') run([cli, 'convert', source, work / 'export.pdf']) if not (work / 'export.pdf').is_file() or not (work / 'export.pdf').stat().st_size: raise RuntimeError('DeckCraft did not create a PDF.') if 'images' in formats: rendered.mkdir() if is_deck: status(f'Rendering all slides as PNG ({dpi} DPI)...') run([cli, 'render', source, '--all', '--scale', str(dpi / 72), rendered]) else: status('Reading PDF page count...') info = json.loads(run([cli, 'info', source])) pages = info.get('pages') if type(pages) is not int or pages < 1: raise RuntimeError('PdfCraft did not report a positive page count.') for page in range(1, pages + 1): status(f'[{page}/{pages}] Rendering page at {dpi} DPI...') run([cli, 'render', source, '--page', str(page), '--dpi', str(dpi), '--out', rendered / f'page-{page:04d}.png']) images = sorted(rendered.glob('*.png')) if not images or any(image.stat().st_size == 0 for image in images): raise RuntimeError(f'{app} did not produce valid image output.') if not is_deck and len(images) != pages: raise RuntimeError('PdfCraft did not produce every requested page.') status(f'Rendered {len(images)} image(s).', 'success') # Publish only after all requested conversions succeed. destination.mkdir(parents=True, exist_ok=True) if 'pdf' in formats: shutil.copy2(work / 'export.pdf', pdf_target) status(f'PDF: {pdf_target}', 'success') if 'images' in formats: images_target.mkdir(exist_ok=True) if overwrite: for old in images_target.iterdir(): if re.fullmatch(r'(slide|page)-\d+\.png', old.name) and old.is_file(): old.unlink() for image in images: target = images_target / image.name if target.is_symlink(): raise RuntimeError(f'Refusing to write through an output symlink: {target}') shutil.copy2(image, target) status(f'Images: {images_target}', 'success') def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('file', type=Path, help='Source .pptx or .pdf') parser.add_argument('--output', required=True, type=output_formats, metavar='pdf,images', help='Comma-separated output formats: pdf, images') parser.add_argument('-d', '--output-dir', type=Path, help='Destination directory (default: _export)') parser.add_argument('--dpi', type=positive_int, default=144, help='PNG resolution (default: 144)') parser.add_argument('--overwrite', action='store_true', help='Replace existing generated output files') parser.add_argument('--deckcraft-cli', help='DeckCraft CLI executable or AppImage') parser.add_argument('--pdfcraft-cli', help='PdfCraft CLI executable or AppImage') args = parser.parse_args(argv) source = args.file.expanduser().resolve() if source.suffix.lower() not in ('.pptx', '.pdf'): parser.error(f'Unsupported input type: {source.suffix or "(no extension)"}. Expected .pptx or .pdf.') if not source.is_file(): parser.error(f'Not a file: {source}') destination = (args.output_dir.expanduser() if args.output_dir else source.with_name(source.stem + '_export')).resolve() try: status(f'Source: {source}') export(source, args.output, destination, args.dpi, args.overwrite, args.deckcraft_cli if source.suffix.lower() == '.pptx' else args.pdfcraft_cli) status('Done.', 'success') return 0 except (OSError, RuntimeError, ValueError) as error: status(str(error), 'error') return 1 if __name__ == '__main__': sys.exit(main())