iText 5:创建包含2个背景颜色且文本重叠的PdfPcell
问题描述:
在java中使用iText5并且想要对PdfPcell的结果进行颜色编码,如下所示。例如,该表格包括2列和3行。iText 5:创建包含2个背景颜色且文本重叠的PdfPcell
人有一个想法如何做到这一点?
我能简单地设置使用
PdfPCell cell = new PdfPCell(new Phrase("60 Pass, 40 Fail", myStyle));
cell.setBackgroundColor(new BaseColor(0xff,0x0,0x0)); // red background
那么,做什么,一个绿色矩形添加到单元格的背景颜色?使用模板?不确定。
答
您可以通过单元事件侦听器完成这种“有趣”的单元特性。
E.g.为你的任务,你可以实现一个PdfPCellEvent
这样的:
public class PercentileCellBackground implements PdfPCellEvent {
public PercentileCellBackground(float percent, BaseColor leftColor, BaseColor rightColor) {
this.percent = percent;
this.leftColor = leftColor;
this.rightColor = rightColor;
}
@Override
public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) {
PdfContentByte canvas = canvases[PdfPTable.BACKGROUNDCANVAS];
float xTransition = position.getLeft() + (position.getRight() - position.getLeft()) * (percent/100.0f);
float yTransition = (position.getTop() + position.getBottom())/2f;
float radius = (position.getRight() - position.getLeft()) * 0.025f;
PdfShading axial = PdfShading.simpleAxial(canvas.getPdfWriter(),
xTransition - radius, yTransition, xTransition + radius, yTransition, leftColor, rightColor);
PdfShadingPattern shading = new PdfShadingPattern(axial);
canvas.saveState();
canvas.setShadingFill(shading);
canvas.rectangle(position.getLeft(), position.getBottom(), position.getWidth(), position.getHeight());
canvas.fill();
canvas.restoreState();
}
final float percent;
final BaseColor leftColor;
final BaseColor rightColor;
}
然后,您可以使用此事件侦听器类是这样的:
Document document = new Document();
try (OutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "TableWithCellsWithPercentileBackground.pdf"))) {
PdfWriter.getInstance(document, os);
document.open();
Font font = new Font(FontFamily.UNDEFINED, Font.UNDEFINED, Font.UNDEFINED, BaseColor.WHITE);
PdfPTable table = new PdfPTable(2);
table.setWidthPercentage(40);
PdfPCell cell = new PdfPCell(new Phrase("Group A"));
table.addCell(cell);
cell = new PdfPCell(new Phrase(new Chunk("60 Pass, 40 Fail", font)));
cell.setCellEvent(new PercentileCellBackground(60, BaseColor.GREEN, BaseColor.RED));
table.addCell(cell);
cell = new PdfPCell(new Phrase("Group B"));
table.addCell(cell);
cell = new PdfPCell(new Phrase(new Chunk("70 Pass, 30 Fail", font)));
cell.setCellEvent(new PercentileCellBackground(70, BaseColor.GREEN, BaseColor.RED));
table.addCell(cell);
cell = new PdfPCell(new Phrase("Group C"));
table.addCell(cell);
cell = new PdfPCell(new Phrase(new Chunk("50 Pass, 50 Fail", font)));
cell.setCellEvent(new PercentileCellBackground(50, BaseColor.GREEN, BaseColor.RED));
table.addCell(cell);
document.add(table);
document.close();
}
(CellsWithPercentileBackground测试testCreateTableWithCellsWithPercentileBackground
)
结果看起来是这样的:
正如你所看到的,我用了一个阴影,使绿/红过渡不太苛刻。如果您想要更加苛刻,请在事件cellLayout
方法中减小径向系数0.025f
,或改为使用矩形绘图指令。