Swift Requires Chilkat v11.7.0+
Swift
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 Swift Downloads
func chilkatTest() {
var success: Bool = false
// 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
let pdf = CkoPdf()!
success = pdf.loadFile(filePath: "qa_data/pdf/spans_table.pdf")
if success == false {
print("\(pdf.lastErrorText!)")
return
}
let json = CkoJsonObject()!
let jsonOut = CkoJsonObject()!
// 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.
json.updateInt(jsonPath: "minRows", value: 3)
json.updateInt(jsonPath: "minColumns", value: 3)
success = pdf.extractText(op: "tables", jsonIn: json, jsonOut: jsonOut)
if success == false {
print("\(pdf.lastErrorText!)")
return
}
print("Tables found: \(jsonOut.int(of: "count").intValue)")
print("\(jsonOut.int(of: "tables[0].rows").intValue) rows x \(jsonOut.int(of: "tables[0].columns").intValue) 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.
var rowSpan: Int
var colSpan: Int
var j: Int = 0
var count_j: Int = jsonOut.size(ofArray: "tables[0].cells").intValue
while j < count_j {
jsonOut.j = j
rowSpan = jsonOut.int(of: "tables[0].cells[j].rowSpan").intValue
colSpan = jsonOut.int(of: "tables[0].cells[j].colSpan").intValue
if (rowSpan > 1) || (colSpan > 1) {
print("row \(jsonOut.int(of: "tables[0].cells[j].row").intValue), col \(jsonOut.int(of: "tables[0].cells[j].col").intValue): \"\(jsonOut.string(of: "tables[0].cells[j].text")!)\" spans \(rowSpan) row(s) and \(colSpan) column(s)")
}
j = 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)
}