将PdfPCell添加到段落中
我正在尝试使用iTextSharp在段落句子的中间添加TextField(acrofield)。 一个例子是“生效日期是[月]的[日]日,[年]这将开始。”
我尝试过的事情:
Paragraph para1 = new Paragraph(); para1.Add(New Phrase("The Effective Date is",fontBold)); //The next line is where it breaks, "Insertion of illegal Element: 30" para1.Add(CreateTextField("Day",1,0)); //this function returns a PdfPCell.
PdfPCell tempCell = new PdfPCell(); tempCell.AddElement(new Phrase("The Effective Date is",fontBold)); //the next line breaks as well, "Element not allowed." tempCell.AddElement(CreateTextField("Day",1,0));
Paragraph para1 = new Paragraph(); para1.Add(New Phrase("The Effective Date is",fontBold)); para1.AddSpecial(CreateTextField("Day",1,0)); //This doesn't generate an error, but the TextField is not displayed on PDF
Paragraph para1 = new Paragraph(); PdfPTable tempTable = new PdfPTable(1); para1.Add(New Phrase("Hello",fontBold)); tempTable.AddCell(CreateTextField("Day",1,0)); para1.Add(tempTable); para1.Add(New Phrase("World",fontBold)); //This doesn't generate an error, but the TextField is not displayed on PDF
我知道CreateTextField(…)有效,因为我在页面上的其他几个地方使用它。
如何在不使用表格的情况下添加TextField与其他文本内联,并且繁琐地尝试操作单元格大小以适应我需要的内容?
谢谢您的帮助!
你的问题是错的。 您不希望将PdfPCell
添加到Paragraph
。 您想要创建内联表单字段。 这是一个完全不同的问题。
看一下GenericFields示例。 在这个例子中,我们创建你需要的Paragraph
,如下所示:
Paragraph p = new Paragraph(); p.add("The Effective Date is "); Chunk day = new Chunk(" "); day.setGenericTag("day"); p.add(day); p.add(" day of "); Chunk month = new Chunk(" "); month.setGenericTag("month"); p.add(month); p.add(", "); Chunk year = new Chunk(" "); year.setGenericTag("year"); p.add(year); p.add(" that this will begin.");
您是否看到我们如何添加空Chunk
以添加PdfPCell
? 我们在这些Chunk
对象上使用setGenericTag()
方法来添加一个表单字段,其中只有Chunk
被渲染。
为此,我们需要声明一个页面事件:
writer.setPageEvent(new FieldChunk());
FieldChunk
类如下所示:
public class FieldChunk extends PdfPageEventHelper { @Override public void onGenericTag(PdfWriter writer, Document document, Rectangle rect, String text) { TextField field = new TextField(writer, rect, text); try { writer.addAnnotation(field.getTextField()); } catch (IOException ex) { throw new ExceptionConverter(ex); } catch (DocumentException ex) { throw new ExceptionConverter(ex); } } }
每次渲染“通用块”时,都会调用onGenericTag()
方法,将setGenericTag()
方法中使用的参数作为text
参数传递。 我们使用writer
, rect
和text
参数来创建和添加TextField
。 结果如下:
如果要创建更大的文本字段,请随意调整rect
。
重要提示:我的示例是用Java编写的。 如果要将示例移植到C#,只需将每个方法的第一个字母更改为大写(例如,将add()
更改为Add()
)。 如果这不起作用,请尝试将参数设置为成员变量(例如,将writer.setPageEvent(event)
更改为writer.PageEvent = event
)。
更新:如果要使字段更大,则应创建一个新的Rectangle
。 例如:
Rectangle rect2 = new Rectangle(rect.Left, rect.Bottom - 5, rect.Right, rect.Top + 2); TextField field = new TextField(writer, rect2, text);