Reputation: 4610
I have an HTML table in a view. I'm using ITextSharp 4 to convert the HTML to a PDF using the htmlParser. The table spans multiple pages. How do I get it to show the header on each page? Is there some setting I can turn on in HTML so that ITextSharp can recognise it?
Upvotes: 1
Views: 11441
Reputation: 763
Apply the "repeat-header" style, and set to "yes", like so:
<table style="repeat-header:yes;">
Upvotes: 2
Reputation: 2044
you should just be able to set: table.HeaderRows = 1;
this will repeat the header on each page.
Upvotes: 3
Reputation: 55417
I don't have access to iTextSharp 4.0 but since the HTML parser writes directly to the document I'm not sure if it would be possible without modify the original source. Is it an option to upgrade to 5.0 which completely replaced the HtmlParser
with a much more robust HTMLWorker
object?
To have a PdfPTable
's headers span multiple page you need to set its HeaderRows
property to the number of rows in your header. Unfortunately if you're using the HTMLParser
or the HTMLWorker
they do not currently treat THEAD
and TH
tags differently than TBODY
and TD
tags. The solution is to modify the PdfPTable
sometime after parsing but before being written to the document. I don't have 4.0 available here but in 5.1.1.0 using the HTMLWorker
you can easily do that and manually set the HeaderRows
property:
//Output file
string outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Table.pdf");
using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.Read))
{
using (Document doc = new Document(PageSize.LETTER))
{
using (PdfWriter w = PdfWriter.GetInstance(doc, fs))
{
doc.Open();
doc.NewPage();
//Create some long text to force a new page
string longText = String.Concat(Enumerable.Repeat("Lorem ipsum.", 40));
//Create our table using both THEAD and TH which iTextSharp currently ignores
string html = "<table>";
html += "<thead><tr><th>Header Row 1/Cell 1</th><th>Header Row 1/Cell 2</th></tr><tr><th>Header Row 2/Cell 1</th><th>Header Row 2/Cell 2</th></tr></thead>";
html += "<tbody>";
for (int i = 3; i < 20; i++)
{
html += "<tr>";
html += String.Format("<td>Data Row {0}</td>", i);
html += String.Format("<td>{0}</td>", longText);
html += "</tr>";
}
html += "</tbody>";
html += "</table>";
using (StringReader sr = new StringReader(html))
{
//Get our list of elements (only 1 in this case)
List<IElement> elements = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(sr, null);
foreach (IElement el in elements)
{
//If the element is a table manually set its header row count
if (el is PdfPTable)
{
((PdfPTable)el).HeaderRows = 2;
}
doc.Add(el);
}
}
doc.Close();
}
}
}
Upvotes: 4