Java Requires Chilkat v11.7.0+
Chilkat2 Java
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 Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.Pdf;
public class ChilkatExample {
public static void main(String[] args) {
// 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 pdf = new Pdf();
try {
pdf.loadFile("qa_data/pdf/invoice_template.pdf");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
JsonObject json = new JsonObject();
json.updateString("placeholders.customer", "Acme Corp");
// (The other placeholders are left as they are for this example.)
json.updateString("unusedPlaceholders", "keep");
JsonObject jsonOut = new JsonObject();
try {
pdf.textReplace("apply", json, jsonOut);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
System.out.println("In the page content, customer was replaced " + jsonOut.intOf("replacements[0].count") + " times.");
// Where else the placeholder occurs, untouched:
int i = 0;
int count_i = jsonOut.sizeOfArray("notReplaced");
while (i < count_i) {
jsonOut.setI(i);
System.out.println("not replaced: {{" + jsonOut.stringOf("notReplaced[i].field") + "}} in " + jsonOut.stringOf("notReplaced[i].where"));
i = i + 1;
}
try {
pdf.writeFile("qa_output/invoice_customer.pdf");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// Sample output:
// In the page content, customer was replaced 2 times.
// not replaced: {{customer}} in metadata
// not replaced: {{customer}} in linkTarget
}
}