问题
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