Extraer datos de tabla en PDF con Java
Contents
[
Hide
]
Extraer tablas de PDF
Utilice TableAbsorber para encontrar tablas en cada página e iterar a través de filas, celdas, fragmentos de texto y segmentos de texto.
- Abra el PDF de origen en una instancia de
Document. - Itere a través de los objetos
Pagedel documento porque las tablas se detectan página por página. - Cree un
TableAbsorberpara cada página y llamevisit(page)para poblar la lista de tablas detectadas. - Itere a través de lo detectado
AbsorbedTable,AbsorbedRow,AbsorbedCell,TextFragment, yTextSegmentobjetos. - Construya el texto de fila extraído del contenido del fragmento e imprima los datos de la tabla.
public static void extractTablesFromPdf(Path inputFile) {
try (Document document = new Document(inputFile.toString())) {
for (Page page : document.getPages()) {
TableAbsorber absorber = new TableAbsorber();
absorber.visit(page);
for (AbsorbedTable table : absorber.getTableList()) {
System.out.println("Table");
for (AbsorbedRow row : table.getRowList()) {
StringBuilder rowText = new StringBuilder();
for (AbsorbedCell cell : row.getCellList()) {
if (rowText.length() > 0) {
rowText.append("|");
}
StringBuilder cellText = new StringBuilder();
for (TextFragment fragment : cell.getTextFragments()) {
StringBuilder fragmentText = new StringBuilder();
for (TextSegment segment : fragment.getSegments()) {
fragmentText.append(segment.getText());
}
if (cellText.length() > 0) {
cellText.append("|");
}
cellText.append(fragmentText);
}
rowText.append(cellText);
}
System.out.println(rowText);
}
}
}
}
}
Extraer una tabla de un área marcada específica
Este ejemplo encuentra una anotación cuadrada, compara su rectángulo con cada tabla detectada y devuelve solo las tablas dentro de la región marcada.
- Abra el PDF de origen en una instancia de
Document. - Obtenga el objetivo
Pagey localice el cuadradoAnnotationque marca la región de extracción. - Cree un
TableAbsorbery llamevisit(page)para detectar tablas en esa página. - Compare cada detectado
AbsorbedTableRectanglecon los límites del rectángulo de anotación. - Itere a través de la coincidencia
AbsorbedRowyAbsorbedCellobjetos y reconstruya el texto de la fila. - Imprima los datos de la tabla solo para la región marcada.
public static void extractTableFromSpecificArea(Path inputFile) {
try (Document document = new Document(inputFile.toString())) {
Page page = document.getPages().get_Item(1);
Annotation squareAnnotation = null;
for (Annotation annotation : page.getAnnotations()) {
if (annotation.getAnnotationType() == AnnotationType.Square) {
squareAnnotation = annotation;
break;
}
}
if (squareAnnotation == null) {
System.out.println("No square annotation found.");
return;
}
TableAbsorber absorber = new TableAbsorber();
absorber.visit(page);
for (AbsorbedTable table : absorber.getTableList()) {
Rectangle tableRect = table.getRectangle();
Rectangle annotationRect = squareAnnotation.getRect();
boolean isInRegion = annotationRect.getLLX() < tableRect.getLLX()
&& annotationRect.getLLY() < tableRect.getLLY()
&& annotationRect.getURX() > tableRect.getURX()
&& annotationRect.getURY() > tableRect.getURY();
if (isInRegion) {
for (AbsorbedRow row : table.getRowList()) {
StringBuilder rowText = new StringBuilder();
for (AbsorbedCell cell : row.getCellList()) {
if (rowText.length() > 0) {
rowText.append("|");
}
StringBuilder cellText = new StringBuilder();
for (TextFragment fragment : cell.getTextFragments()) {
StringBuilder fragmentText = new StringBuilder();
for (TextSegment segment : fragment.getSegments()) {
fragmentText.append(segment.getText());
}
if (cellText.length() > 0) {
cellText.append("|");
}
cellText.append(fragmentText);
}
rowText.append(cellText);
}
System.out.println(rowText);
}
}
}
}
}
Exportar tablas a Excel
- Abra el PDF de origen en una instancia de
Document. - Cree
ExcelSaveOptionspara la exportación. - Establezca el formato de salida de Excel a
XLSXpor lo tanto, el diseño de tabla detectado se escribe como un libro de Excel. - Llame
document.save(outputFile.toString(), excelSave)para exportar el documento en formato Excel.
public static void exportTablesToExcel(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
ExcelSaveOptions excelSave = new ExcelSaveOptions();
excelSave.setFormat(ExcelSaveOptions.ExcelFormat.XLSX);
document.save(outputFile.toString(), excelSave);
}
}