Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import markdown | |
| from weasyprint import HTML | |
| import os | |
| def convert_md_to_pdf(md_file): | |
| if md_file is None: | |
| return None | |
| # 1. Read the Markdown file | |
| with open(md_file.name, 'r', encoding='utf-8') as f: | |
| md_text = f.read() | |
| # 2. Convert to HTML | |
| raw_html = markdown.markdown(md_text, extensions=['extra', 'codehilite']) | |
| # 3. Add some "Professional" styling | |
| styled_html = f""" | |
| <html> | |
| <head> | |
| <style> | |
| body {{ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.6; padding: 50px; color: #333; }} | |
| h1 {{ color: #2c3e50; border-bottom: 2px solid #eee; }} | |
| code {{ background: #f4f4f4; padding: 2px 5px; border-radius: 3px; font-family: monospace; }} | |
| pre {{ background: #f4f4f4; padding: 15px; border-radius: 5px; overflow-x: auto; }} | |
| img {{ max-width: 100%; height: auto; }} | |
| table {{ border-collapse: collapse; width: 100%; margin-bottom: 20px; }} | |
| th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }} | |
| th {{ background-color: #f2f2f2; }} | |
| </style> | |
| </head> | |
| <body> | |
| {raw_html} | |
| </body> | |
| </html> | |
| """ | |
| # 4. Generate PDF | |
| output_path = "document.pdf" | |
| HTML(string=styled_html).write_pdf(output_path) | |
| return output_path | |
| # --- UI Layout --- | |
| with gr.Blocks(theme=gr.themes.Soft()) as demo: | |
| gr.Markdown("# 📄 Professional MD to PDF Converter") | |
| gr.Markdown("Upload a `.md` file and get a styled PDF document instantly.") | |
| with gr.Row(): | |
| file_input = gr.File(label="Upload Markdown (.md)", file_types=[".md"]) | |
| file_output = gr.File(label="Download Result (.pdf)") | |
| convert_btn = gr.Button("Convert to PDF", variant="primary") | |
| convert_btn.click(fn=convert_md_to_pdf, inputs=file_input, outputs=file_output) | |
| if __name__ == "__main__": | |
| demo.launch() |