File size: 2,000 Bytes
81dba5a
4194e87
1a078b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81dba5a
a1eb9dc
1a078b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81dba5a
1a078b5
 
81dba5a
1a078b5
81dba5a
1a078b5
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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()