生成下划线 Waves itext7

Generate underline Waves itext7

如何在 :

之间绘制特定的下划线
String s = "This text is underlined with a dashed line";
Paragraph paragraph = new Paragraph();
Text text;
for (int i = 0; i <s.length() ; i++) {
    text = new Text(String.valueOf(s.charAt(i)));
    paragraph.add(text);
    text.setNextRenderer(new DashedLineTextRenderer(text));
}

doc.add(paragraph);
doc.close();

private static class DashedLineTextRenderer extends TextRenderer {

    public DashedLineTextRenderer(Text textElement) {
        super(textElement);
    }

    // If renderer overflows on the next area, iText uses getNextRender() method to create a renderer for the overflow part.
    // If getNextRenderer isn't overriden, the default method will be used and thus a default rather than custom
    // renderer will be created
    @Override
    public IRenderer getNextRenderer() {

        return new DashedLineTextRenderer((Text) modelElement);
    }

    @Override
    public void draw(DrawContext drawContext) {
        super.draw(drawContext);
        Rectangle rect = this.getOccupiedAreaBBox();
        PdfCanvas canvas = drawContext.getCanvas();
        canvas.moveTo(rect.getLeft(), rect.getBottom());

        canvas.curveTo(rect.getLeft()+100,rect.getBottom()+5,
        rect.getLeft()+150,rect.getBottom()-2,rect.getLeft()+200,rect.getBottom()-5);
        canvas.stroke();
    }
}

如果我使用单个元素文本,它会起作用: enter image description here

如果有多个文本元素,我如何定义绘制位置canvas

问题未明确说明(请参阅澄清评论)。基本上是为了避免屏幕截图上的重叠:

您可以为 Paragraph 自定义渲染器,不能为 Text 自定义渲染器:

private static class WaveUnderlinedParagraphRenderer extends ParagraphRenderer {
    public WaveUnderlinedParagraphRenderer(Paragraph paragraph) {
        super(paragraph);
    }

    @Override
    public void draw(DrawContext drawContext) {
        super.draw(drawContext);
        Rectangle rect = this.getOccupiedAreaBBox();
        PdfCanvas canvas = drawContext.getCanvas();
        canvas.moveTo(rect.getLeft(), rect.getBottom());

        canvas.curveTo(rect.getLeft() + 100, rect.getBottom() + 5,
                rect.getLeft() + 150, rect.getBottom() - 2, rect.getLeft() + 200, rect.getBottom() - 5);
        canvas.stroke();
    }

    @Override
    public IRenderer getNextRenderer() {
        return new WaveUnderlinedParagraphRenderer((Paragraph) modelElement);
    }
}
Document doc = new Document(pdfDocument);
String s = "This text is underlined with a dashed line";
Paragraph paragraph = new Paragraph();
Text text;
for (int i = 0; i <s.length() ; i++) {
    text = new Text(String.valueOf(s.charAt(i)));
    paragraph.add(text);
}

paragraph.setNextRenderer(new WaveUnderlinedParagraphRenderer(paragraph));
doc.add(paragraph);
doc.close();

并得到如下结果: