【问题标题】:How can I populate Textboxes on a PDF with text that will disappear/be replaceable when the user places the cursor in them?如何在 PDF 上的文本框中填充当用户将光标放在其中时将消失/可替换的文本?
【发布时间】: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


【解决方案1】:

你应该删除这一行:

Phrase = new Phrase(boxRequestDate.Text, timesRoman9Font)

正如 mkl 在他的评论中解释的那样,这一行会将文本 boxRequestDate 添加到页面中。该内容不是交互式的。它是页面内容流的一部分,而不是显示字段值的小部件注释。

相反,您需要调整您的 DynamicTextbox 事件。您已经有一个名为fieldname 的成员变量。现在你应该添加一个额外的变量:

private string fieldname;
private string fieldvalue;

public DynamicTextbox(string name, string value)
{
    fieldname = name;
    fieldvalue = value;
}

你应该像这样使用这个值:

iTextSharp.text.pdf.TextField text = new iTextSharp.text.pdf.TextField(writer, rectangle, fieldname);
text.Text = fieldvalue;

现在文本不会添加到页面中,但会存储在字段字典的/V(值)键中,并将用于为小部件创建/AP(外观)注解。当您选择该小部件注释时,您可以更改该字段的值并进行更改。外观会相应改变。

【讨论】:

  • 谢谢,布鲁诺——完美!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多