HTML to PDF manage Header and move section to new page if content exceeds

Hi Team,
I have requirement in which I want the following while generating a PDF via HTML

  1. The first page should have header
    2 . Rest pages should have the same header but few fields should be hidden from that header content
  2. If the First page last section goes long which contains text that can be small or long, then move the whole section to the next page with the header in which few fields are hidden as its a new page

I am implementing this in MVC with layout.cshtml and partial views defined with in RenderBody()

So how can I achieve this using change in HTML and css only

Hi Ronny,

1 - Currently only default headers and footers can be read from the input HTML file, see the " Convert HTML to PDF with headers and footers" section:

So what you’ll need to do is add that content afterward, for example:

string htmlBody = "...";
string htmlFirstHeader = "...";
string htmlHeader = "...";

var htmlOptions = LoadOptions.HtmlDefault;

var document = new DocumentModel();
document.Content.LoadText(htmlBody, htmlOptions);

var section = document.Sections[0];

var firstHeader = new HeaderFooter(document, HeaderFooterType.HeaderFirst);
firstHeader.Content.LoadText(htmlFirstHeader, htmlOptions);
section.HeadersFooters.Add(firstHeader);

var header = new HeaderFooter(document, HeaderFooterType.HeaderDefault);
header.Content.LoadText(htmlHeader, htmlOptions);
section.HeadersFooters.Add(header);

document.Save("output.pdf");

2 - I’m not exactly sure what you’re referring to with “section”, nevertheless, try adding the page-break-after:avoid;page-break-inside:avoid; CSS to paragraphs that you want to keep together.

For example, try this:

<div>
    <h1 style="page-break-after:avoid;page-break-inside:avoid;">Title</h1>
    <p style="page-break-after:avoid;page-break-inside:avoid;">First paragraph.</p>
    <p style="page-break-after:avoid;page-break-inside:avoid;">Second paragraph.</p>
    <p style="page-break-after:avoid;page-break-inside:avoid;">Third paragraph.</p>
</div>
<p>&nbsp;</p>
<div>
    <h1 style="page-break-after:avoid;page-break-inside:avoid;">Title</h1>
    <p style="page-break-after:avoid;page-break-inside:avoid;">First paragraph.</p>
    <p style="page-break-after:avoid;page-break-inside:avoid;">Second paragraph.</p>
    <p style="page-break-after:avoid;page-break-inside:avoid;">Third paragraph.</p>
</div>
<p>&nbsp;</p>
...

Notice that I’m using <p>&nbsp;</p> paragraphs between <div>, they are used in order to separate those sections.

Without them, you would just end up with all the paragraphs having “Keep with next” and “Keep lines together” options; which is basically the same as if none of them had those options.

Regards,
Mario