Extraer datos de tabla en PDF con Java

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.

  1. Abra el PDF de origen en una instancia de Document.
  2. Itere a través de los objetos Page del documento porque las tablas se detectan página por página.
  3. Cree un TableAbsorber para cada página y llame visit(page) para poblar la lista de tablas detectadas.
  4. Itere a través de lo detectado AbsorbedTable, AbsorbedRow, AbsorbedCell, TextFragment, y TextSegment objetos.
  5. 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.

  1. Abra el PDF de origen en una instancia de Document.
  2. Obtenga el objetivo Page y localice el cuadrado Annotation que marca la región de extracción.
  3. Cree un TableAbsorber y llame visit(page) para detectar tablas en esa página.
  4. Compare cada detectado AbsorbedTable Rectangle con los límites del rectángulo de anotación.
  5. Itere a través de la coincidencia AbsorbedRow y AbsorbedCell objetos y reconstruya el texto de la fila.
  6. 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

  1. Abra el PDF de origen en una instancia de Document.
  2. Cree ExcelSaveOptions para la exportación.
  3. Establezca el formato de salida de Excel a XLSX por lo tanto, el diseño de tabla detectado se escribe como un libro de Excel.
  4. 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);
    }
}