import os import markdown import pdfkit import pypandoc WKHTMLTOPDF_PATH = r"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe" config = pdfkit.configuration(wkhtmltopdf=WKHTMLTOPDF_PATH) TEMPLATE_DOCX_PATH = os.path.join(os.path.dirname(__file__), "..", "templates", "default_template.docx") def convert_markdown(input_file, output_format, font=None, template_path=None): output_file = os.path.splitext(input_file)[0] + (".pdf" if output_format == "PDF" else ".docx") if output_format == "PDF": with open(input_file, 'r', encoding='utf-8') as f: html = markdown.markdown(f.read()) style = f"" if font else "" pdfkit.from_string(style + html, output_file, configuration=config) elif output_format == "DOCX": args = [] if template_path and os.path.exists(template_path): args.extend(["--reference-doc", template_path]) elif os.path.exists(TEMPLATE_DOCX_PATH): args.extend(["--reference-doc", TEMPLATE_DOCX_PATH]) pypandoc.convert_file(input_file, 'docx', outputfile=output_file, extra_args=args) else: raise ValueError("Formato non supportato") return output_file