Update file_conversion.py
Browse files- file_conversion.py +76 -27
file_conversion.py
CHANGED
|
@@ -1,51 +1,100 @@
|
|
| 1 |
-
from fastapi import APIRouter, UploadFile, File, HTTPException, BackgroundTasks
|
| 2 |
from fastapi.responses import FileResponse
|
|
|
|
| 3 |
from pdf2docx import Converter
|
| 4 |
import os
|
| 5 |
-
import logging
|
| 6 |
import shutil
|
|
|
|
|
|
|
| 7 |
|
| 8 |
router = APIRouter()
|
| 9 |
|
| 10 |
-
# Setup logging
|
| 11 |
-
logging.basicConfig(level=logging.INFO)
|
| 12 |
-
logger = logging.getLogger(__name__)
|
| 13 |
-
|
| 14 |
-
# Define the temp directory
|
| 15 |
TEMP_DIR = "/.tempfiles"
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
def remove_file(path: str):
|
| 18 |
if os.path.exists(path):
|
| 19 |
os.unlink(path)
|
| 20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
@router.post("/convert/pdf_to_docx")
|
| 22 |
async def convert_pdf_to_docx(background_tasks: BackgroundTasks, file: UploadFile = File(...)):
|
| 23 |
if not file.filename.endswith('.pdf'):
|
| 24 |
raise HTTPException(status_code=400, detail="File must be a PDF")
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
pdf_temp_path =
|
| 28 |
docx_temp_path = pdf_temp_path.replace('.pdf', '.docx')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
try:
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
raise FileNotFoundError(f"Converted file not found: {docx_temp_path}")
|
| 40 |
-
|
| 41 |
-
background_tasks.add_task(remove_file, pdf_temp_path)
|
| 42 |
-
background_tasks.add_task(remove_file, docx_temp_path)
|
| 43 |
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
except Exception as e:
|
| 50 |
remove_file(pdf_temp_path)
|
| 51 |
remove_file(docx_temp_path)
|
|
|
|
| 1 |
+
from fastapi import APIRouter, UploadFile, File, HTTPException, BackgroundTasks, Response
|
| 2 |
from fastapi.responses import FileResponse
|
| 3 |
+
from pydantic import BaseModel
|
| 4 |
from pdf2docx import Converter
|
| 5 |
import os
|
|
|
|
| 6 |
import shutil
|
| 7 |
+
import pdfkit
|
| 8 |
+
import uuid
|
| 9 |
|
| 10 |
router = APIRouter()
|
| 11 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
TEMP_DIR = "/.tempfiles"
|
| 13 |
|
| 14 |
+
class HTMLRequest(BaseModel):
|
| 15 |
+
html_content: str
|
| 16 |
+
|
| 17 |
+
def ensure_temp_dir():
|
| 18 |
+
os.makedirs(TEMP_DIR, exist_ok=True)
|
| 19 |
+
|
| 20 |
def remove_file(path: str):
|
| 21 |
if os.path.exists(path):
|
| 22 |
os.unlink(path)
|
| 23 |
|
| 24 |
+
def generate_temp_filepath(extension: str) -> str:
|
| 25 |
+
return os.path.join(TEMP_DIR, f"temp_{uuid.uuid4()}.{extension}")
|
| 26 |
+
|
| 27 |
+
def html_to_pdf(html_content: str, output_path: str) -> None:
|
| 28 |
+
options = {
|
| 29 |
+
'page-size': 'A4',
|
| 30 |
+
'margin-top': '0.75in',
|
| 31 |
+
'margin-right': '0.75in',
|
| 32 |
+
'margin-bottom': '0.75in',
|
| 33 |
+
'margin-left': '0.75in',
|
| 34 |
+
'encoding': "UTF-8",
|
| 35 |
+
}
|
| 36 |
+
pdfkit.from_string(html_content, output_path, options=options)
|
| 37 |
+
|
| 38 |
+
def pdf_to_docx(pdf_path: str, docx_path: str) -> None:
|
| 39 |
+
cv = Converter(pdf_path)
|
| 40 |
+
cv.convert(docx_path)
|
| 41 |
+
cv.close()
|
| 42 |
+
|
| 43 |
+
def handle_conversion(convert_func, input_path: str, output_path: str, background_tasks: BackgroundTasks):
|
| 44 |
+
try:
|
| 45 |
+
convert_func(input_path, output_path)
|
| 46 |
+
if not os.path.exists(output_path):
|
| 47 |
+
raise FileNotFoundError(f"Converted file not found: {output_path}")
|
| 48 |
+
background_tasks.add_task(remove_file, input_path)
|
| 49 |
+
background_tasks.add_task(remove_file, output_path)
|
| 50 |
+
return FileResponse(
|
| 51 |
+
output_path,
|
| 52 |
+
media_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
| 53 |
+
filename=f"converted_document_{uuid.uuid4()}.docx"
|
| 54 |
+
)
|
| 55 |
+
except Exception as e:
|
| 56 |
+
remove_file(input_path)
|
| 57 |
+
remove_file(output_path)
|
| 58 |
+
raise HTTPException(status_code=500, detail=f"Conversion failed: {str(e)}")
|
| 59 |
+
|
| 60 |
@router.post("/convert/pdf_to_docx")
|
| 61 |
async def convert_pdf_to_docx(background_tasks: BackgroundTasks, file: UploadFile = File(...)):
|
| 62 |
if not file.filename.endswith('.pdf'):
|
| 63 |
raise HTTPException(status_code=400, detail="File must be a PDF")
|
| 64 |
+
|
| 65 |
+
ensure_temp_dir()
|
| 66 |
+
pdf_temp_path = generate_temp_filepath("pdf")
|
| 67 |
docx_temp_path = pdf_temp_path.replace('.pdf', '.docx')
|
| 68 |
+
|
| 69 |
+
with open(pdf_temp_path, "wb") as pdf_file:
|
| 70 |
+
shutil.copyfileobj(file.file, pdf_file)
|
| 71 |
+
|
| 72 |
+
return handle_conversion(pdf_to_docx, pdf_temp_path, docx_temp_path, background_tasks)
|
| 73 |
|
| 74 |
+
@router.post("/convert/html_to_pdf")
|
| 75 |
+
async def convert_html_to_pdf(request: HTMLRequest):
|
| 76 |
+
ensure_temp_dir()
|
| 77 |
+
pdf_temp_path = generate_temp_filepath("pdf")
|
| 78 |
+
|
| 79 |
try:
|
| 80 |
+
html_to_pdf(request.html_content, pdf_temp_path)
|
| 81 |
+
with open(pdf_temp_path, "rb") as pdf_file:
|
| 82 |
+
pdf_content = pdf_file.read()
|
| 83 |
+
remove_file(pdf_temp_path)
|
| 84 |
+
return Response(content=pdf_content, media_type="application/pdf")
|
| 85 |
+
except Exception as e:
|
| 86 |
+
remove_file(pdf_temp_path)
|
| 87 |
+
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
+
@router.post("/convert/html_to_docx")
|
| 90 |
+
async def convert_html_to_docx(background_tasks: BackgroundTasks, request: HTMLRequest):
|
| 91 |
+
ensure_temp_dir()
|
| 92 |
+
pdf_temp_path = generate_temp_filepath("pdf")
|
| 93 |
+
docx_temp_path = pdf_temp_path.replace('.pdf', '.docx')
|
| 94 |
+
|
| 95 |
+
try:
|
| 96 |
+
html_to_pdf(request.html_content, pdf_temp_path)
|
| 97 |
+
return handle_conversion(pdf_to_docx, pdf_temp_path, docx_temp_path, background_tasks)
|
| 98 |
except Exception as e:
|
| 99 |
remove_file(pdf_temp_path)
|
| 100 |
remove_file(docx_temp_path)
|