Sample code for 30+ languages & platforms
C Requires Chilkat v11.7.0+

What PDF Text Replacement Does Not Change: Metadata, Links, Form Fields

See more PDF Text Replacement Examples

TextReplace changes the page content only. A placeholder that also appears in the document's metadata (the Title, Author, Subject, Keywords, Creator or Producer), in a link's target URL, or in a form field's value is left as it is and reported in "notReplaced" with "where" saying which. The invoice template's title is "Invoice for {{customer}}" and its "View this invoice online" link points at a URL that holds {{customer}}.

Chilkat C Downloads

C
#include <C_CkPdf.h>
#include <C_CkJsonObject.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkPdf pdf;
    HCkJsonObject json;
    HCkJsonObject jsonOut;
    int i;
    int count_i;

    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 invoice_template.pdf

    pdf = CkPdf_Create();
    success = CkPdf_LoadFile(pdf,"qa_data/pdf/invoice_template.pdf");
    if (success == FALSE) {
        printf("%s\n",CkPdf_lastErrorText(pdf));
        CkPdf_Dispose(pdf);
        return;
    }

    json = CkJsonObject_Create();
    CkJsonObject_UpdateString(json,"placeholders.customer","Acme Corp");
    //  (The other placeholders are left as they are for this example.)
    CkJsonObject_UpdateString(json,"unusedPlaceholders","keep");

    jsonOut = CkJsonObject_Create();
    success = CkPdf_TextReplace(pdf,"apply",json,jsonOut);
    if (success == FALSE) {
        printf("%s\n",CkPdf_lastErrorText(pdf));
        CkPdf_Dispose(pdf);
        CkJsonObject_Dispose(json);
        CkJsonObject_Dispose(jsonOut);
        return;
    }

    printf("In the page content, customer was replaced %d times.\n",CkJsonObject_IntOf(jsonOut,"replacements[0].count"));

    //  Where else the placeholder occurs, untouched:
    i = 0;
    count_i = CkJsonObject_SizeOfArray(jsonOut,"notReplaced");
    while (i < count_i) {
        CkJsonObject_putI(jsonOut,i);
        printf("not replaced: {{%s}} in %s\n",CkJsonObject_stringOf(jsonOut,"notReplaced[i].field"),CkJsonObject_stringOf(jsonOut,"notReplaced[i].where"));
        i = i + 1;
    }

    success = CkPdf_WriteFile(pdf,"qa_output/invoice_customer.pdf");
    if (success == FALSE) {
        printf("%s\n",CkPdf_lastErrorText(pdf));
        CkPdf_Dispose(pdf);
        CkJsonObject_Dispose(json);
        CkJsonObject_Dispose(jsonOut);
        return;
    }

    //  Sample output:

    //  In the page content, customer was replaced 2 times.
    //  not replaced: {{customer}} in metadata
    //  not replaced: {{customer}} in linkTarget


    CkPdf_Dispose(pdf);
    CkJsonObject_Dispose(json);
    CkJsonObject_Dispose(jsonOut);

    }