我正在使用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; } }
我希望这能为将来节省一些时间和精力.
原文地址:https://www.jb51.cc/html/232273.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。