我正在使用iTextSharp填写PDF模板.我使用的数据保存在数据库中,并且是HTML格式的.我的问题是,当我用这个文本加载AcroField时,我得到它来做换行符,但没有粗体也没有斜体.我已经尝试使用HtmlWorker,但是所有在线示例都显示它用于将HTML转换为PDF,但我试图在PDF模板中设置AcroField.任何帮助,将不胜感激.
解决方法
花了几天时间浏览论坛和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,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.Top);
- c1.Go();//very important!!!
- }
- catch (Exception ex)
- {
- throw;
- }
- }
我希望这能为将来节省一些时间和精力.