Extrair dados da tabela em PDF com Java
Contents
[
Hide
]
Extrair tabelas de PDF
Use TableAbsorber para encontrar tabelas em cada página e iterar pelas linhas, células, fragmentos de texto e segmentos de texto.
- Abra o PDF de origem em uma instância de Document.
- Itere através do documento objetos Page porque as tabelas são detectadas página por página.
- Crie um TableAbsorber para cada página e chamar
visit(page)para preencher a lista de tabelas detectadas. - Itere pelos detectados AbsorbedTable, AbsorbedRow, AbsorbedCell, TextFragment, e objetos
TextSegment. - Construa o texto da linha extraída a partir do conteúdo do fragmento e imprima os dados da tabela.
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);
}
}
}
}
}
Extrair uma tabela de uma área marcada específica
Este exemplo encontra uma anotação quadrada, compara seu retângulo com cada tabela detectada e exibe apenas as tabelas dentro da região marcada.
- Abra o PDF de origem em uma instância de Document.
- Obtenha a página de destino Page e localize o quadrado Annotation que marca a região de extração.
- Crie um TableAbsorber e chame
visit(page)para detectar tabelas nessa página. - Compare cada detectado AbsorbedTable Rectangle com os limites do retângulo da anotação.
- Itere através da correspondência objetos AbsorbedRow e AbsorbedCell e reconstruir o texto da linha.
- Imprima os dados da tabela apenas para a região 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 tabelas para Excel
- Abra o PDF de origem em uma instância de Document.
- Crie ExcelSaveOptions para a exportação.
- Defina o formato de saída do Excel como
XLSX; assim, o layout da tabela detectado é gravado como uma pasta de trabalho do Excel. - Chame
document.save(outputFile.toString(), excelSave)para exportar o documento no 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);
}
}