Unicode C Requires Chilkat v11.7.0+
Unicode 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 Unicode C Downloads
#include <C_CkPdfW.h>
#include <C_CkJsonObjectW.h>
#include <C_CkStringBuilderW.h>
void ChilkatSample(void)
{
BOOL success;
HCkPdfW pdf;
HCkJsonObjectW json;
HCkStringBuilderW sbText;
HCkJsonObjectW 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 = CkPdfW_Create();
success = CkPdfW_LoadFile(pdf,L"qa_data/pdf/long_report.pdf");
if (success == FALSE) {
wprintf(L"%s\n",CkPdfW_lastErrorText(pdf));
CkPdfW_Dispose(pdf);
return;
}
wprintf(L"Number of pages: %d\n",CkPdfW_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 = CkJsonObjectW_Create();
sbText = CkStringBuilderW_Create();
jsonOut = CkJsonObjectW_Create();
success = CkPdfW_ExtractTextSb(pdf,L"text",json,sbText,jsonOut);
if (success == FALSE) {
wprintf(L"%s\n",CkPdfW_lastErrorText(pdf));
CkPdfW_Dispose(pdf);
CkJsonObjectW_Dispose(json);
CkStringBuilderW_Dispose(sbText);
CkJsonObjectW_Dispose(jsonOut);
return;
}
wprintf(L"Extracted %d characters.\n",CkStringBuilderW_getLength(sbText));
// Save the text to a file.
success = CkStringBuilderW_WriteFile(sbText,L"qa_output/long_report.txt",L"utf-8",FALSE);
if (success == FALSE) {
wprintf(L"%s\n",CkStringBuilderW_lastErrorText(sbText));
CkPdfW_Dispose(pdf);
CkJsonObjectW_Dispose(json);
CkStringBuilderW_Dispose(sbText);
CkJsonObjectW_Dispose(jsonOut);
return;
}
// The JSON output does not contain the text, but it still has the quality report.
wprintf(L"Quality: %s\n",CkJsonObjectW_stringOf(jsonOut,L"quality.rating"));
wprintf(L"Pages with no text (need OCR): [%s]\n",CkJsonObjectW_stringOf(jsonOut,L"quality.pagesNeedingOcr"));
// Sample output:
// Number of pages: 3
// Extracted 4522 characters.
// Quality: good
// Pages with no text (need OCR): []
CkPdfW_Dispose(pdf);
CkJsonObjectW_Dispose(json);
CkStringBuilderW_Dispose(sbText);
CkJsonObjectW_Dispose(jsonOut);
}