加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 资源网站 > 资源 > 正文

表单 – 使用iTextSharp使用HTML格式的文本填充PDF模板acrofield

发布时间:2020-12-14 21:15:47 所属栏目:资源 来源:网络整理
导读:我正在使用iTextSharp填写PDF模板.我使用的数据保存在数据库中,并且是HTML格式的.我的问题是,当我用这个文本加载AcroField时,我得到它来做换行符,但没有粗体也没有斜体.我已经尝试使用HtmlWorker,但是所有在线示例都显示它用于将HTML转换为PDF,但我试图在PDF
我正在使用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;
        }
    }

我希望这能为将来节省一些时间和精力.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读