PureBasic Requires Chilkat v11.7.0+
PureBasic
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 PureBasic Downloads
IncludeFile "CkStringBuilder.pb"
IncludeFile "CkJsonObject.pb"
IncludeFile "CkPdf.pb"
Procedure ChilkatExample()
success.i = 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 long_report.pdf
pdf.i = CkPdf::ckCreate()
If pdf.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
success = CkPdf::ckLoadFile(pdf,"qa_data/pdf/long_report.pdf")
If success = 0
Debug CkPdf::ckLastErrorText(pdf)
CkPdf::ckDispose(pdf)
ProcedureReturn
EndIf
Debug "Number of pages: " + Str(CkPdf::ckNumPages(pdf))
; 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.
json.i = CkJsonObject::ckCreate()
If json.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
sbText.i = CkStringBuilder::ckCreate()
If sbText.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
jsonOut.i = CkJsonObject::ckCreate()
If jsonOut.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
success = CkPdf::ckExtractTextSb(pdf,"text",json,sbText,jsonOut)
If success = 0
Debug CkPdf::ckLastErrorText(pdf)
CkPdf::ckDispose(pdf)
CkJsonObject::ckDispose(json)
CkStringBuilder::ckDispose(sbText)
CkJsonObject::ckDispose(jsonOut)
ProcedureReturn
EndIf
Debug "Extracted " + Str(CkStringBuilder::ckLength(sbText)) + " characters."
; Save the text to a file.
success = CkStringBuilder::ckWriteFile(sbText,"qa_output/long_report.txt","utf-8",0)
If success = 0
Debug CkStringBuilder::ckLastErrorText(sbText)
CkPdf::ckDispose(pdf)
CkJsonObject::ckDispose(json)
CkStringBuilder::ckDispose(sbText)
CkJsonObject::ckDispose(jsonOut)
ProcedureReturn
EndIf
; The JSON output does not contain the text, but it still has the quality report.
Debug "Quality: " + CkJsonObject::ckStringOf(jsonOut,"quality.rating")
Debug "Pages with no text (need OCR): [" + CkJsonObject::ckStringOf(jsonOut,"quality.pagesNeedingOcr") + "]"
; Sample output:
; Number of pages: 3
; Extracted 4522 characters.
; Quality: good
; Pages with no text (need OCR): []
CkPdf::ckDispose(pdf)
CkJsonObject::ckDispose(json)
CkStringBuilder::ckDispose(sbText)
CkJsonObject::ckDispose(jsonOut)
ProcedureReturn
EndProcedure