Sample code for 30+ languages & platforms
Tcl Requires Chilkat v11.7.0+

Extract a PDF Table with Merged Cells

See more PDF Text Extraction Examples

Demonstrates how merged cells are reported by the "tables" operation: a header cell that spans several columns has colSpan greater than 1, and a row label that spans several rows has rowSpan greater than 1. Also shows the minRows and minColumns options.

Chilkat Tcl Downloads

Tcl

load ./chilkat.dll

set success 0

#  This example requires the Chilkat API to have been previously unlocked.
#  See Global Unlock Sample for sample code.

#  The PDF used in this example is available at spans_table.pdf

set pdf [new_CkPdf]

set success [CkPdf_LoadFile $pdf "qa_data/pdf/spans_table.pdf"]
if {$success == 0} then {
    puts [CkPdf_lastErrorText $pdf]
    delete_CkPdf $pdf
    exit
}

set json [new_CkJsonObject]

set jsonOut [new_CkJsonObject]

#  Grids smaller than minRows x minColumns are not reported as tables.  The defaults are 2 and 2.
#  Setting them higher skips small boxes that are not really tables.
CkJsonObject_UpdateInt $json "minRows" 3
CkJsonObject_UpdateInt $json "minColumns" 3

set success [CkPdf_ExtractText $pdf "tables" $json $jsonOut]
if {$success == 0} then {
    puts [CkPdf_lastErrorText $pdf]
    delete_CkPdf $pdf
    delete_CkJsonObject $json
    delete_CkJsonObject $jsonOut
    exit
}

puts "Tables found: [CkJsonObject_IntOf $jsonOut count]"
puts [CkJsonObject_IntOf $jsonOut {tables[0].rows}] rows x [CkJsonObject_IntOf $jsonOut {tables[0].columns}] columns

#  A merged cell is reported once, at its top-left position, with its spans.
#  The positions it covers have no cell of their own.

set j 0
set count_j [CkJsonObject_SizeOfArray $jsonOut "tables[0].cells"]
while {$j < $count_j} {
    CkJsonObject_put_J $jsonOut $j
    set rowSpan [CkJsonObject_IntOf $jsonOut "tables[0].cells[j].rowSpan"]
    set colSpan [CkJsonObject_IntOf $jsonOut "tables[0].cells[j].colSpan"]
    if {expr [$rowSpan > 1]  ||  [$colSpan > 1]} then {
        puts "row [CkJsonObject_IntOf $jsonOut {tables[0].cells[j].row}], col [CkJsonObject_IntOf $jsonOut {tables[0].cells[j].col}]: \"[CkJsonObject_stringOf $jsonOut {tables[0].cells[j].text}]\" spans $rowSpan row(s) and $colSpan column(s)"
    }

    set j [expr $j + 1]
}

#  Sample output:

#  Tables found: 1
#  6 rows x 6 columns
#  row 0, col 0: "Area" spans 2 row(s) and 1 column(s)
#  row 0, col 1: "City" spans 2 row(s) and 1 column(s)
#  row 0, col 2: "First Half" spans 1 row(s) and 2 column(s)
#  row 0, col 4: "Second Half" spans 1 row(s) and 2 column(s)
#  row 2, col 0: "East" spans 2 row(s) and 1 column(s)
#  row 4, col 0: "West" spans 2 row(s) and 1 column(s)

delete_CkPdf $pdf
delete_CkJsonObject $json
delete_CkJsonObject $jsonOut