File size: 2,019 Bytes
a6ea3cd
a7639f7
 
a6ea3cd
 
a7639f7
 
f733c5e
dbf34cc
a7639f7
 
 
a6ea3cd
a7639f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6ea3cd
f733c5e
a6ea3cd
a7639f7
 
 
 
a6ea3cd
 
a7639f7
 
 
 
 
a6ea3cd
 
a7639f7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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()