Click or drag to resize
Pdf Library for .NET

Headers and Footers with SelectPdf HtmlToPdf Converter

The Headers And Footers page describes how to add headers and footers to a PdfDocument using Pdf Templates. That is the approach to be used if the html to pdf conversion is done using PdfHtmlElement objects as described here.

When the pdf conversion is done using the main HtmlToPdf converter object, there is another way of adding headers and footers to the generated pdf document. That is done using the Header and Footer properties of the HtmlToPdf converter object.

Header and Footer Options are covered in more details in the following sections:

To display a custom header in the generated pdf, the DisplayHeader property of the HtmlToPdfOptions object must be set to true. If the DisplayHeader property of the Options object is false, the header will not be displayed and all the options set for the header will have no effect.

The header of the pdf document generated from the html to pdf conversion can be customized using the Header property of the HtmlToPdf converter object. That is an instance of PdfHeader class and has the following properties:

  • Height - The height of the pdf document header.

  • DisplayOnFirstPage - Controls the visibility of the header on the first page of the generated pdf document.

  • DisplayOnOddPages - Controls the visibility of the header on the odd numbered pages of the generated pdf document.

  • DisplayOnEvenPages - Controls the visibility of the header on the even numbered pages of the generated pdf document.

  • FirstPageNumber - Controls the page number for the first page being rendered.

  • TotalPagesOffset - Controls the total number of pages offset in the generated pdf document.

To add content to the pdf header, PdfHeader class exposes the Add(PdfSectionElement) method. That can be used to add 3 types of objects to the header:

Page numbers can be added to pdf document headers using PdfTextSection objects. The page number is displayed setting a {page_number} placeholder in a Text property of a PdfTextSection object that can be added to the header. By default the page numbers start with 1. This can be changed using the FirstPageNumber property of the PdfHeader object.

The total number of pages is displayed setting a {total_pages} placeholder in the Text property of a PdfTextSection object that can be added to the header. The total number of pages can be incremented with a value specified by the TotalPagesOffset property of the PdfHeader object. This could be useful when the generated pdf will be merged with other documents.

The following code sample shows how to add a custom header to the pdf document generated from a html to pdf conversion:

// instantiate a html to pdf converter object
HtmlToPdf converter = new HtmlToPdf();

// header settings
converter.Options.DisplayHeader = true;
converter.Header.DisplayOnFirstPage = true;
converter.Header.DisplayOnOddPages = true;
converter.Header.DisplayOnEvenPages = true;
converter.Header.Height = 50;

// add some html content to the header
PdfHtmlSection headerHtml = new PdfHtmlSection(headerUrl);
headerHtml.AutoFitHeight = HtmlToPdfPageFitMode.AutoFit;
converter.Header.Add(headerHtml);

// create a new pdf document converting an url
PdfDocument doc = converter.ConvertUrl(url);

// save pdf document
doc.Save(Response, false, "Sample.pdf");

// close pdf document
doc.Close();

To display a custom footer in the generated pdf, the DisplayFooter property of the HtmlToPdfOptions object must be set to true. If the DisplayFooter property of the Options object is false, the footer will not be displayed and all the options set for the footer will have no effect.

The footer of the pdf document generated from the html to pdf conversion can be customized using the Footer property of the HtmlToPdf converter object. That is an instance of PdfFooter class and has the following properties:

  • Height - The height of the pdf document footer.

  • DisplayOnFirstPage - Controls the visibility of the footer on the first page of the generated pdf document.

  • DisplayOnOddPages - Controls the visibility of the footer on the odd numbered pages of the generated pdf document.

  • DisplayOnEvenPages - Controls the visibility of the footer on the even numbered pages of the generated pdf document.

  • FirstPageNumber - Controls the page number for the first page being rendered.

  • TotalPagesOffset - Controls the total number of pages offset in the generated pdf document.

To add content to the pdf footer, PdfFooter class exposes the Add(PdfSectionElement) method. That can be used to add 3 types of objects to the footer:

