[英]Add PdfPCell to Paragraph
我正在嘗試使用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.");
你看到我們如何在你想要添加PdfPCell
的地方添加空Chunk
嗎? 我們在這些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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.