Swift Requires Chilkat v11.7.0+
Swift
Extract PDF Text to a StringBuilder and Save to a File
See more PDF Text Extraction Examples
Demonstrates ExtractTextSb, which writes the extracted text to a StringBuilder instead of returning it as a JSON string. Use it for large documents. The JSON output still receives the quality report.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 long_report.pdf
let pdf = CkoPdf()!
success = pdf.loadFile(filePath: "qa_data/pdf/long_report.pdf")
if success == false {
print("\(pdf.lastErrorText!)")
return
}
print("Number of pages: \(pdf.numPages.intValue)")
// ExtractTextSb takes the same operation and options as ExtractText, but the text
// goes to a StringBuilder. This avoids building a very large JSON string for
// documents with many pages.
let json = CkoJsonObject()!
let sbText = CkoStringBuilder()!
let jsonOut = CkoJsonObject()!
success = pdf.extractTextSb(op: "text", jsonIn: json, sbOut: sbText, jsonOut: jsonOut)
if success == false {
print("\(pdf.lastErrorText!)")
return
}
print("Extracted \(sbText.length.intValue) characters.")
// Save the text to a file.
success = sbText.writeFile(path: "qa_output/long_report.txt", charset: "utf-8", emitBom: false)
if success == false {
print("\(sbText.lastErrorText!)")
return
}
// The JSON output does not contain the text, but it still has the quality report.
print("Quality: \(jsonOut.string(of: "quality.rating")!)")
print("Pages with no text (need OCR): [\(jsonOut.string(of: "quality.pagesNeedingOcr")!)]")
// Sample output:
// Number of pages: 3
// Extracted 4522 characters.
// Quality: good
// Pages with no text (need OCR): []
}