答案 0 :(得分:2)
最简单的方法可能是使用带有通用标记的Chunk
和PdfPageEvent
。这样,当Chunk
位于页面上时,您将获得事件回调。回调将为您提供Chunk
的坐标(矩形),允许您在正确的位置绘制边框和阴影。
绘制黑色边框和灰色阴影的此类事件处理程序的示例:
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();
(请注意,text
方法的onGenericTag
参数将包含String
与Chunk
设置的setGenericTag
。这是{{在上面的示例中,它允许区分不同的标记。由于我们在这里只使用了1个标记,因此我没有使用"shadow"
参数。)
示例的结果如下所示: