Extraer datos de una tabla en PDF con Python

Extraer tablas de PDF programáticamente

Usar TableAbsorber para detectar tablas en cada página de un Documento. Después de visitar una página, itera a través de table_list, luego recorre cada fila y celda para reconstruir el contenido de la tabla en un formato de texto legible.

  1. Abra el PDF como un Document.
  2. Iterar a través de las páginas en document.pages.
  3. Crear un TableAbsorber para cada página y llame visit(page).
  4. Recorre las tablas, filas y celdas detectadas.
  5. Lee fragmentos de texto de cada celda y ensambla la salida de la fila extraída.
import aspose.pdf as apdf
from os import path

path_infile = path.join(self.dataDir, infile)

# Open PDF document
document = apdf.Document(path_infile)

# Iterate through each page in the document
for page in document.pages:
    absorber = apdf.text.TableAbsorber()
    absorber.visit(page)

    for table in absorber.table_list:
        print("Table")
        for row in table.row_list:
            row_text = []
            for cell in row.cell_list:
                cell_text = []
                for fragment in cell.text_fragments:
                    cell_text.append("".join(seg.text for seg in fragment.segments))
                row_text.append("|".join(cell_text))
            print("|".join(row_text))

Extraer tabla en área específica de la página PDF

Si necesita extraer solo tablas ubicadas dentro de una región marcada, combine TableAbsorber con un SquareAnnotation. En este ejemplo, el rectángulo de anotación se usa como límite, y solo se procesan las tablas que están completamente contenidas dentro de esa región.

  1. Abra el PDF como un Document.
  2. Seleccione la página de destino.
  3. Encuentre la anotación cuadrada que marca la región de interés.
  4. Crear un TableAbsorber y visite la página.
  5. Compara cada rectángulo de tabla detectado con el rectángulo de anotación.
  6. Procesa sólo las tablas que estén completamente dentro del área marcada.
import aspose.pdf as apdf
from os import path

# The path to the documents directory
path_infile = path.join(self.dataDir, infile)

# Open PDF document
document = apdf.Document(path_infile)

# Get the first page (index starts from 1 in Aspose.PDF)
page = document.pages[1]

# Find the first square annotation
square_annotation = next(
    (
        ann
        for ann in page.annotations
        if ann.annotation_type == apdf.annotations.AnnotationType.SQUARE
    ),
    None,
)

if square_annotation is None:
    print("No square annotation found.")
    return

# Initialize the TableAbsorber
absorber = apdf.text.TableAbsorber()
absorber.visit(page)

# Iterate through tables on the page
for table in absorber.table_list:
    table_rect = table.rectangle
    annotation_rect = square_annotation.rect

    # Check if the table is inside the annotation region
    is_in_region = (
        annotation_rect.llx < table_rect.llx
        and annotation_rect.lly < table_rect.lly
        and annotation_rect.urx > table_rect.urx
        and annotation_rect.ury > table_rect.ury
    )

    if is_in_region:
        for row in table.row_list:
            row_text = []
            for cell in row.cell_list:
                cell_text = []
                for fragment in cell.text_fragments:
                    cell_text.append("".join(seg.text for seg in fragment.segments))
                row_text.append("|".join(cell_text))
            print("|".join(row_text))

Exportar datos de tabla de PDF a CSV

Cuando necesites los datos extraídos en un formato compatible con hojas de cálculo, guarda el PDF usando ExcelSaveOptions y establezca el formato de salida en CSV. El archivo resultante se puede abrir en Excel, Google Sheets o importarse en flujos de trabajo de análisis.

  1. Abra el PDF de origen como un Documento.
  2. Crear un ExcelSaveOptions instancia.
  3. Establecer excel_save.format a ExcelSaveOptions.ExcelFormat.CSV.
  4. Guarde el documento en la ruta CSV de destino.
import aspose.pdf as apdf
from os import path

path_infile = path.join(self.dataDir, infile)
path_outfile = path.join(self.dataDir, outfile)

document = apdf.Document(path_infile)
excel_save = apdf.ExcelSaveOptions()
excel_save.format = apdf.ExcelSaveOptions.ExcelFormat.CSV
document.save(path_outfile, excel_save)