Aprende a construir una aplicación completa con Spring Boot que analiza automáticamente documentos legales en formato PDF usando Apache PDFBox 3 para extracción de texto y Ollama AI vía Spring AI para análisis inteligente. Paso a paso con código y explicación clara.
En este artículo descubrirás cómo combinar tecnologías modernas para automatizar el análisis de contratos legales en PDF. Usaremos Spring Boot con el nuevo módulo Spring AI y el modelo Ollama para procesar textos extraídos con Apache PDFBox 3. Te guiaré paso a paso en la creación de servicios, controladores y vistas para que puedas implementar fácilmente esta funcionalidad en tus proyectos Java.
Crea un proyecto Spring Boot usando Spring Initializr (https://start.spring.io) con las siguientes dependencias:
Luego agrega en tu pom.xml
la dependencia para PDFBox 3.0.3:
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>3.0.3</version>
</dependency>
Tendrias que tener las siguientes dependencias:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-ollama</artifactId>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Crea un servicio que abra el PDF y extraiga su texto usando el nuevo Loader para PDFBox 3.
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.stereotype.Service;
import java.io.File;
@Service
public class PdfService {
public String extractText(File file){
try (PDDocument document = Loader.loadPDF(file)) {
PDFTextStripper stripper = new PDFTextStripper();
return stripper.getText(document);
}catch (Exception e){
throw new RuntimeException("Error Al procesar el pdf " + e);
}
}
}
Usa el cliente OllamaChatModel para enviar un prompt personalizado con el texto del contrato.
import lombok.AllArgsConstructor;
import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.stereotype.Service;
@Service
@AllArgsConstructor
public class AiService {
private final OllamaChatModel ollamaChatModel;
public String analyze(String textContent){
String prompt = """
Eres un abogado experto. Analiza el siguiente contrato legal y proporciona:
1. Resumen en 3-5 puntos.
2. Posibles riesgos o cláusulas problemáticas.
3. Fechas y partes involucradas.
4. Tipo de contrato.
Contrato:
%s
""".formatted(textContent);
return ollamaChatModel.call(prompt);
}
}
import com.amoelcodigo.lexscanai.services.AiService;
import com.amoelcodigo.lexscanai.services.PdfService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
@Controller
@AllArgsConstructor
public class UploadController {
private PdfService pdfService;
private AiService aiService;
@GetMapping("/")
public String home(){
return "upload";
}
@PostMapping("/analyze")
public String analyzePdf(@RequestParam("file") MultipartFile file, Model model) throws Exception {
//Guardar archivo en temp file
File tempFile = File.createTempFile("upload-", ".pdf");
file.transferTo(tempFile);
//Extraer el texto con PDFBox 3
String texto = pdfService.extractText(tempFile);
//Analizar con Ollama
String analisis = aiService.analyze(texto);
model.addAttribute("analisis", analisis);
return "result";
}
}
Formulario para subir el PDF:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Subir PDF</title>
</head>
<body>
<h1>Subir archivo PDF para analizar</h1>
<form method="post" action="/analyze" enctype="multipart/form-data">
<input type="file" name="file" accept="application/pdf" required />
<button type="submit">Analizar</button>
</form>
</body>
</html>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Resultado del análisis</title>
</head>
<body>
<h1>Análisis del Contrato</h1>
<pre th:text="${analisis}"></pre>
<a href="/">Volver</a>
</body>
</html>
Ejecuta tu aplicación Spring Boot y abre http://localhost:8080/ en tu navegador. Sube un PDF y espera que la IA analice y muestre el resultado.
Puedes encontrar el código completo de este ejemplo en el siguiente repositorio de GitHub:
🔗 Repositorio en GitHub: LexScanAI
En este tutorial aprendiste a:
Manejar archivos PDF con Apache PDFBox 3
Integrar modelos Ollama AI con Spring AI
Crear controladores para subir archivos y mostrar resultados
Usar Thymeleaf para renderizar vistas dinámicas