在 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
然后,做什么,向单元格添加一个绿色矩形?使用模板?不确定。
最佳答案
您可以通过单元格事件监听器来完成此类“有趣”的单元格功能。
例如对于您的任务,您可以像这样实现 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
或使用其中的矩形绘制指令。
关于java - iText 5 : create PdfPcell containing 2 background colors with text overlap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46869670/