I've got a PdfPTable in which I am drawing simple text:
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
Font f2 = new Font(bf, 10.0f);
PdfPTable tab = new PdfPTable(2);
table.AddCell(new PdfPCell(new Phrase("Dude", f2)));
And that's all fine and dandy. But then in order to do some fancier stuff, I'm trying to get cell events to work:
Font f2 = new Font(bf, 10.0f); // Pretend this is a global
class CellEvent : IPdfPCellEvent
{
void IPdfPCellEvent.CellLayout(PdfPCell cell, Rectangle r, PdfContentByte[] canvases)
{
ColumnText ct = new ColumnText(canvases[0]);
ct.SetSimpleColumn(r);
ct.AddElement(new PdfPCell(new Phrase("Dude", f2)));
ct.Go();
}
}
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
PdfPTable tab = new PdfPTable(2);
PdfPCell ce = new PdfPCell();
ce.CellEvent = new CellEvent();
table.AddCell(ce);
When I do this though, the cell is drawn quite differently. My actual text is multiple lines long, and when drawn directly (adding the phrase directly to the cell) the text lines are quite close together vertically; when drawn via the cell event, there is a lot of space between the text lines and it doesn't fit in the box the PdfPTable provides for me.
Is there a different, more preferred method for drawing text inside IPdfPCellEvent.CellLayout()? Or are there just some formatting parameters I need to copy from PdfPCell into ColumnText?
There is something very wrong with this snippet:
ColumnText ct = new ColumnText(canvases[0]);
ct.SetSimpleColumn(r);
ct.AddElement(new PdfPCell(new Phrase("Dude", f2)));
ct.Go();
More specifically:
ct.AddElement(new PdfPCell(new Phrase("Dude", f2)));
You can not use the PdfPCell
object outside of the context of a PdfPTable
.
As for the differences between content in PdfPCell
and ColumnText
, you may want to read the answers to these questions:
The content of a PdfPCell
is actually stored in a ColumnText
object, but a PdfPCell
may have a padding.
There's also text mode versus composite mode. You are talking about the distance between two lines. In text mode, this distance is defined at the level of the PdfPCell
/ColumnText
using the setLeading()
method. In composite mode, this parameter is ignored. Instead, the leading of the elements added to the PdfPCell
/ColumnText
is used.
For instance: if p1
, p2
and p3
are three Paragraph
objects, each having a different leading, then ct
will have text with three different leadings if you do this:
ct.addElement(p1);
ct.addElement(p2);
ct.addElement(p3);
来源:https://stackoverflow.com/questions/32749219/itextsharp-text-is-different-when-drawn-with-cell-event-vs-directly