Page numbers can be added to pdf document footer using PdfTextSection objects. The page number is displayed setting a {page_number} placeholder in a Text property of a PdfTextSection object that can be added to the footer. By default the page numbers start with 1. This can be changed using the FirstPageNumber property of the PdfFooter object.

The total number of pages is displayed setting a {total_pages} placeholder in the Text property of a PdfTextSection object that can be added to the footer. The total number of pages can be incremented with a value specified by the TotalPagesOffset property of the PdfFooter object. This could be useful when the generated pdf will be merged with other documents.

The following code sample shows how to add a custom footer to the pdf document generated from a html to pdf conversion:

// instantiate a html to pdf converter object
HtmlToPdf converter = new HtmlToPdf();

// footer settings
converter.Options.DisplayFooter = true;
converter.Footer.DisplayOnFirstPage = true;
converter.Footer.DisplayOnOddPages = true;
converter.Footer.DisplayOnEvenPages = true;
converter.Footer.Height = 50;

// add some html content to the footer
PdfHtmlSection footerHtml = new PdfHtmlSection(footerUrl);
footerHtml.AutoFitHeight = HtmlToPdfPageFitMode.AutoFit;
converter.Footer.Add(footerHtml);

// page numbers can be added using a PdfTextSection object
PdfTextSection text = new PdfTextSection(0, 10, "Page: {page_number} of {total_pages}  ", new System.Drawing.Font("Arial", 8));
text.HorizontalAlign = PdfTextHorizontalAlign.Right;
converter.Footer.Add(text);

// create a new pdf document converting an url
PdfDocument doc = converter.ConvertUrl(url);

// save pdf document
doc.Save(Response, false, "Sample.pdf");

// close pdf document
doc.Close();

Setting a Different Header or Footer for a Specific Pdf Page

With Select.Pdf Library for .NET it is possible to customize headers and footers of the generated pdf document and have different headers and footers on specific pages. This can be done using CustomHeader and CustomFooter properties of the PdfPage objects from the generated pdf document.

The following sample code shows how to customize the header of the 3rd page of a generated pdf document:

// instantiate a html to pdf converter object
HtmlToPdf converter = new HtmlToPdf();

// header settings
converter.Options.DisplayHeader = true;
converter.Header.DisplayOnFirstPage = true;
converter.Header.DisplayOnOddPages = true;
converter.Header.DisplayOnEvenPages = true;
converter.Header.Height = 50;

// add some html content to the header
PdfHtmlSection headerHtml = new PdfHtmlSection(headerUrl);
headerHtml.AutoFitHeight = HtmlToPdfPageFitMode.AutoFit;
converter.Header.Add(headerHtml);

// create a new pdf document converting an url
PdfDocument doc = converter.ConvertUrl(url);

// custom header on page 3
if (doc.Pages.Count >= 3)
{
    PdfPage page = doc.Pages[2];

    PdfTemplate customHeader = doc.AddTemplate(page.PageSize.Width, headerHeight);
    PdfHtmlElement customHtml = new PdfHtmlElement(
        "<div><b>This is the custom header that will appear only on page 3!</b></div>", 
        string.Empty);
    customHeader.Add(customHtml);

    page.CustomHeader = customHeader;
}

// save pdf document
doc.Save(Response, false, "Sample.pdf");

// close pdf document
doc.Close();
PdfHtmlSection Properties

A PdfHtmlSection renders a web page or an html string into the header or footer band. It has its own conversion settings, independent of the ones used for the document body:

AllowContentHeightResize - A flag used only by WebKitRestricted, Blink or Chromium engines indicating if the content height can be recalculated to better fit the page. This can introduce certain errors in some cases. The default is True. Set it to False if content is split to more pages than expected.

Authentication - Handles authentication options if the web page being converted requires authentication.

AutoFitHeight - Specifies the vertical auto fit mode. The default value of this property is NoAdjustment and for rendering, the converter will only take AutoFitWidth into consideration.

AutoFitWidth - Specifies the horizontal auto fit mode. The default value of this property is ShrinkOnly.

BlinkEngineLaunchMaxTries - Blink engine process launch tries. Note: This is used only by the Blink rendering engine.

BlinkEngineLaunchTimeout - Blink engine process launch timeout. Note: This is used only by the Blink rendering engine.

BlinkEnginePath - Gets or sets the full path (excluding the chrome.exe file name) of the Blink html rendering engine binaries.

BlinkEngineTemporaryFilesPath - Gets or sets the full path of a folder where Blink html rendering engine will write temporary files. Note: Write permissions need to be enabled for this folder.

BlinkMaxThreadPoolWorkers - Upper bound for the auto-tuned Blink ThreadPool worker floor (prevents browser-launch starvation under concurrency). 0 disables auto-tuning. Note: This is used only by the Blink rendering engine.

CefEnginePath - Gets or sets the full path of the folder containing the CEF (Chromium) html rendering engine binaries. Note: This is used only by the Chromium rendering engine.

CefEngineTemporaryFilesPath - Gets or sets the full path of a folder where the CEF rendering engine will write temporary files. Note: This is used only by the Chromium rendering engine.

ClickElementsDelayAfter - Delay in miliseconds, after element click. Note: This is used only by the Blink or Chromium rendering engine.

ClickElementsDelayBefore - Delay in miliseconds, before element click. Note: This is used only by the Blink or Chromium rendering engine.

ClickElementsSelectors - Specifies elements from the web page that will be clicked before converting the page. Note: This is used only by the Blink or Chromium rendering engine.

ConsoleLog - Returns the console log of the browser used to render the web page.

CssMediaType - Indicates what css styles are used when the web page is rendered.

CustomCSS - Use this property to specify some CSS styles that will be injected into the page that is converted. Note: This is used only by the Blink or Chromium rendering engine.

DenyLocalFileAccess - A flag indicating if local files can be loaded during the conversion. The default value is False and local files can be loaded.

DisplayCutText - Gets or sets a flag indicating if the text that is out of the calculated rendering rectangle is displayed or not. The default value for this property is False.

DrawBackground - Gets or sets a flag indicating if the web page background is rendered in pdf. The default value for this property is true and the page background is rendered into the generated pdf.

EmbedFonts - Instructs the converter to embed all the needed fonts into the pdf document or not. The default value for this property is false and the fonts are not automatically embedded.

ExternalBrowserEndpoint - External browser service. Note: This is used only by the Blink rendering engine.

ExternalLinksEnabled - Controls the rendering of external hyperlinks in pdf. The default value for this property is true and in this case all external hyperlinks from the web page will be rendered in the generated pdf document.

HiddenWebElements - Gets a reference to the object that controls the visibility of some web elements in the generated pdf document.

HttpCookies - Gets the collection of custom HTTP cookies used for the conversion.

HttpHeaders - Get the collection of custom HTTP headers used for the conversion.

HttpPostParameters - Gets the collection of custom HTTP POST parameters used for the conversion.

InternalLinksEnabled - Controls the conversion of internal html links to internal pdf links. The default value for this property is true and in this case all internal hyperlinks from the web page (links that point within the web page) will be rendered in the generated pdf document as internal pdf links (clicking one of them will jump within the pdf document).

JavaScriptEnabled - Enable scripts when rendering the url or html string. Note: If the javascript requires some time to load, MinPageLoadTime property should be set to delay the conversion with the specified number of seconds and allow the javascript to run.

KeepImagesTogether - This property instructs the converter whether to try to avoid cutting off the images between pdf pages or not. The default value is false and the converter does not try to avoid images cutting between pdf pages.

KeepTextsTogether - This property instructs the converter whether to try to avoid cutting off the text lines between pdf pages or not. The default value is true and the converter tries to avoid text cutting between pdf pages.

LazyImagesLoadingDelay - Delay per page, in miliseconds, for lazy images loading. The default value is 50 ms. Note: Honored by the Blink and Chromium rendering engines.

LazyImagesLoadingEnabled - Enables a delay mechanism to allow images to fully load. Note: Honored by the Blink and Chromium rendering engines.

