java - 在 iText 元素上添加阴影效果

标签 java itext cell shadow rectangles

我在 Java 中使用 iText 时遇到一些问题。我需要生成一个带阴影的单元格或矩形,就像本例中一样:

enter image description here

460 位于某种带有阴影的单元格或矩形中。我不知道该怎么做。有什么帮助吗?

最佳答案

最简单的方法可能是使用带有通用标记和 PdfPageEventChunk。这样,当 Chunk 位于页面上时,您将收到事件回调。回调将为您提供 block 的坐标(矩形),以便您在正确的位置绘制边框和阴影。

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

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();
    }
}

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

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();

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

示例的结果如下所示:

Border with shadow

关于java - 在 iText 元素上添加阴影效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33290487/

相关文章:

java - 无论如何要缩短 if else 语句而不是绕圈子

java - 双向链表逻辑

java - SWT RowLayout 从右到左?

java - Guice 和 Wicket : using SessionScoped injections

java - 如何检索 PdfStampAnnotation 旋转

Excel VBA 如何选择可变的单元格范围

java - 使用 Apache POI 和 itext 将 word(.docx) 转换为 pdf

c# - 使用一个签名签署 PDF,但具有多个签名外观

c - 如何测量 C 程序中每条指令的 CPU 周期

Swift 自动尺寸单元格高度不起作用