pdfstamper HTMLWorker itextSharp

回眸只為那壹抹淺笑 提交于 2019-12-25 04:19:43

问题


My application is MVC c#, I use itextSharp 5.3.4 to generate PDF using an existing template. I add text to the form fields (from sql database) using:

 pdfFormFields.SetField("Notes", cth.Notes.ToString());

The challenge I have is adding html contents, for example:

text text <img alt="" height="133" src="/Content/UserFiles/635380078478327671/Images/test.png" width="179" /> 

I used before HTMLWorker to generate paragraphs using:

public Paragraph CreateSimpleHtmlParagraph (String text)
    {

    string fontpath = System.Web.HttpContext.Current.Server.MapPath("~/Content/");
    BaseFont bf = BaseFont.CreateFont(fontpath + "ARIALUNI.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    var f = new Font(bf, 10, Font.NORMAL);
    var p = new Paragraph { Alignment = Element.ALIGN_LEFT, Font = f };
    var styles = new StyleSheet();
    styles.LoadTagStyle(HtmlTags.SPAN, HtmlTags.FONTSIZE, "10");
    styles.LoadTagStyle(HtmlTags.BODY, HtmlTags.ENCODING, BaseFont.IDENTITY_H);
    using (var sr = new StringReader(text))
        {
        var elements = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(sr, styles);
        foreach (var e in elements)
            {
            p.Add(e);
            }
        }
    return p;
    }

Can't figure out how can I add the paragraph to the form field, or even add a new page to the existing form or generating a new document and merging the form and the new document. Would appreciate your suggestions.


回答1:


Assuming that you want to flatten the form (I'll delete this answer if that's not your intention), I want to refer you to this example: MovieAds (see http://tinyurl.com/itextsharpIIA2C08 for the corresponding C# example).

You have a list of iText elements obtained from HTMLWorker. You are adding them to a Paragraph object. This is wrong. You should add them to a ColumnText object:

ColumnText ct = new ColumnText(canvas);
var elements = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(sr, styles);
foreach (var e in elements) {
    ct.AddElement(e);
}

Now you need the position of the field:

AcroFields.FieldPosition f = form.GetFieldPositions("Notes")[0];

You can now use this FieldPosition object to define the rectangle for the ColumnText object:

ct.SetSimpleColumn(
    f.position.Left, f.position.GetBottom(2),
    f.position.GetRight(2), f.position.Top
  );

To render the elements you've added to ct, just do:

ct.Go();

Note that elements that don't fit into the rectangle will be omitted. That's why the example I refer to returns a Boolean:

return ColumnText.HasMoreText(ct.Go(simulate));

If the HasMoreText() method returns true, I try adding the same elements anew, but using a smaller font.



来源:https://stackoverflow.com/questions/24155848/pdfstamper-htmlworker-itextsharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!