【发布时间】:2015-08-12 22:47:20
【问题描述】:
使用 iTextSharp,我生成了一个如下所示的 PDF 文件:
虽然它仍然需要一些美化,但它的表现相当不错,除了一件事:填充的文本框不可覆盖。您可以在它们上键入 ,是的,但如您所见,旧值仍保留在下方。在“必填日期”字段中,我在“2015 年 8 月 12 日”上输入了“9”,而 8 仍然显示出来。电子邮件框也是如此,我在我的电子邮件地址(等)上输入了“bla”
这需要工作的方式是在网页上输入的值以编程方式输入到适当的框中(例如这里的“Reuired Date”和“Email”的情况),但它们也应该是可删除的,而不是而不是与新文本共存。
这是我用来创建文本框的代码,以 Date 为例:
PdfPTable tblFirstRow = new PdfPTable(7);
tblFirstRow.WidthPercentage = 100;
tblFirstRow.SpacingBefore = 4f;
float[] FirstRowWidths = new float[] { 137f, 138f, 140f, 135f, 50f, 150f, 250f };
tblFirstRow.SetWidths(FirstRowWidths);
tblFirstRow.HorizontalAlignment = Element.ALIGN_LEFT;
Phrase phraseReqDate = new Phrase("Required Date: ", timesRoman9Font);
PdfPCell cellReqDate = GetCellForBorderlessTable(phraseReqDate, Element.ALIGN_LEFT);
tblFirstRow.AddCell(cellReqDate);
PdfPCell cellReqDateTextBox = new PdfPCell()
{
CellEvent = new DynamicTextbox("textBoxReqDate"),
Phrase = new Phrase(boxRequestDate.Text, timesRoman9Font)
};
tblFirstRow.AddCell(cellReqDateTextBox);
// For dynamically creating TextBoxes; from http://stackoverflow.com/questions/2675895/itextsharp-text-field-in-pdfpcell
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;
iTextSharp.text.pdf.TextField text = new iTextSharp.text.pdf.TextField(writer, rectangle, fieldname);
PdfFormField field = text.GetTextField();
writer.AddAnnotation(field);
}
}
我还希望当用户以同样的方式点击它们时,“提醒”文本(关于在哪里输入的内容)“消失”。
我做错了什么,或者我需要更改什么以使这些文本框能够正常运行?
【问题讨论】:
-
您的代码创建包含短语和单元格事件的单元格(用于生成表单字段)。这使得短语被绘制在常规页面内容中。当您开始在字段中输入时,常规页面内容不会消失。您可能希望使用该短语创建初始字段外观。
标签: c# pdf-generation itextsharp