LoginOptions - Handle custom page login. Note: This is used only by the Blink or Chromium rendering engine.

ManagedContentTrimming - Gets or sets whether the library decides where the rendered content ends on each page. The default value is True. With True, the page the content ends on is drawn only down to where the content ends, on a document of any length. With False, the page is shortened to the content only when the whole content fits on one page. Set it to False if pages are cut in the wrong place. Note: This is used only by the Chromium rendering engine.

ManagedContentTrimmingMode - Gets or sets how the rendering engine reports where the rendered content ends when ManagedContentTrimming is True. The default value is Ink. With Ink, the engine measures where the last painted content is after the page is rendered, so what the page paints outside its layout, such as a shadow or a positioned decoration, is kept, together with the space the last element leaves below itself. With Marker, the content ends where the page's layout ends, the way earlier versions cut; something painted outside the layout can be cut. Only the last page is affected: the pages before it are the same in both modes. An engine that does not support the Ink mode uses the Marker mode. Note: This is used only by the Chromium rendering engine.

MaxConversionTime - Timeout in seconds for the print phase. Applies to the Chromium rendering engine only. Default value is 60 seconds.

MaxPageLoadTime - The web page navigation timeout in seconds. Default value is 60 seconds.

MinPageLoadTime - An additional time in seconds to wait for asynchronous items to be loaded before the web page is rendered.

PluginsEnabled - A flag indicating if plugins (like Flash players) are enabled in the converter. The default value for this property is true.

PostLoadingScript - Use this property to specify some JavaScript code that will be injected into the page that is converted and executed after the page was fully loaded. Note: This is used only by the Blink or Chromium rendering engine.

PostLoadingScriptDelayAfter - Delay in miliseconds, after post page loading javascript injection. Note: This is used only by the Blink or Chromium rendering engine.

ProxyOptions - Gets a reference to an object containing the proxy settings used to access the web page that is being converted.

RenderPageOnTimeout - A flag indicating if the page is rendered even if a navigation timeout occurs. The default value is False and a navigation timeout exception is raised.

RenderingEngine - Gets or sets the rendering engine used by the converter to load and render the HTML. The possible values are WebKit, WebKitRestricted and Blink. The Webkit rendering engine is internal and renders similar to Apple's Safari. For Blink, Chromium binaries must be also installed.

ScaleImages - A flag indicating if the images from the page are scaled during the conversion process. The default value is False and images are not scaled.

SecureProtocol - Protocol used for secure (HTTPS) connections.

StartupMode - Use this property to specify how the conversion starts.

StartupScript - Use this property to specify some JavaScript code that will be injected into the page that is converted.

Tagged - Produce tagged, accessible (PDF/UA-style) logical structure from this HTML section's rendered content. The structure is taken from the rendering engine's own tagged output and re-mapped onto the host document as the section is stamped, exactly like the HtmlToPdf converter's Options.Tagged. The default value is False.

VisibleWebElementSelector - Convert only the part of the page matched by this CSS selector, for example "#content", ".infobox" or "table.data tbody". Note: Honored by the Blink and Chromium rendering engines; the WebKit engines take an element id instead.

VisibleWebElementId - Use this property to convert only a certain section of the page, specified by the html element ID. Honored by every rendering engine; the WebKit engines take only this form.

WebGlEnabled - Controls WebGL support in the rendering engine. Note: This is used by the Chromium and Blink rendering engines.

WebPageFixedSize - Controls whether the web page is rendered with a fixed size internal browser or the size automatically extends to make the whole content visible. Note: If WebPageFixedSize is set to true, a page height needs to be set using WebPageHeight, because the default value (0) will make the converter fail (cannot render a web page with no height).

WebPageHeight - Gets or sets the height of the converted web page as it would appear in the internal browser used to render the html. Note: the height on its own does not limit what is converted - it is the size of the browser viewport. To leave the content that does not fit this height out of the generated pdf document, set WebPageFixedSize to true as well.

WebPageWidth - Gets or sets the width of the converted web page as it would appear in the internal browser used to render the html.

See Also