# app.py import gradio as gr import markdown import tempfile import os from weasyprint import HTML, CSS from pathlib import Path def convert_markdown_to_pdf(file_obj): """ Convert uploaded markdown file to PDF and return both preview HTML and PDF path """ if file_obj is None: return None, None try: # Read the markdown content from the file object if hasattr(file_obj, 'name'): # If it's a file path with open(file_obj.name, 'r', encoding='utf-8') as f: markdown_content = f.read() else: # If it's already string content markdown_content = str(file_obj) # Convert markdown to HTML html_content = markdown.markdown( markdown_content, extensions=['extra', 'codehilite'] ) # Wrap HTML content with proper HTML structure and CSS full_html = f"""
{html_content} """ # Create temporary file for PDF pdf_path = tempfile.mktemp(suffix='.pdf') # Convert HTML to PDF using WeasyPrint html = HTML(string=full_html) html.write_pdf(pdf_path) return full_html, pdf_path except Exception as e: print(f"Error converting to PDF: {e}") if 'pdf_path' in locals() and os.path.exists(pdf_path): os.unlink(pdf_path) return None, None def process_file(file): """ Process the uploaded file and return preview and PDF download """ if file is None: return None, None preview_html, pdf_path = convert_markdown_to_pdf(file) if preview_html is None or pdf_path is None: return "Error converting file", None return preview_html, pdf_path # Create Gradio interface with gr.Blocks() as app: gr.Markdown("# Markdown to PDF Converter") gr.Markdown("Upload a markdown file to convert it to PDF. You can preview the result and download the PDF.") with gr.Row(): file_input = gr.File(label="Upload Markdown File", file_types=[".md", ".markdown"]) with gr.Row(): preview = gr.HTML(label="Preview") pdf_output = gr.File(label="Download PDF") file_input.upload( fn=process_file, inputs=[file_input], outputs=[preview, pdf_output] ) if __name__ == "__main__": app.launch(share=True)