I have PDF form with keys in placeholders, and I need to replace them with actual data. As I understand, Apache PDFBox do it. Please, tell me, is this case able with Apache PDFBox? Have you examples how to replace text with this library?
I try to do it this way:
public void replaceText() throws IOException {
PDDocument load = PDDocument.load(new File("test_3.pdf"));
List<Object> tokens = null;
for (PDPage pdPage : load.getPages()) {
PDFStreamParser parser = new PDFStreamParser(pdPage);
parser.parse();
tokens = parser.getTokens();
for (int i = 0; i < tokens.size(); i++) {
Object next = tokens.get(i);
if (next instanceof Operator) {
Operator o = (Operator) next;
if ("Tj".equals(o.getName())) {
COSString previous = (COSString) tokens.get(i - 1);
String string = previous.getString();
if ("goal".equals(string)) {
System.out.println(string);
}
string = string.replaceFirst("goal", "GOAL==");
previous.setValue(string.getBytes());
}
}
}
}
PDStream updatedStream = new PDStream(load);
OutputStream out = updatedStream.createOutputStream(COSName.FLATE_DECODE);
ContentStreamWriter tokenWriter = new ContentStreamWriter(out);
tokenWriter.writeTokens(tokens);
out.close();
load.save("output.pdf");
load.close();
}
I want to replace keyword 'goal' with value 'GOAL=='.