We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Redact text in PDF using Java - Misplaced overlay text on RedactionAnnotation

Overlay text on RedactionAnnotation overlap paragraph text instead of placed over annotation. Example: image.png (44.4 KB)

Java version: 11
Aspose PDF version: 21.10

Code snippet

  @Test
    void testReduction() {
        var document = new Document("testFile.pdf");
        var page = document.getPages().get_Item(3);
        var textFragment = findTextFragment(page, "release process");

        var annotation = new RedactionAnnotation(page, textFragment.getRectangle());
        annotation.setFillColor(Color.getBlueViolet());
        annotation.setColor(Color.getBlack());
        annotation.setOverlayText("OverlayText");
        annotation.setTextAlignment(HorizontalAlignment.Left);

        var textFragmentQuadPoints = getTextFragmentQuadPoints(textFragment);
        annotation.setQuadPoints(textFragmentQuadPoints);

        annotation.redact();
        page.getAnnotations().add(annotation);

        document.save("result.pdf");
    }

    private TextFragment findTextFragment(Page page, String searchValue) {
        var regexp = createRegexp(searchValue);
        var absorber = new TextFragmentAbsorber(regexp, new TextSearchOptions(true));

        page.accept(absorber);

        return absorber.getTextFragments().get_Item(1);
    }

    private String createRegexp(String searchValue){
        var tokens = searchValue.split(" ");
        var regexp = Arrays.stream(tokens)
                .map(Pattern::quote)
                .collect(Collectors.joining("\\s*"));

        return regexp;
    }

    private Point[] getTextFragmentQuadPoints(TextFragment textFragment) {
        int offset = 0;
        var quadPoints = new Point[textFragment.getSegments().size() * 4];
        for (TextSegment segment : textFragment.getSegments()) {
            var rectangle = segment.getRectangle();
            quadPoints[offset] = new Point(rectangle.getLLX(), rectangle.getURY());
            quadPoints[offset + 1] = new Point(rectangle.getURX(), rectangle.getURY());
            quadPoints[offset + 2] = new Point(rectangle.getLLX(), rectangle.getLLY());
            quadPoints[offset + 3] = new Point(rectangle.getURX(), rectangle.getLLY());
            offset += 4;
        }

        return quadPoints;
    }

Original file: testFile.pdf (402.5 KB)

@dkuksa

We have also noticed the similar issue in our environment while testing the scenario. Therefore, an issue as PDFJAVA-41046 has been logged in our issue tracking system for the sake of correction. We will look into its details and keep you posted with the status of its correction. Please be patient and spare us some time.

We are sorry for the inconvenience.