DaniFera commited on
Commit
0ee8143
verified
1 Parent(s): a6f28ff

Create core.py

Browse files
Files changed (1) hide show
  1. core.py +99 -0
core.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Versi贸n 1.0: L贸gica para Unir, Dividir y Proteger PDFs
2
+ import os
3
+ from pypdf import PdfWriter, PdfReader
4
+ from config import TEMP_DIR
5
+ import uuid
6
+
7
+ class PDFEngine:
8
+ """
9
+ Motor de procesamiento de PDFs.
10
+ Principio SRP: Solo se encarga de manipular bytes y archivos.
11
+ """
12
+
13
+ @staticmethod
14
+ def _get_output_path(filename: str) -> str:
15
+ """Genera una ruta 煤nica para evitar colisiones."""
16
+ unique_name = f"{uuid.uuid4().hex[:8]}_{filename}"
17
+ return os.path.join(TEMP_DIR, unique_name)
18
+
19
+ def merge_pdfs(self, file_paths: list) -> str:
20
+ """
21
+ Une m煤ltiples PDFs en uno solo.
22
+ Args:
23
+ file_paths: Lista de rutas de archivos temporales.
24
+ Returns:
25
+ Ruta del archivo generado.
26
+ """
27
+ if not file_paths:
28
+ raise ValueError("No se han proporcionado archivos.")
29
+
30
+ merger = PdfWriter()
31
+
32
+ try:
33
+ for path in file_paths:
34
+ merger.append(path)
35
+
36
+ output_path = self._get_output_path("unido.pdf")
37
+ with open(output_path, "wb") as f:
38
+ merger.write(f)
39
+
40
+ return output_path
41
+ except Exception as e:
42
+ raise RuntimeError(f"Error al unir PDFs: {str(e)}")
43
+ finally:
44
+ merger.close()
45
+
46
+ def split_pdf(self, file_path: str) -> list:
47
+ """
48
+ Divide un PDF en p谩ginas individuales.
49
+ Nota: Devuelve una lista de archivos.
50
+ """
51
+ if not file_path:
52
+ raise ValueError("Archivo no proporcionado.")
53
+
54
+ output_files = []
55
+ try:
56
+ reader = PdfReader(file_path)
57
+ base_name = os.path.basename(file_path).replace(".pdf", "")
58
+
59
+ for i, page in enumerate(reader.pages):
60
+ writer = PdfWriter()
61
+ writer.add_page(page)
62
+
63
+ out_name = f"{base_name}_pag_{i+1}.pdf"
64
+ out_path = self._get_output_path(out_name)
65
+
66
+ with open(out_path, "wb") as f:
67
+ writer.write(f)
68
+
69
+ output_files.append(out_path)
70
+
71
+ return output_files
72
+ except Exception as e:
73
+ raise RuntimeError(f"Error al dividir PDF: {str(e)}")
74
+
75
+ def protect_pdf(self, file_path: str, password: str) -> str:
76
+ """
77
+ Encripta un PDF con contrase帽a.
78
+ """
79
+ if not file_path or not password:
80
+ raise ValueError("Faltan el archivo o la contrase帽a.")
81
+
82
+ try:
83
+ reader = PdfReader(file_path)
84
+ writer = PdfWriter()
85
+
86
+ # Copiar todas las p谩ginas
87
+ for page in reader.pages:
88
+ writer.add_page(page)
89
+
90
+ # Encriptar
91
+ writer.encrypt(password)
92
+
93
+ output_path = self._get_output_path("protegido.pdf")
94
+ with open(output_path, "wb") as f:
95
+ writer.write(f)
96
+
97
+ return output_path
98
+ except Exception as e:
99
+ raise RuntimeError(f"Error al proteger PDF: {str(e)}")