How to add a string in pdf format, like the <hr / "> tag in html
3 answers
I found this online, not tested, but later if it does not work for you.
PdfWriter writer = PdfWriter.getInstance(document, out); PdfContentByte cb = writer.getDirectContent(); cb.setLineWidth(2.0f); // Make a bit thicker than 1.0 default cb.setGrayStroke(0.95f); // 1 = black, 0 = white float x = 72f; float 7 = 72f; cb.moveTo(x, y); cb.lineTo(x + 72f*6, y); cb.stroke(); +1
Since iTextSharp have limitations in understanding several HTML styles / tags and give errors when including the <hr /> in html during parsing.
Solving this problem is a small workaround and uses graphics:
You need to create a new class that extends the
HTMLWorkerclass and overrides theStartElementmethod, which gives us an event when each html element starts.public class HTMLWorkerExtended : HTMLWorker { LineSeparator line = new LineSeparator(4f, 100f, BaseColor.BLACK, Element.ALIGN_CENTER, -1); public HTMLWorkerExtended(IDocListener document): base(document) { } public override void StartElement(string tag, IDictionary<string, string> str) { if (tag.Equals("hrline")) document.Add(new Chunk(line)); else base.StartElement(tag, str); }}
In your html, add the
<hrline />tag wherever you are.Now use the
HTMLWorkerExtendedclass' object to parse the html.using (TextReader htmlViewReader = new StringReader(htmlText)) { using (var htmlWorker = new HTMLWorkerExtended(pdfDocument)) { htmlWorker.Open(); htmlWorker.Parse(htmlViewReader); } }
+1