Cómo leer archivos PDF en Java con Apache PDFBox (Guía completa con Eclipse)
Para extraer texto de PDFs en Java, la librería estándar open-source es Apache PDFBox. Esta guía cubre la configuración del proyecto en Eclipse con todas las dependencias necesarias y el código para parsear PDFs.
1. Preparar entorno y dependencias
- JDK: Descarga e instala JDK 11/17/21 LTS (Oracle, Eclipse Temurin, Azul Zulu). Configura
JAVA_HOMEyPATH. - Eclipse IDE for Java Developers: Descarga, descomprime, ejecuta
eclipse.exe. Crea workspace. - Proyecto Maven (Recomendado):
File > New > Maven Project>maven-archetype-quickstart> GroupId:com.ejemplo, ArtifactId:pdf-reader. - Dependencias en
pom.xml:<dependencies> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>3.0.2</version> <!-- Versión actual 2024 --> </dependency> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>fontbox</artifactId> <version>3.0.2</version> </dependency> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>jempbox</artifactId> <version>3.0.2</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.23.1</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.23.1</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.15.0</version> </dependency> </dependencies> - Clic derecho en proyecto > Maven > Update Project.
2. Código para extraer texto (PDFBox 3.x)
package com.ejemplo.pdfreader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import java.io.File;
import java.io.IOException;
public class PDFTextExtractor {
public static void main(String[] args) {
if (args.length == 0) {
System.err.println("Uso: java PDFTextExtractor ruta/al/archivo.pdf");
return;
}
String pdfPath = args[0];
File file = new File(pdfPath);
if (!file.exists()) {
System.err.println("Archivo no encontrado: " + pdfPath);
return;
}
try (PDDocument document = PDDocument.load(file)) {
if (document.isEncrypted()) {
System.err.println("El PDF está cifrado. Proporciona contraseña.");
return;
}
PDFTextStripper stripper = new PDFTextStripper();
// Opcional: configurar páginas
// stripper.setStartPage(1);
// stripper.setEndPage(document.getNumberOfPages());
// stripper.setSortByPosition(true); // Orden de lectura natural
String text = stripper.getText(document);
System.out.println(text);
} catch (IOException e) {
System.err.println("Error leyendo PDF: " + e.getMessage());
e.printStackTrace();
}
}
}
3. Ejecutar
- Copia un PDF de prueba a la raíz del proyecto (ej.
prueba.pdf). - Clic derecho en la clase > Run As > Java Application.
- En "Arguments" (pestaña Arguments), en "Program arguments" pon:
prueba.pdf(o ruta relativa). Run. - La consola mostrará el texto extraído.
4. Silenciar log4j (opcional)
Crea src/main/resources/log4j2.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="WARN">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
Alternativas comerciales (si PDFBox falla en PDFs complejos)
- iText 7 (AGPL / Comercial): Potente, pero licencia restrictiva.
- Aspose.PDF for Java (Comercial): Muy robusto, caro.
- PDFTron (Comercial): Alto rendimiento, caro.
Consejos clave
- PDFBox 3.x requiere Java 8+. Usa JDK 11/17/21 LTS.
- Maneja
try-with-resourcespara cerrarPDDocumentautomáticamente. - Para PDFs escaneados (imagen), necesitas OCR (Tesseract via
tess4j) antes de PDFBox. - Los PDFs con formularios, firmas, capas o fuentes incrustadas complejas pueden extraer texto desordenado. Prueba
setSortByPosition(true).
- Cómo reducir la resolución de un PDF con Adobe Acrobat Pro
- Cómo combinar (fusionar) varios archivos PDF en uno solo
- Cómo convertir un PDF a JPEG en Windows (con Recortes / Snipping Tool)
- Cómo crear un archivo PDF gratis (online y offline)
- Cómo cambiar la extensión de un archivo (incluyendo PDF) en Windows y Mac
- Cómo abrir / ver un archivo .PFX (certificado digital) en Windows
