Spaces:
Sleeping
Sleeping
import gradio as gr | |
from xhtml2pdf import pisa | |
from io import BytesIO | |
import os | |
import uuid | |
import tempfile | |
def generate_dummy_pdf(): | |
# β Step 1: Create simple HTML | |
html = """ | |
<html> | |
<body> | |
<h1>Hello PDF</h1> | |
<p>This is a test PDF generated by xhtml2pdf.</p> | |
</body> | |
</html> | |
""" | |
# β Step 2: Generate PDF into memory | |
pdf_data = BytesIO() | |
result = pisa.CreatePDF(html, dest=pdf_data) | |
# β Step 3: Error handling | |
if result.err: | |
return "β PDF generation failed" | |
# β Step 4: Write PDF to a real file | |
pdf_data.seek(0) | |
output_path = os.path.join(tempfile.gettempdir(), f"test_report_{uuid.uuid4().hex}.pdf") | |
with open(output_path, "wb") as f: | |
f.write(pdf_data.read()) | |
print("β PDF generated at:", output_path) | |
return output_path # β Gradio File component works with actual file path | |
# β Gradio UI | |
with gr.Blocks() as demo: | |
gr.Markdown("## π§ͺ PDF Generation Test") | |
btn = gr.Button("π Generate PDF Report") | |
file_output = gr.File(label="π₯ Download PDF") | |
btn.click(fn=generate_dummy_pdf, inputs=[], outputs=file_output) | |
demo.launch() | |