要解决此问题,可以使用自定义渲染器。如果你看看
BlockRenderer#drawBackground
如果将透明背景设置为段落,则调用此函数,您可以在其中看到以下行:
TransparentColor backgroundColor = new TransparentColor(background.getColor(), background.getOpacity());
drawContext.getCanvas().saveState().setFillColor(backgroundColor.getColor());
backgroundColor.applyFillTransparency(drawContext.getCanvas());
TextRenderer
但是,它有自己的实现,不尊重透明的背景。但是我们可以定制渲染器实现。我们需要从当前
文本呈现程序
实现,但好消息是我们不需要更改很多代码。只需在正确的位置插入两行:
TransparentColor backgroundColor = new TransparentColor(background.getColor(), background.getOpacity());
backgroundColor.applyFillTransparency(drawContext.getCanvas());
总的来说,我们得到了以下实现:
private static class TextRendererWithBackgroundOpacity extends TextRenderer {
public TextRendererWithBackgroundOpacity(Text textElement) {
super(textElement);
}
@Override
public void drawBackground(DrawContext drawContext) {
Background background = this.<Background>getProperty(Property.BACKGROUND);
Float textRise = this.getPropertyAsFloat(Property.TEXT_RISE);
Rectangle bBox = getOccupiedAreaBBox();
Rectangle backgroundArea = applyMargins(bBox, false);
float bottomBBoxY = backgroundArea.getY();
float leftBBoxX = backgroundArea.getX();
if (background != null) {
boolean isTagged = drawContext.isTaggingEnabled();
PdfCanvas canvas = drawContext.getCanvas();
if (isTagged) {
canvas.openTag(new CanvasArtifact());
}
boolean backgroundAreaIsClipped = clipBackgroundArea(drawContext, backgroundArea);
canvas.saveState().setFillColor(background.getColor());
TransparentColor backgroundColor = new TransparentColor(background.getColor(), background.getOpacity());
backgroundColor.applyFillTransparency(drawContext.getCanvas());
canvas.rectangle(leftBBoxX - background.getExtraLeft(), bottomBBoxY + (float) textRise - background.getExtraBottom(),
backgroundArea.getWidth() + background.getExtraLeft() + background.getExtraRight(),
backgroundArea.getHeight() - (float) textRise + background.getExtraTop() + background.getExtraBottom());
canvas.fill().restoreState();
if (backgroundAreaIsClipped) {
drawContext.getCanvas().restoreState();
}
if (isTagged) {
canvas.closeTag();
}
}
}
@Override
public IRenderer getNextRenderer() {
return new TextRendererWithBackgroundOpacity((Text)modelElement);
}
}
使
Text
元素使用自定义呈现器实现只需调用
setNextRenderer
方法:
Text customTextElement = new Text("missing background transparency");
customTextElement.setNextRenderer(new TextRendererWithBackgroundOpacity(customTextElement));
顺便说一下,我们非常欢迎您将修复作为请求提交到iText(请按照
contribution guidelines
但是)。存储库位于
https://github.com/itext/itext7