developer28 commited on
Commit
a6e9713
Β·
verified Β·
1 Parent(s): c0f8987

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -15
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, PDF!</h1>
12
- <p>This is a test PDF file.</p>
13
  </body>
14
  </html>
15
  """
16
- result = BytesIO()
17
- pisa_status = pisa.CreatePDF(html, dest=result)
18
 
19
- if pisa_status.err:
20
- print("PDF generation failed")
21
- return None
22
 
23
- pdf_path = os.path.join(os.path.expanduser("~"), "Downloads", f"test_pdf_{uuid.uuid4().hex}.pdf")
24
- with open(pdf_path, "wb") as f:
25
- f.write(result.getvalue())
26
 
27
- print("βœ… PDF saved at:", pdf_path)
28
- return pdf_path
 
 
 
29
 
 
 
 
 
30
  with gr.Blocks() as demo:
31
- btn = gr.Button("πŸ“„ Generate PDF")
32
- output = gr.File(label="πŸ“₯ Download PDF")
 
33
 
34
- btn.click(fn=generate_dummy_pdf, inputs=[], outputs=output)
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()