Asad.ali. Thank you for your quick response.
Below source code I written to Update “Payment” word to “Transaction” word in first two Paragraphs after “Greetings” word found in PDF. In this code I am trying to Replace Payment Word in first occurrence Paragraph. This code Identifying Paragraph and extracting first Paragraph but not able to write back PDF.
Can you please share java code snippet which will Identify first two Paragraphs and replace Word after specific word found(Like Greetings Word).
// Code Snippet I am trying
public static void main(String[] args) {
Document pdfDocument = null;
pdfDocument = new Document(SRC);
Test1(“Payment”, “Transaction”)
}
public static void Test1(String originalText,String longerText) {
ParagraphAbsorber paragraphAbsorber = new ParagraphAbsorber();
paragraphAbsorber.visit(pdfDocument.getPages().get_Item(1));
String textInParagraph = "";
boolean foundIt = false;
MarkupParagraph originalParagraph = null;
for (PageMarkup markup : paragraphAbsorber.getPageMarkups()) {
if (foundIt) break;
for (MarkupSection section : markup.getSections()) {
if (foundIt) break;
for (MarkupParagraph paragraph : section.getParagraphs()) {
if (foundIt) break;
for (TextFragment fragment : paragraph.getFragments()) {
if (fragment.getText().equals(originalText) || originalText.equals(fragment.getText())) {
textInParagraph = paragraph.getText();
originalParagraph = paragraph;
foundIt = true;
break;
}
}
}
}
}
String searchableContent = textInParagraph.replace(" ", "\\s+");
TextFragmentAbsorber absorber = new TextFragmentAbsorber(searchableContent);
absorber.getTextReplaceOptions().setReplaceAdjustmentAction(TextReplaceOptions.ReplaceAdjustment.WholeWordsHyphenation);
pdfDocument.getPages().accept(absorber);
if (textInParagraph.length() > 0) {
String newText = textInParagraph.replaceAll(originalText, longerText);
TextFragmentCollection textFragmentCollection = absorber.getTextFragments();
for (TextFragment fragment : (Iterable<TextFragment>) textFragmentCollection) {
fragment.getReplaceOptions().setReplaceAdjustmentAction(TextReplaceOptions.ReplaceAdjustment.WholeWordsHyphenation);
fragment.setText(newText);
}
}
}
TestPDF.pdf (106.1 KB)