Spaces:
Sleeping
Sleeping
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293# app.pyimport gradio as grimport markdownimport pdfkitimport tempfileimport osfrom pathlib import Path
def convert_markdown_to_pdf(markdown_file): """ Convert uploaded markdown file to PDF and return both preview HTML and PDF path """ if markdown_file is None: return None, None # Read the markdown content markdown_content = markdown_file.decode('utf-8') # Convert markdown to HTML html_content = markdown.markdown(markdown_content) # Wrap HTML content with proper HTML structure full_html = f""" <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <style> body {{ font-family: Arial, sans-serif; line-height: 1.6; max-width: 800px; margin: 0 auto; padding: 20px; }} h1 {{ color: #2c3e50; }} h2 {{ color: #34495e; }} code {{ background-color: #f7f7f7; padding: 2px 5px; border-radius: 3px; }} pre {{ background-color: #f7f7f7; padding: 15px; border-radius: 5px; overflow-x: auto; }} </style> </head> <body> {html_content} </body> </html> """ # Create temporary files for HTML and PDF with tempfile.NamedTemporaryFile(delete=False, suffix='.html') as html_file: html_file.write(full_html.encode('utf-8')) html_path = html_file.name pdf_path = html_path.replace('.html', '.pdf') # Convert HTML to PDF using pdfkit try: pdfkit.from_file(html_path, pdf_path) os.unlink(html_path) # Clean up temporary HTML file return full_html, pdf_path except Exception as e: print(f"Error converting to PDF: {e}") if os.path.exists(html_path): os.unlink(html_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 interfacewith 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()app.pyAdded+93