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

PDF Placeholders with Other Delimiters: [[name]]

See more PDF Text Replacement Examples

Demonstrates the "placeholderSyntax" option. Placeholders are {{name}} by default; a template written with other delimiters, such as [[name]] or <>, says so with placeholderSyntax, written around the word "name".

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.Pdf;

public class ChilkatExample {

    public static void main(String[] args) {
        boolean 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 letter_template.pdf

        Pdf pdf = new Pdf();
        try {
            pdf.loadFile("qa_data/pdf/letter_template.pdf");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // The letter reads: "Dear [[name]]," ... "expires on [[expiry]]" ... "[[amount]] per year" ... "[[agent]]".
        JsonObject json = new JsonObject();
        json.updateString("placeholderSyntax", "[[name]]");
        json.updateString("placeholders.date", "October 18, 2026");
        json.updateString("placeholders.name", "Ms. Rivera");
        json.updateString("placeholders.expiry", "December 31, 2026");
        json.updateString("placeholders.amount", "$299.00");
        json.updateString("placeholders.agent", "Dana Whitfield, Account Manager");

        JsonObject jsonOut = new JsonObject();
        try {
            pdf.textReplace("apply", json, jsonOut);
            success = true;
        } catch (ChilkatException e) {
            success = false;
        }
        if (!success) {
            System.out.println("Not applied: " + jsonOut.emit());
            if (!success) {
                System.out.println(pdf.getLastErrorText());
                return;
            }
        }

        int i = 0;
        int count_i = jsonOut.sizeOfArray("replacements");
        while (i < count_i) {
            jsonOut.setI(i);
            System.out.println("[[" + jsonOut.stringOf("replacements[i].field") + "]] replaced");
            i = i + 1;
        }

        try {
            pdf.writeFile("qa_output/letter_rivera.pdf");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // Sample output:

        // [[date]] replaced
        // [[name]] replaced
        // [[expiry]] replaced
        // [[amount]] replaced
        // [[agent]] replaced
    }
}