Reputation: 1860
I wanted to render a HTML string in a page with header and footer. I tried by PdfPageEventHelper to add header/footer and then load the HTML. It does work. However the HTML loads in the page without margins. I tried adding margin to body element in HTML, which didn't work. Then I tried to add a table to body and then load the HTML inside the Table using HTMLWorker.ParseToList
and cell.AddElement
. It resulted in an empty table without the HTML elements.
pdfDoc.Open();
iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(pdfDoc);
StyleSheet styles = new StyleSheet();
// hw.Parse(new StringReader(invoiceHTML));
PdfPTable bodyTable = new PdfPTable(1);
PdfPCell bodyCell = new PdfPCell();
bodyTable.AddCell(bodyCell);
pdfDoc.Add(bodyTable);
var htmlarraylist = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(new StringReader(invoiceHTML), styles);
for (int k = 0; k < htmlarraylist.Count; k++)
{
var ele = (IElement)htmlarraylist[k];
bodyCell.AddElement(ele);
}
pdfDoc.Close();
Upvotes: 1
Views: 4272
Reputation: 55457
You are creating a table, creating a cell, adding the cell to the table and then adding that table to the document. At this point these objects are done and you should treat them as read-only variables (at best). However, after those steps is when you start adding actual content to the cell and that's why you aren't seeing anything. You need to move your adding the cell to the table and your table to the document after the loop:
var bodyTable = new PdfPTable(1);
var bodyCell = new PdfPCell();
var htmlarraylist = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(new StringReader(invoiceHTML), styles);
for (int k = 0; k < htmlarraylist.Count; k++) {
var ele = (IElement)htmlarraylist[k];
bodyCell.AddElement(ele);
}
bodyTable.AddCell(bodyCell);
pdfDoc.Add(bodyTable);
Upvotes: 2