iText 5:创建包含2种背景颜色且文本重叠的PdfPcell

在java中使用iText5并想要对PdfPcell的结果进行颜色编码,如下所示。 例如,该表包括2列和3行。

在此处输入图像描述

任何人都知道如何实现这一目标?

我可以简单地使用设置背景颜色

PdfPCell cell = new PdfPCell(new Phrase("60 Pass, 40 Fail", myStyle)); cell.setBackgroundColor(new BaseColor(0xff,0x0,0x0)); // red background 

然后,做什么,在单元格中添加绿色矩形? 使用模板? 不确定。

您可以通过单元格事件侦听器完成此类“有趣”的单元格function。

例如,对于您的任务,您可以实现这样的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; } 

( PercentileCellBackground )

然后,您可以像这样使用此事件侦听器类:

 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 test testCreateTableWithCellsWithPercentileBackground

结果如下:

截图

正如您所看到的,我使用阴影来使绿色/红色过渡不那么刺耳。 如果你想要它更苛刻, 0.025f在事件cellLayout方法中减小半径系数0.025f ,或者在其中使用矩形绘图指令。