Replace Text in PDF with Java
Aspose.PDF for Java provides both simple replacement and layout-aware replacement features through TextFragmentAbsorber and replace options.
Replace text on all pages
Use this example when the same phrase should be replaced throughout the entire document.
- Open the source PDF document.
- Search all pages for the target phrase with
TextFragmentAbsorber. - Replace the matched text and save the updated PDF.
public static void replaceTextOnAllPages(Path inputFile, Path outputFile) {
String searchPhrase = "PDF";
String replacePhrase = "pdf";
try (Document document = new Document(inputFile.toString())) {
TextFragmentAbsorber absorber = new TextFragmentAbsorber(searchPhrase);
document.getPages().accept(absorber);
for (TextFragment fragment : absorber.getTextFragments()) {
fragment.setText(replacePhrase);
}
document.save(outputFile.toString());
}
}
Replace text in a specific page region
Use this example when replacement should be limited to a selected rectangle on one page.
- Open the source PDF document.
- Configure
TextSearchOptionswith page bounds and a target rectangle. - Replace the matched text inside that region and save the document.
public static void replaceTextInParticularPageRegion(Path inputFile, Path outputFile) {
String searchPhrase = "doc";
String replacePhrase = "DOC";
try (Document document = new Document(inputFile.toString())) {
TextFragmentAbsorber absorber = new TextFragmentAbsorber(searchPhrase);
absorber.getTextSearchOptions().setLimitToPageBounds(true);
absorber.getTextSearchOptions().setRectangle(new Rectangle(300, 442, 500, 742, true));
document.getPages().get_Item(1).accept(absorber);
for (TextFragment fragment : absorber.getTextFragments()) {
fragment.setText(replacePhrase);
}
document.save(outputFile.toString());
}
}
Replace text and adjust spacing inside a shifted rectangle
Use this example when replacement text should stay on the page with adjusted spacing but the font size should remain unchanged.
- Open the source PDF and collect text fragments from the target page.
- Modify the replacement rectangle and choose
AdjustSpaceWidthbehavior. - Set the new text and save the document.
public static void replaceTextAndResizeAndShiftWithoutChangingFontSize(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
TextFragmentAbsorber absorber = new TextFragmentAbsorber();
absorber.visit(document.getPages().get_Item(1));
TextFragment fragment = absorber.getTextFragments().get_Item(1);
String text = fragment.getText();
Rectangle rectangle = fragment.getRectangle();
rectangle.setLLX(rectangle.getLLX() + 50);
rectangle.setURX(rectangle.getURX() - 50);
fragment.getReplaceOptions().setRectangle(rectangle);
fragment.getReplaceOptions().setReplaceAdjustmentAction(TextReplaceOptions.ReplaceAdjustment.AdjustSpaceWidth);
fragment.setText(text + " " + text);
document.save(outputFile.toString());
}
}
Replace text inside a larger paragraph rectangle
Use this example when replacement text should expand into a larger page area.
- Open the source PDF and get the first text fragment from the target page.
- Build a larger replacement rectangle from the page media box.
- Apply the replacement options and save the PDF.
public static void replaceTextAndResizeAndShiftParagraph(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
TextFragmentAbsorber absorber = new TextFragmentAbsorber();
absorber.visit(document.getPages().get_Item(1));
TextFragment fragment = absorber.getTextFragments().get_Item(1);
String text = fragment.getText();
Rectangle rectangle = document.getPages().get_Item(1).getMediaBox();
rectangle.setLLX(rectangle.getLLX() + 20);
rectangle.setURX(rectangle.getURX() - 20);
rectangle.setURY(rectangle.getURY() - 20);
fragment.getReplaceOptions().setRectangle(rectangle);
fragment.getReplaceOptions().setReplaceAdjustmentAction(TextReplaceOptions.ReplaceAdjustment.AdjustSpaceWidth);
fragment.setText(text + " " + text);
document.save(outputFile.toString());
}
}
Replace text and scale the font to fill the rectangle
Use this example when replacement text should enlarge to fill a target area.
- Open the source PDF and access the target text fragment.
- Define a replacement rectangle and enable
ScaleToFillfont adjustment. - Set the new text and save the updated document.
public static void replaceTextAndResizeAndExpandFont(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
TextFragmentAbsorber absorber = new TextFragmentAbsorber();
absorber.visit(document.getPages().get_Item(1));
TextFragment fragment = absorber.getTextFragments().get_Item(1);
String text = fragment.getText();
fragment.getReplaceOptions().setRectangle(new Rectangle(100, 300, 512, 692, true));
fragment.getReplaceOptions().setReplaceAdjustmentAction(TextReplaceOptions.ReplaceAdjustment.AdjustSpaceWidth);
fragment.getReplaceOptions().setFontSizeAdjustmentAction(TextReplaceOptions.FontSizeAdjustment.ScaleToFill);
fragment.setText(text + " " + text);
document.save(outputFile.toString());
}
}
Replace text and shrink it to fit
Use this example when the replacement text must stay inside the original text rectangle.
- Open the source PDF and select the target fragment.
- Reuse the current fragment rectangle and enable
ShrinkToFit. - Replace the text and save the document.
public static void replaceTextAndFitTextIntoRectangle(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
TextFragmentAbsorber absorber = new TextFragmentAbsorber();
absorber.visit(document.getPages().get_Item(1));
TextFragment fragment = absorber.getTextFragments().get_Item(1);
String text = fragment.getText();
fragment.getReplaceOptions().setRectangle(fragment.getRectangle());
fragment.getReplaceOptions().setFontSizeAdjustmentAction(TextReplaceOptions.FontSizeAdjustment.ShrinkToFit);
fragment.getReplaceOptions().setReplaceAdjustmentAction(TextReplaceOptions.ReplaceAdjustment.AdjustSpaceWidth);
fragment.setText(text + " " + text);
document.save(outputFile.toString());
}
}
Replace text by regular expression
Use this example when matched text should be found by a regex pattern and restyled during replacement.
- Open the source PDF document.
- Search the page with a regex-enabled
TextFragmentAbsorber. - Replace each match, update its text style, and save the result.
public static void replaceTextBasedOnRegex(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
TextFragmentAbsorber absorber = new TextFragmentAbsorber(Pattern.compile("\\d{4}-\\d{4}"));
absorber.setTextSearchOptions(new TextSearchOptions(true));
document.getPages().get_Item(1).accept(absorber);
for (TextFragment fragment : absorber.getTextFragments()) {
fragment.setText("ABC1-2XZY");
fragment.getTextState().setFont(FontRepository.findFont("Verdana"));
fragment.getTextState().setFontSize(12);
fragment.getTextState().setForegroundColor(Color.getBlue());
fragment.getTextState().setBackgroundColor(Color.getLightGreen());
}
document.save(outputFile.toString());
}
}
Replace placeholder text and let the page rearrange
Use this example when a placeholder must be replaced by a longer real value while preserving page layout.
- Open the source PDF and search for the placeholder text.
- Assign the replacement text and update its font settings.
- Save the document so the layout is recalculated.
public static void automaticallyRearrangePageContents(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
TextFragmentAbsorber absorber = new TextFragmentAbsorber("[Long_placeholder_Long_placeholder]");
document.getPages().accept(absorber);
for (TextFragment textFragment : absorber.getTextFragments()) {
textFragment.setText("John Smith, South Development Studio");
textFragment.getTextState().setFont(FontRepository.findFont("Calibri"));
textFragment.getTextState().setFontSize(12);
textFragment.getTextState().setForegroundColor(Color.getNavy());
}
document.save(outputFile.toString());
}
}
Replace one font with another
Use this example when text using a specific embedded font should be switched to another font.
- Open the source PDF and collect all text fragments.
- Check the font name of each fragment and replace the target font.
- Save the updated PDF.
public static void replaceFonts(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
TextFragmentAbsorber absorber = new TextFragmentAbsorber();
document.getPages().accept(absorber);
for (TextFragment fragment : absorber.getTextFragments()) {
if ("Arial-BoldMT".equals(fragment.getTextState().getFont().getFontName())) {
fragment.getTextState().setFont(FontRepository.findFont("Verdana"));
}
}
document.save(outputFile.toString());
}
}
Replace fonts and remove unused font resources
Use this example when the document should be cleaned up after font replacement.
- Open the source PDF and configure
TextEditOptionsto remove unused fonts. - Absorb the text fragments and assign the replacement font.
- Save the optimized document.
public static void removeUnusedFonts(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
TextEditOptions options = new TextEditOptions(TextEditOptions.FontReplace.RemoveUnusedFonts);
TextFragmentAbsorber absorber = new TextFragmentAbsorber(options);
document.getPages().accept(absorber);
for (TextFragment textFragment : absorber.getTextFragments()) {
textFragment.getTextState().setFont(FontRepository.findFont("TimesNewRoman"));
}
document.save(outputFile.toString());
}
}
Remove all text from the document
Use this example when all text content must be deleted from every page.
- Open the source PDF document.
- Create a
TextFragmentAbsorberand callremoveAllText(document). - Save the cleaned PDF.
public static void removeAllTextUsingAbsorber1(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
TextFragmentAbsorber absorber = new TextFragmentAbsorber();
absorber.removeAllText(document);
document.save(outputFile.toString());
}
}
Remove all text from one page
Use this example when all text should be removed only from a specific page.
- Open the source PDF document.
- Create a
TextFragmentAbsorberand remove text from the target page. - Save the updated document.
public static void removeAllTextUsingAbsorber2(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
TextFragmentAbsorber absorber = new TextFragmentAbsorber();
absorber.removeAllText(document.getPages().get_Item(1));
document.save(outputFile.toString());
}
}
Remove text from a selected rectangle
Use this example when text should be deleted only inside a chosen page area.
- Open the source PDF document.
- Create a
TextFragmentAbsorberand define the rectangle to clean. - Remove the text from that region and save the document.
public static void removeAllTextUsingAbsorber3(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
TextFragmentAbsorber absorber = new TextFragmentAbsorber();
absorber.removeAllText(document.getPages().get_Item(1), new Rectangle(10, 200, 120, 600, true));
document.save(outputFile.toString());
}
}
Remove hidden text
Use this example when invisible text fragments should be stripped from the PDF.
- Open the source PDF and absorb all text fragments.
- Check each fragment for the invisible text state.
- Clear the hidden text and save the document.
public static void removeHiddenText(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
TextFragmentAbsorber textAbsorber = new TextFragmentAbsorber();
textAbsorber.setTextReplaceOptions(new TextReplaceOptions(TextReplaceOptions.ReplaceAdjustment.None));
document.getPages().accept(textAbsorber);
for (TextFragment fragment : textAbsorber.getTextFragments()) {
if (fragment.getTextState().isInvisible()) {
fragment.setText("");
}
}
document.save(outputFile.toString());
}
}