C Requires Chilkat v11.7.0+
C
Audit a PDF First, Optimize Only If It Is Worth It
See more PDF Optimization Examples
Demonstrates deciding whether to rewrite a PDF at all. "audit" costs a fraction of a second and changes nothing, so a batch job can audit every file and optimize only those where enough would be saved. Here the threshold is a tenth of the file; a file already as small as it can be is left alone.Chilkat C Downloads
#include <C_CkPdf.h>
#include <C_CkJsonObject.h>
void ChilkatSample(void)
{
BOOL success;
HCkPdf pdf;
HCkJsonObject json;
HCkJsonObject jsonOut;
int fileSize;
int estimated;
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 watersense_accomplishments.pdf
pdf = CkPdf_Create();
success = CkPdf_LoadFile(pdf,"qa_data/pdf/watersense_accomplishments.pdf");
if (success == FALSE) {
printf("%s\n",CkPdf_lastErrorText(pdf));
CkPdf_Dispose(pdf);
return;
}
json = CkJsonObject_Create();
jsonOut = CkJsonObject_Create();
success = CkPdf_Optimize(pdf,"audit",json,jsonOut);
if (success == FALSE) {
printf("%s\n",CkPdf_lastErrorText(pdf));
CkPdf_Dispose(pdf);
CkJsonObject_Dispose(json);
CkJsonObject_Dispose(jsonOut);
return;
}
fileSize = CkJsonObject_IntOf(jsonOut,"fileSize");
estimated = CkJsonObject_IntOf(jsonOut,"estimatedSavings.total");
printf("fileSize: %d\n",fileSize);
printf("estimated: %d\n",estimated);
// Only bother when at least a tenth of the file would go.
if (estimated > (fileSize / 10)) {
printf("Worth optimizing.\n");
success = CkPdf_Optimize(pdf,"optimize",json,jsonOut);
if (success == FALSE) {
printf("%s\n",CkPdf_lastErrorText(pdf));
CkPdf_Dispose(pdf);
CkJsonObject_Dispose(json);
CkJsonObject_Dispose(jsonOut);
return;
}
success = CkPdf_WriteFile(pdf,"qa_output/watersense_optimized.pdf");
if (success == FALSE) {
printf("%s\n",CkPdf_lastErrorText(pdf));
CkPdf_Dispose(pdf);
CkJsonObject_Dispose(json);
CkJsonObject_Dispose(jsonOut);
return;
}
printf("bytesSaved: %d\n",CkJsonObject_IntOf(jsonOut,"bytesSaved"));
}
else {
printf("Already small enough; left as it is.\n");
}
CkPdf_Dispose(pdf);
CkJsonObject_Dispose(json);
CkJsonObject_Dispose(jsonOut);
}