花了几天时间浏览论坛和 iTextsharp 源代码后,我找到了解决方案。我没有使用 HTML 格式的文本填充 Acrofield,而是使用了 ColumnText。我解析 html 文本并将 IElements 加载到段落中。然后将段落添加到 ColumnText。然后我使用字段的坐标将 ColumnText 覆盖在 Acrofield 应该在的位置上。
public void AddHTMLToContent(String htmlText,PdfContentByte contentBtye,IList<AcroFields.FieldPosition> pos)
{
Paragraph par = new Paragraph();
ColumnText c1 = new ColumnText(contentBtye);
try
{
List<IElement> elements = HTMLWorker.ParseToList(new StringReader(htmlText),null);
foreach (IElement element in elements)
{
par.Add(element);
}
c1.AddElement(par);
c1.SetSimpleColumn(pos[0].position.Left, pos[0].position.Bottom, pos[0].position.Right, pos[0].position.Top);
c1.Go(); //very important!!!
}
catch (Exception ex)
{
throw;
}
}
这里是一个调用这个函数的例子。
string htmlText ="<b>Hello</b><br /><i>World</i>";
IList<AcroFields.FieldPosition> pos = form.GetFieldPositions("Field1");
//Field1 is the name of the field in the PDF Template you are trying to fill/overlay
AddHTMLToContent(htmlText, stamp.GetOverContent(pos[0].page), pos);
//stamp is the PdfStamper in this example
我在执行此操作时遇到的一件事是我的 Acrofield 确实具有预定义的字体大小。由于此函数将 ColumnText 设置在字段的顶部,因此必须在函数中完成任何字体更改。下面是一个改变字体大小的例子:
public void AddHTMLToContent(String htmlText,PdfContentByte contentBtye,IList<AcroFields.FieldPosition> pos)
{
Paragraph par = new Paragraph();
ColumnText c1 = new ColumnText(contentBtye);
try
{
List<IElement> elements = HTMLWorker.ParseToList(new StringReader(htmlText),null);
foreach (IElement element in elements)
{
foreach (Chunk chunk in element.Chunks)
{
chunk.Font.Size = 14;
}
}
par.Add(elements[0]);
c1.AddElement(par);
c1.SetSimpleColumn(pos[0].position.Left, pos[0].position.Bottom, pos[0].position.Right, pos[0].position.Top);
c1.Go();//very important!!!
}
catch (Exception ex)
{
throw;
}
}