C Requires Chilkat v11.7.0+
C
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 C Downloads
#include <C_CkPdf.h>
#include <C_CkJsonObject.h>
#include <C_CkStringBuilder.h>
void ChilkatSample(void)
{
BOOL success;
HCkPdf pdf;
HCkJsonObject json;
HCkStringBuilder sbText;
HCkJsonObject jsonOut;
success = 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
pdf = CkPdf_Create();
success = CkPdf_LoadFile(pdf,"qa_data/pdf/long_report.pdf");
if (success == FALSE) {
printf("%s\n",CkPdf_lastErrorText(pdf));
CkPdf_Dispose(pdf);
return;
}
printf("Number of pages: %d\n",CkPdf_getNumPages(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 = CkJsonObject_Create();
sbText = CkStringBuilder_Create();
jsonOut = CkJsonObject_Create();
success = CkPdf_ExtractTextSb(pdf,"text",json,sbText,jsonOut);
if (success == FALSE) {
printf("%s\n",CkPdf_lastErrorText(pdf));
CkPdf_Dispose(pdf);
CkJsonObject_Dispose(json);
CkStringBuilder_Dispose(sbText);
CkJsonObject_Dispose(jsonOut);
return;
}
printf("Extracted %d characters.\n",CkStringBuilder_getLength(sbText));
// Save the text to a file.
success = CkStringBuilder_WriteFile(sbText,"qa_output/long_report.txt","utf-8",FALSE);
if (success == FALSE) {
printf("%s\n",CkStringBuilder_lastErrorText(sbText));
CkPdf_Dispose(pdf);
CkJsonObject_Dispose(json);
CkStringBuilder_Dispose(sbText);
CkJsonObject_Dispose(jsonOut);
return;
}
// The JSON output does not contain the text, but it still has the quality report.
printf("Quality: %s\n",CkJsonObject_stringOf(jsonOut,"quality.rating"));
printf("Pages with no text (need OCR): [%s]\n",CkJsonObject_stringOf(jsonOut,"quality.pagesNeedingOcr"));
// Sample output:
// Number of pages: 3
// Extracted 4522 characters.
// Quality: good
// Pages with no text (need OCR): []
CkPdf_Dispose(pdf);
CkJsonObject_Dispose(json);
CkStringBuilder_Dispose(sbText);
CkJsonObject_Dispose(jsonOut);
}