Added Login + Working on pdf creation
This commit is contained in:
83
src/worker/tasks/common/pdf_converter.py
Normal file
83
src/worker/tasks/common/pdf_converter.py
Normal file
@@ -0,0 +1,83 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from pathlib import Path
|
||||
|
||||
import pypandoc
|
||||
from PIL import Image
|
||||
from reportlab.lib.pagesizes import A4
|
||||
from reportlab.pdfgen import canvas
|
||||
|
||||
from tasks.common.converter_utils import generate_uuid_filename
|
||||
|
||||
|
||||
class BaseConverter(ABC):
|
||||
"""Abstract base class for file converters to PDF."""
|
||||
|
||||
def __init__(self, input_path: str, output_dir: str = ".") -> None:
|
||||
self.input_path = Path(input_path)
|
||||
self.output_dir = Path(output_dir)
|
||||
self.output_path = self.output_dir / f"{generate_uuid_filename()}.pdf"
|
||||
|
||||
@abstractmethod
|
||||
def convert(self) -> str:
|
||||
"""Convert input file to PDF and return the output path."""
|
||||
pass
|
||||
|
||||
|
||||
class TextToPdfConverter(BaseConverter):
|
||||
"""Converter for text files to PDF."""
|
||||
|
||||
def convert(self) -> str:
|
||||
c = canvas.Canvas(str(self.output_path), pagesize=A4)
|
||||
width, height = A4
|
||||
with open(self.input_path, "r", encoding="utf-8") as f:
|
||||
y = height - 50
|
||||
for line in f:
|
||||
c.drawString(50, y, line.strip())
|
||||
y -= 15
|
||||
if y < 50:
|
||||
c.showPage()
|
||||
y = height - 50
|
||||
c.save()
|
||||
return str(self.output_path)
|
||||
|
||||
|
||||
class ImageToPdfConverter(BaseConverter):
|
||||
"""Converter for image files to PDF."""
|
||||
|
||||
def convert(self) -> str:
|
||||
image = Image.open(self.input_path)
|
||||
rgb_image = image.convert("RGB")
|
||||
rgb_image.save(self.output_path)
|
||||
return str(self.output_path)
|
||||
|
||||
|
||||
class WordToPdfConverter(BaseConverter):
|
||||
"""Converter for Word files (.docx) to PDF using pypandoc."""
|
||||
|
||||
def convert(self) -> str:
|
||||
pypandoc.convert_file(
|
||||
str(self.input_path), "pdf", outputfile=str(self.output_path)
|
||||
)
|
||||
return str(self.output_path)
|
||||
|
||||
|
||||
# Placeholders for future extensions
|
||||
class HtmlToPdfConverter(BaseConverter):
|
||||
"""Placeholder for HTML to PDF converter."""
|
||||
|
||||
def convert(self) -> str:
|
||||
raise NotImplementedError("HTML to PDF conversion not implemented.")
|
||||
|
||||
|
||||
class ExcelToPdfConverter(BaseConverter):
|
||||
"""Placeholder for Excel to PDF converter."""
|
||||
|
||||
def convert(self) -> str:
|
||||
raise NotImplementedError("Excel to PDF conversion not implemented.")
|
||||
|
||||
|
||||
class MarkdownToPdfConverter(BaseConverter):
|
||||
"""Placeholder for Markdown to PDF converter."""
|
||||
|
||||
def convert(self) -> str:
|
||||
raise NotImplementedError("Markdown to PDF conversion not implemented.")
|
||||
Reference in New Issue
Block a user