在iText元素上添加阴影效果 [英] Adding shadow effect on iText elements

查看:155
本文介绍了在iText元素上添加阴影效果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中遇到iText的问题。我需要生成一个带阴影的单元格或矩形,如下例所示:

I have some problem with iText in Java. I need to produce a cell or rectangle with shadow just like in this example:

4 60 是某种带阴影的单元格或矩形。我不知道怎么做。任何帮助?

4 and 60 are in some kind of cell or rectangle with shadow. I don't know how to do it. Any help ?

推荐答案

最简单的方法可能是使用使用通用标记和 PdfPageEvent 。这样,当 Chunk 位于页面上时,您将获得事件回调。回调将为您提供的坐标(矩形),允许您在正确的位置绘制边框和阴影。

The easiest way probably is to use a Chunk with a generic tag and a PdfPageEvent. This way you'll get an event callback when the Chunk is positioned on the page. The callback will give you the coordinates (rectangle) of the Chunk, allowing you to paint a border and a shadow at the correct location.

绘制黑色边框和灰色阴影的此类事件处理程序示例:

An example of such an event handler to paint a black border and a gray shadow:

class ShadowEvent extends PdfPageEventHelper {
    @Override
    public void onGenericTag(PdfWriter writer, Document document,
      Rectangle rect, String text) {
        PdfContentByte canvas = writer.getDirectContent();
        // Paddings for the border
        int paddingHorizontal = 20;
        int paddingVertical = 5;
        // Width of the shadow
        int shadowwidth = 5;
        // Calculate border location and size
        float left = rect.getLeft() - paddingHorizontal;
        float bottom = rect.getBottom() - paddingVertical;
        float width = rect.getWidth() + 2*paddingHorizontal;
        float height = rect.getHeight() + 2*paddingVertical;
        canvas.saveState();
        canvas.setColorFill(BaseColor.GRAY);
        // Draw the shadow at the bottom
        canvas.rectangle(left + shadowwidth, bottom - shadowwidth, width, shadowwidth);
        canvas.fill();
        // Draw the shadow at the right
        canvas.rectangle(left + width, bottom - shadowwidth, shadowwidth, height);
        canvas.fill();
        canvas.setColorStroke(BaseColor.BLACK);
        // Draw the border
        canvas.rectangle(left, bottom, width, height);
        canvas.stroke();
        canvas.restoreState();
    }
}

这显示了如何使用通用标签:

This shows how to use the generic tag:

Document doc = new Document();
PdfWriter pdfWriter = PdfWriter.getInstance(doc, outfile);
pdfWriter.setPageEvent(new ShadowEvent());
doc.open();
Chunk c = new Chunk("60");
c.setGenericTag("shadow");
doc.add(c);
doc.close();

(请注意 text 参数 onGenericTag 方法将包含设置为块 String >使用 setGenericTag 。这是上面示例中的shadow。它允许区分不同的标签。由于我们我只是在这里使用1个标签,我没有使用 text 参数。)

(Note that the text parameter of the onGenericTag method will contain the String that was set to the Chunk with setGenericTag. This is "shadow" in the example above. It allows to differentiate between different tags. Since we're just using 1 tag here, I'm not using the text parameter.)

结果示例如下所示:

这篇关于在iText元素上添加阴影效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