diff --git a/src/dlw/convert.py b/src/dlw/convert.py new file mode 100644 index 0000000..e806d99 --- /dev/null +++ b/src/dlw/convert.py @@ -0,0 +1,118 @@ +import mammoth +from weasyprint import HTML, CSS +import os +import sys + +def convert_docx_to_pdf(input_docx, output_pdf): + """ + Konvertiert eine DOCX-Datei über HTML in ein PDF unter Verwendung von + Mammoth für die Struktur und WeasyPrint für das PDF-Rendering. + """ + + # Sicherstellen, dass der Pfad absolut oder korrekt relativ ist + input_path = os.path.abspath(input_docx) + output_path = os.path.abspath(output_pdf) + + if not os.path.exists(input_path): + print(f"Fehler: '{input_path}' wurde nicht gefunden.") + return + + print(f"Lese Inhalt aus: {os.path.basename(input_path)}...") + + try: + # 1. DOCX zu HTML konvertieren + with open(input_path, "rb") as docx_file: + # Mammoth extrahiert die semantische Struktur (h1, p, table, etc.) + result = mammoth.convert_to_html(docx_file) + html_content = result.value + + # Warnungen ausgeben (z.B. nicht unterstützte Word-Styles) + for message in result.messages: + print(f"Mammoth Hinweis: {message.message}") + + print("Generiere PDF mit WeasyPrint...") + + # 2. Modernes CSS-Layout definieren + # Hier kannst du das Design zentral steuern + styled_html = f""" + + +
+ + + + + {html_content} + + + """ + + # 3. PDF-Erstellung durchführen + HTML(string=styled_html).write_pdf(output_path) + print(f"Erfolg! PDF gespeichert unter: {output_path}") + + except Exception as e: + print(f"Ein Fehler ist aufgetreten: {str(e)}") + if "Cairo" in str(e) or "Pango" in str(e): + print("\nHINWEIS: WeasyPrint benötigt externe Bibliotheken.") + print("Windows: Installiere 'GTK for Windows Runtime'.") + print("macOS: 'brew install pango'.") + +if __name__ == "__main__": + # Standard-Pfade (können beim Aufruf angepasst werden) + # Wenn du das Skript aus src/dlw/ startest, sucht es im selben Ordner. + test_input = "test_dokument.docx" + test_output = "test_ergebnis.pdf" + + # Ermöglicht Aufruf via: python convert.py input.docx output.pdf + if len(sys.argv) > 2: + test_input = sys.argv[1] + test_output = sys.argv[2] + + convert_docx_to_pdf(test_input, test_output) \ No newline at end of file