Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,34 +3,42 @@ from xhtml2pdf import pisa
|
|
| 3 |
from io import BytesIO
|
| 4 |
import os
|
| 5 |
import uuid
|
|
|
|
| 6 |
|
| 7 |
def generate_dummy_pdf():
|
|
|
|
| 8 |
html = """
|
| 9 |
<html>
|
| 10 |
<body>
|
| 11 |
-
<h1>Hello
|
| 12 |
-
<p>This is a test PDF
|
| 13 |
</body>
|
| 14 |
</html>
|
| 15 |
"""
|
| 16 |
-
result = BytesIO()
|
| 17 |
-
pisa_status = pisa.CreatePDF(html, dest=result)
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
with gr.Blocks() as demo:
|
| 31 |
-
|
| 32 |
-
|
|
|
|
| 33 |
|
| 34 |
-
btn.click(fn=generate_dummy_pdf, inputs=[], outputs=
|
| 35 |
|
| 36 |
demo.launch()
|
|
|
|
| 3 |
from io import BytesIO
|
| 4 |
import os
|
| 5 |
import uuid
|
| 6 |
+
import tempfile
|
| 7 |
|
| 8 |
def generate_dummy_pdf():
|
| 9 |
+
# β
Step 1: Create simple HTML
|
| 10 |
html = """
|
| 11 |
<html>
|
| 12 |
<body>
|
| 13 |
+
<h1>Hello PDF</h1>
|
| 14 |
+
<p>This is a test PDF generated by xhtml2pdf.</p>
|
| 15 |
</body>
|
| 16 |
</html>
|
| 17 |
"""
|
|
|
|
|
|
|
| 18 |
|
| 19 |
+
# β
Step 2: Generate PDF into memory
|
| 20 |
+
pdf_data = BytesIO()
|
| 21 |
+
result = pisa.CreatePDF(html, dest=pdf_data)
|
| 22 |
|
| 23 |
+
# β
Step 3: Error handling
|
| 24 |
+
if result.err:
|
| 25 |
+
return "β PDF generation failed"
|
| 26 |
|
| 27 |
+
# β
Step 4: Write PDF to a real file
|
| 28 |
+
pdf_data.seek(0)
|
| 29 |
+
output_path = os.path.join(tempfile.gettempdir(), f"test_report_{uuid.uuid4().hex}.pdf")
|
| 30 |
+
with open(output_path, "wb") as f:
|
| 31 |
+
f.write(pdf_data.read())
|
| 32 |
|
| 33 |
+
print("β
PDF generated at:", output_path)
|
| 34 |
+
return output_path # β
Gradio File component works with actual file path
|
| 35 |
+
|
| 36 |
+
# β
Gradio UI
|
| 37 |
with gr.Blocks() as demo:
|
| 38 |
+
gr.Markdown("## π§ͺ PDF Generation Test")
|
| 39 |
+
btn = gr.Button("π Generate PDF Report")
|
| 40 |
+
file_output = gr.File(label="π₯ Download PDF")
|
| 41 |
|
| 42 |
+
btn.click(fn=generate_dummy_pdf, inputs=[], outputs=file_output)
|
| 43 |
|
| 44 |
demo.launch()
|