简体   繁体   中英

ITextSharp repeat HTML table header in PDF with using external css file

I have an HTML table in a view. I'm using ITextSharp to convert the HTML to a PDF. I want to use external CSS and repeat table header for each page. How do I get it to show the header on each page using CSS and page header?

This is to show my page header

str.Append("<table class='text-center'>");
                    str.Append("<tr class='h4'><td> " + companyName + " </ td ></ tr >");
                    str.Append("</table>");

And this to show my HTML

TextReader xmlString = new StringReader(str.Append(html).ToString());

And this to append my CSS

ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
cssResolver.AddCssFile(HttpContext.Current.Server.MapPath(@"~/Content/Print.css"), true);
IPipeline pipeline = new CssResolverPipeline(cssResolver,
    new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer)));

var worker = new XMLWorker(pipeline, true);
var xmlParse = new XMLParser(true, worker);
xmlParse.Parse(xmlString);
xmlParse.Flush();

This code work fine but I am using 1 table for showing data and the table header does not repeat for each page. If i am using this code to repeat headers for table, the CSS does not work. How can i resolve this issue, using both CSS and repeating header.

using (TextReader sr = new StringReader(html))
{
    List<IElement> elements =
      iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(sr, null);
    foreach (IElement el in elements)
    {
        if (el is PdfPTable)
        {
            ((PdfPTable)el).HeaderRows = 2;
        }
        document.Add(el);
        xmlParse.Parse(sr);
    }
}

XML Worker allows you to configure repeating table headers and footers through proprietary CSS properties: repeat-header and repeat-footer . These are not part of the CSS specification. They are only used by XML Worker for this specific purpose.

You can specify your header and footer rows using <thead> and <tfoot> .

<table style="repeat-header: yes; repeat-footer: yes;">
  <tfoot>
    <tr>
      <td>Footer 1</td>
    </tr>
  </tfoot>
  <thead>
    <tr>
      <td>Header 1</td>
    </tr>
    <tr>
      <td>Header 2</td>
    </tr>
  </thead>
  <tbody>
    <!-- ... -->
  </tbody>
</table>

In your last code sample, you use HTMLWorker . You shouldn't. It's deprecated in favor of XMLWorker .

So just use your code based on XMLWorker and XMLParser , with the CSS property repeat-header as illustrated in the HTML sample above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM