如何创建使用iTextSharp添加到PDF文件的按钮?
问题描述:
我使用iTextSharp创建“标签”和文本框和复选框,但是我试图从该代码派生以创建按钮尚未成功。如何创建使用iTextSharp添加到PDF文件的按钮?
这里是我是如何创建文本框:
PdfPCell cellRequesterNameTextBox = new PdfPCell()
{
CellEvent = new DynamicTextbox("textBoxRequesterName")
};
tblFirstRow.AddCell(cellRequesterNameTextBox);
. . .
public class DynamicTextbox : IPdfPCellEvent
{
private string fieldname;
public DynamicTextbox(string name)
{
fieldname = name;
}
public void CellLayout(PdfPCell cell, Rectangle rectangle, PdfContentByte[] canvases)
{
PdfWriter writer = canvases[0].PdfWriter;
float textboxheight = 11f;
Rectangle rect = rectangle;
rect.Bottom = rect.Top - textboxheight;
TextField text = new TextField(writer, rect, fieldname);
PdfFormField field = text.GetTextField();
writer.AddAnnotation(field);
}
}
,这里是我是如何创建复选框:
PdfPCell cell204Submitted = new PdfPCell()
{
CellEvent = new DynamicCheckbox("checkbox204Submitted")
};
tblLastRow.AddCell(cell204Submitted);
. . .
public class DynamicCheckbox : IPdfPCellEvent
{
private string fieldname;
public DynamicCheckbox(string name)
{
fieldname = name;
}
public void CellLayout(PdfPCell cell, Rectangle rectangle, PdfContentByte[] canvases)
{
PdfWriter writer = canvases[0].PdfWriter;
RadioCheckField ckbx = new RadioCheckField(writer, rectangle, fieldname, "Yes");
ckbx.CheckType = RadioCheckField.TYPE_CHECK;
ckbx.BackgroundColor = new BaseColor(255, 197, 0);
ckbx.FontSize = 6;
ckbx.TextColor = BaseColor.WHITE;
PdfFormField field = ckbx.CheckField;
writer.AddAnnotation(field);
}
}
,这里是我是如何试图创建按钮:
PdfPCell cellButton1 = new PdfPCell()
{
CellEvent = new DynamicButton("button1")
};
tblButtonRow.AddCell(cellButton1);
. . .
public class DynamicButton : IPdfPCellEvent
{
private string fieldname;
public DynamicButton(string name)
{
fieldname = name;
}
public void CellLayout(PdfPCell cell, Rectangle rectangle, PdfContentByte[] canvases)
{
PdfWriter writer = canvases[0].PdfWriter;
float buttonheight = 24f;
Rectangle rect = rectangle;
PushbuttonField btn = new PushbuttonField(writer, rect, fieldname);
PdfFormField field = btn.Field; // <= what should this be?
writer.AddAnnotation(field);
}
}
上次(按钮)代码中有什么缺失或错误?我认为我在DynamicButton.CellLayout()中的“field”赋值必须是错误的,但它应该是什么?
这里是如何的“按钮”的外观(长瘦的线在底部,复选框之下,与其相关的文本/标签):
我怎么能胖起来/滋润那些twiggified “纽扣”?
答
您没有显示代码中最重要的部分:您没有展示如何创建为其定义按钮的单元格。如果您要检查rect
(更具体地说它的高度)的值,您会发现您可能正在创建高度为0
的单元格。为什么高度为零?因为他们可能不包含任何东西。
单元格是否需要包含任何东西?当然不是,但如果你想避免零高度的行,你必须定义一个高度。这在我的书的Chapter 4中有解释,例如在CellHeights的例子中。我为这个相当神秘的名字道歉,但这个例子是关于细胞的高度。
您可以定义一个固定的高度:
cell.FixedHeight = 72f;
这是一个危险的特性:如果添加了不适合的固定高度(例如72个用户单位)里面的内容,这些内容都将丢失。
您还可以定义一个最小高度:
cell.MinimumHeight = 36f;
在这种情况下,高度肯定会有36个用户单位(在这种情况下),但它可能是更多,如果有比配合更多的内容最小高度。