data-boards / app.py
prithivMLmods's picture
Update app.py
1a078b5 verified
raw
history blame
2 kB
import gradio as gr
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from docx import Document
import os
def word_to_pdf(word_file):
try:
doc = Document(word_file.name)
pdf_file = "output.pdf"
c = canvas.Canvas(pdf_file, pagesize=letter)
width, height = letter
for paragraph in doc.paragraphs:
text = paragraph.text
if text.strip():
c.drawString(72, height - 72, text)
height -= 14
if height < 72: # Create a new page if space runs out
c.showPage()
height = letter[1]
c.save()
return pdf_file
except Exception as e:
return f"Error: {e}"
def pdf_to_word(pdf_file):
try:
from PyPDF2 import PdfReader
reader = PdfReader(pdf_file.name)
doc = Document()
for page in reader.pages:
text = page.extract_text()
if text.strip():
doc.add_paragraph(text)
word_file = "output.docx"
doc.save(word_file)
return word_file
except Exception as e:
return f"Error: {e}"
def interface():
with gr.Blocks() as app:
gr.Markdown("## PDF to Word and Word to PDF Converter")
with gr.Tab("Word to PDF"):
word_input = gr.File(label="Upload Word File", file_types=[".docx"])
pdf_output = gr.File(label="Download PDF File")
word_to_pdf_button = gr.Button("Convert Word to PDF")
with gr.Tab("PDF to Word"):
pdf_input = gr.File(label="Upload PDF File", file_types=[".pdf"])
word_output = gr.File(label="Download Word File")
pdf_to_word_button = gr.Button("Convert PDF to Word")
word_to_pdf_button.click(word_to_pdf, inputs=word_input, outputs=pdf_output)
pdf_to_word_button.click(pdf_to_word, inputs=pdf_input, outputs=word_output)
return app
app = interface()
app.launch()