此事件未在第一个单元格中调用
public class pdfCellBorder : IPdfPCellEvent
{
public void CellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases)
{
PdfContentByte canvas = canvases[PdfPTable.LINECANVAS];
canvas.SetLineDash(0.5F, 2.2F, 0 );
canvas.Stroke();
}
}
注释中的代码:
PdfPTable table = new PdfPTable(1);
pdfCellBorder pdfcell = new pdfCellBorder();
table.DefaultCell.CellEvent = pdfcell;
table.DefaultCell.Border = PdfPCell.NO_BORDER;
PdfPCell cell = new PdfPCell(new Phrase("product"));
cell.Border = Rectangle.BOTTOM_BORDER;
cell.CellEvent = pdfcell;
table.AddCell(cell);
cell = new PdfPCell(new Phrase("product"));
// cell.BorderWidthBottom = 1f;
cell.Border = Rectangle.BOTTOM_BORDER;
cell.CellEvent = pdfcell;
table.AddCell(cell);
public class pdfCellBorder : IPdfPCellEvent {
public void CellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) {
PdfContentByte canvas = canvases[PdfPTable.LINECANVAS];
//canvas.SetLineWidth(0.5F);
canvas.SetLineDash(0.5F, 2.2F, 0);
canvas.Rectangle(position.Left, position.Bottom, position.Width, 0);
canvas.Stroke();
}
}
您可以通过两件事来解决此问题。首先,在您的事件中设置实际的Rectangle
:
public class pdfCellBorder : IPdfPCellEvent {
public void CellLayout(PdfPCell cell, iTextSharp.text.Rectangle position, PdfContentByte[] canvases) {
PdfContentByte canvas = canvases[PdfPTable.LINECANVAS];
canvas.SetLineDash(0.5F, 2.2F, 0);
//Set the rectangle to draw on
canvas.Rectangle(position.Left, position.Bottom, position.Width, position.Height);
canvas.Stroke();
}
}
第二,禁用默认单元格上的边框:
var t = new PdfPTable(2);
t.DefaultCell.CellEvent = new pdfCellBorder();
//Disable the border
t.DefaultCell.Border = PdfPCell.NO_BORDER;
t.AddCell("Hello");
t.AddCell("World");
doc.Add(t);
编辑
根据您的评论,您需要一条线,并且只需要在每个单元格的底部绘制一条线。您只想用Rectangle
和MoveTo
画一条线,而不是LineTo
:
public class pdfCellBorder : IPdfPCellEvent {
public void CellLayout(PdfPCell cell, iTextSharp.text.Rectangle position, PdfContentByte[] canvases) {
PdfContentByte canvas = canvases[PdfPTable.LINECANVAS];
canvas.SetLineDash(0.5F, 2.2F, 0);
//Move the "pen" to where we want to start drawing
canvas.MoveTo(position.Left, position.Bottom);
//Draw a straight line
canvas.LineTo(position.Right, position.Bottom);
canvas.Stroke();
}
}
但是,您仍然需要在所有单元格上禁用自动边框。如果在下面设置任何边框,则指示iTextSharp为您绘制边框。另外,由于您正在调用new PdfPCell()
,因此我们可以摆脱与DefaultCell
PdfPTable table = new PdfPTable(1);
pdfCellBorder pdfcell = new pdfCellBorder();
PdfPCell cell = new PdfPCell(new Phrase("product"));
cell.Border = PdfPCell.NO_BORDER;
cell.CellEvent = pdfcell;
table.AddCell(cell);
cell = new PdfPCell(new Phrase("product"));
cell.Border = PdfPCell.NO_BORDER;
cell.CellEvent = pdfcell;
table.AddCell(cell);
有人使用ironpython来实现PdfPCellEvent吗?当构造Rectangle类型的position时,IronPython需要一个非null参数,“ position = Rectangle()”语句是错误的。我没有办法,请帮忙。