ASPOSE PDF JAVA - How to replace word in PDF with new word which has html tag, superscript and subscript letter/word

We have license version of ASPOSE PDF 10.6.1 and we are using it to replace the text pattern in PDF with different text.

e.g. Replace $xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx$ with “some text”. We recently came across an issue where we received text which has superscript with html tag which got replaced as is.

Please find the following code which is not working. After research I found we have setSuperscript and other superscript related method in TextState, TextFragmentState classes of aspose.pdf-18.10.jar but I don’t know how to use it. I don’t know which classes/methods should I use for this requirement. Can you please help me to find out a way replace a text in PDF with new text which has superscript in it.

I appreciate your quick response. Please let me know if you need any other information about this issue.

Document pdfDocument = null;
TextFragmentAbsorber nameAbsorber = new TextFragmentAbsorber("$xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx$");

byte[] pdf = FileUtils.readFileToByteArray(FileUtils.getFile(“PDF File Path which has above text pattern”));
ByteArrayInputStream byteOverlayStream = new ByteArrayInputStream(pdf);

Document pdfDocument = new Document(byteOverlayStream);

isNameReplaceSuccess = replaceText(pdfDocument, nameAbsorber, “Test <Sup>®</Sup> Registered Mark”);

private static boolean replaceText(Document pdfDocument, TextFragmentAbsorber absorber, String newText) {
boolean success = false;
pdfDocument.getPages().accept(absorber);
TextFragmentCollection tfc = absorber.getTextFragments();
for (TextFragment textFragment : (Iterable) tfc) {
textFragment.setText(newText);
success = true;
}
return success;
}

@avinashshete

Thank you for contacting support.

Would you please upgrade to Aspose.PDF for Java 18.10.2 because latest version includes more features and bug fixes. Moreover, support is provided based on latest available version. You may Replace Text in a PDF Document or Add HTML String as per your requirements.

Furthermore, you can set TextState.Superscript and TextState.Subscript properties for TextSegment and TextFragment objects as in the code snippet below:

Document document = new Document();
Page page = document.getPages().add();
TextFragment fragment1 = new TextFragment();
TextSegment seg11 = new TextSegment("8");
fragment1.getSegments().add(seg11);
TextSegment seg12 = new TextSegment("th");
fragment1.getSegments().add(seg12);
seg12.getTextState().setSubscript(true);
TextSegment seg13 = new TextSegment(" M");
fragment1.getSegments().add(seg13);
seg13.getTextState().setSuperscript(true);

We hope this will be helpful. Please feel free to contact us if you need any further assistance.