HiQPdf HTML to PDF Converter allows you to add stamps to the generated PDF document using any valid HTML markup and elements. The HTML content can also include the template variables {page_number} and {total_pages} to insert page numbering.
The Zoom property sets the zoom at which the stamp HTML is laid out and drawn, at the same stamp width, 100 percent by default. Set it to BrowserZoom to give the stamp the scale of the pages, so that a font size has the same size in the stamp and in the page.
HTML stamps can be added to the conversion result using the PdfDocumentControlAddHtmlTemplate(Int32, Int32, Int32, PdfTemplateHorizontalAlign, PdfTemplateVerticalAlign, String, String) method. An object of type PdfDocumentControl is exposed through the HtmlToPdfDocument property.
There are overloaded versions of the AddHtmlTemplate() method that allow you to create HTML templates rendered on PDF pages, using either a URL to an HTML page or an HTML string with an optional base URL.
You can specify the horizontal and vertical alignment of the template on the PDF page or use absolute X and Y coordinates. The alignment takes precedence over the coordinates when it is set to a value other than None.
The template height can be automatically resized based on the HTML content or set to a fixed height, depending on the method parameters.
The most important options related to adding HTML stamps are:
HTML Stamp Options
HTML Template Source. The source of the HTML template used by the stamp can be specified when calling the AddHtmlTemplate() method and can also be modified after the stamp object is created by setting either the Html or the HtmlSourceUrl property, to provide the HTML content directly or specify a URL from which to retrieve the HTML. If both properties are set, the directly provided HTML code takes precedence. When setting the Html property, you must also set the HtmlBaseUrl property, which is used to resolve external resources in the HTML.
Stamp Visibility. You can control the visibility of the stamp on the first PDF page, odd pages and even pages using the ShowInFirstPage, ShowInOddPages and ShowInEvenPages properties.
The first page refers to the first page generated from the HTML content if ShowOnlyInHtmlToPdfPages is set to true, or to the first page of the final PDF document, which may include a table of contents or pages from external PDF documents, if it is set to false. The page following the first is considered even, the next one odd and so on.
Stamp Opacity. You can control the opacity by setting the Opacity property to a value between 0 and 1, which is applied to the entire template. For example, setting the property to 0.75 lowers the opacity to 75%. The default value is 1 and the rendered PDF content has its original opacity.
If you want to control only the opacity of the HTML template background, you can do this by setting the body element style to background-color: rgba(255, 255, 255, 0.75), which sets the opacity to 0.75, as exemplified in the HTML code below.
<!-- Use background-color: rgba(r, g, b, a) to apply background opacity (a = 0 transparent, 1 opaque) -->
<body style="background-color: rgba(255, 255, 255, 0.75)">Stamp Rotation. You can control the stamp rotation by setting the RotationDegrees property to the rotation angle in degrees applied to the entire HTML template and the RotationPivot property to the pivot used for rotating the HTML template. Positive values for RotationDegrees rotate counter-clockwise and negative values rotate clockwise. The default value is 0, which means no rotation. The default rotation pivot is the top-left corner.
HTML Template Variables. The HTML used in the stamp can include variables for page numbering, which are replaced with the actual values when the PDF pages are generated. The following template variables can be used:
{page_number}: Current page number
{total_pages}: Total number of pages in the document
Auto Size Content Height. The AutoSizeContentHeight property allows the stamp content height to be automatically resized based on the rendered HTML content height.
The minimum and maximum heights are controlled by the MinContentHeight and MaxContentHeight properties.
When this property is false, the content height is given by the Height property. When this property is true, if the Height property is set to a positive value and the FitHeight property is also true, the content may be scaled down to fit the specified height. The default value is true.
Stamp Height. You can specify a fixed height for the stamp on PDF pages using the Height property, in combination with the AutoSizeContentHeight property, to control the final height of the stamp on the PDF page.
When the height is set to a positive value, it defines the stamp height if AutoSizeContentHeight is false, or if it is true and FitHeight is also true.
When the height is set to 0 or a negative value and AutoSizeContentHeight is true, the stamp height is automatically determined based on the HTML content height. The default value is 0.
Fit Height. You can use the FitHeight property in combination with the AutoSizeContentHeight property to control the final height of the stamp on the PDF page.
If this property is set to true and AutoSizeContentHeight is also true and Height has a positive value, the HTML content may be scaled down to fit within the specified stamp height on the PDF page. The default value is true.
using System;
using System.IO;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using HiQPdf_Next_AspNetDemo.Models;
using HiQPdf.Next;
namespace HiQPdf_Next_AspNetDemo.Controllers
{
public class StampWithHtmlGeneratedPdfController : Controller
{
private readonly IWebHostEnvironment m_hostingEnvironment;
public StampWithHtmlGeneratedPdfController(IWebHostEnvironment hostingEnvironment)
{
m_hostingEnvironment = hostingEnvironment;
}
public IActionResult Index()
{
var model = SetViewModel();
return View(model);
}
[HttpPost]
public ActionResult ConvertToPdf(StampWithHtmlGeneratedPdfViewModel model)
{
if (!ModelState.IsValid)
{
var errorMessage = ModelStateHelper.GetModelErrors(ModelState);
throw new ValidationException(errorMessage);
}
// Set the serial number received after purchase to use the library in licensed mode; leave it commented for demo mode
// Licensing.SerialNumber = "your-serial-number";
// Create an HTML to PDF converter object with default settings
HtmlToPdf htmlToPdfConverter = new HtmlToPdf();
bool stampEnabled = model.StampEnabled;
if (stampEnabled)
{
PdfHtmlTemplate stamp = null;
// Get stamp width
int stampWidth = model.StampWidth;
// Get stamp height
int stampHeight = model.StampHeight.HasValue ? model.StampHeight.Value : 0;
// Get stamp top left corner X and Y position
int x = model.StampXPosition;
int y = model.StampYPosition;
// Get horizontal alignment, which takes precedence over the X coordinate when specified
PdfTemplateHorizontalAlign horizontalAlign = model.HorizontalAlign;
// Get vertical alignment, which takes precedence over the Y coordinate when specified
PdfTemplateVerticalAlign verticalAlign = model.VerticalAlign;
// Set the stamp HTML from a URL or from an HTML string
bool stampHtmlFromUrl = model.StampHtmlSource == "Url";
if (stampHtmlFromUrl)
{
string stampUrl = model.StampUrl;
if (stampHeight > 0)
{
// The stamp has a specified height
stamp = htmlToPdfConverter.Document.AddHtmlTemplate(x, y, stampWidth, stampHeight,
horizontalAlign, verticalAlign, stampUrl);
}
else
{
// The stamp size is automatically determined from the HTML content when AutoSizeContentHeight is true
stamp = htmlToPdfConverter.Document.AddHtmlTemplate(x, y, stampWidth, stampHeight,
horizontalAlign, verticalAlign, stampUrl);
}
}
else
{
string stampHtml = model.StampHtml;
string stampHtmlBaseUrl = model.StampHtmlBaseUrl;
if (stampHeight > 0)
{
// The stamp has a specified height
stamp = htmlToPdfConverter.Document.AddHtmlTemplate(x, y, stampWidth, stampHeight,
horizontalAlign, verticalAlign, stampHtml, stampHtmlBaseUrl);
}
else
{
// The stamp size is automatically determined from the HTML content when AutoSizeContentHeight is true
stamp = htmlToPdfConverter.Document.AddHtmlTemplate(x, y, stampWidth, stampHeight,
horizontalAlign, verticalAlign, stampHtml, stampHtmlBaseUrl);
}
}
// Set stamp rotation degrees. Positive values rotate counter-clockwise
stamp.RotationDegrees = model.RotationDirection == RotationDirection.CounterClockwise
? model.RotationDegrees
: -model.RotationDegrees;
// Set stamp rotation pivot
stamp.RotationPivot = model.RotationPivot;
// If AutoSizeContentHeight is true, the Height property is positive and FitHeight is true,
// the content may be scaled down to fit the specified height
bool fitStampHeight = model.FitStampHeight;
stamp.FitHeight = fitStampHeight;
// Set the auto resize stamp option to allow the stamp height adjust based on HTML content
bool autoSizeStampContentHeight = model.AutoSizeStampContentHeight;
stamp.AutoSizeContentHeight = autoSizeStampContentHeight;
// Set Min and Max content height used when the AutoSizeContentHeight property is true
stamp.MinContentHeight = model.StampMinContentHeight;
stamp.MaxContentHeight = model.StampMaxContentHeight;
// The zoom at which the stamp HTML is laid out and drawn, at the same stamp width
stamp.Zoom = model.StampZoom;
// Set stamp visibility in PDF for the first page, odd pages, and even pages
stamp.ShowInFirstPage = model.ShowStampInFirstPage;
stamp.ShowInOddPages = model.ShowStampInOddPages;
stamp.ShowInEvenPages = model.ShowStampInEvenPages;
// Sets the opacity for the entire stamp content, including text.
// To apply opacity only to the background, use the alpha channel
// in the CSS background-color property of the body element,
// e.g., background-color: rgba(255, 255, 255, 0.75);
int opacity = model.StampOpacity;
stamp.Opacity = ((float)opacity) / 100;
// Optimize the stamp rendering time by providing a hint if the HTML template contains variables such as { page_number} or { total_pages}
stamp.SkipVariablesParsing = model.SkipVariablesParsing;
// Optionally set additional time to wait for the asynchronous stamp HTML content before rendering
if (model.WaitBeforeConvert > 0)
stamp.WaitBeforeConvert = model.WaitBeforeConvert;
}
// Convert the HTML page to a PDF document in a memory buffer
byte[] outPdfBuffer = htmlToPdfConverter.ConvertUrlToMemory(model.Url);
// Send the PDF file to browser
FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf");
fileResult.FileDownloadName = "StampWithHtmlGeneratedPdf.pdf";
return fileResult;
}
private PdfTemplateHorizontalAlign SelectedHorizontalAlign(string selectedValue)
{
switch (selectedValue)
{
case "None":
return PdfTemplateHorizontalAlign.None;
case "Left":
return PdfTemplateHorizontalAlign.Left;
case "Center":
return PdfTemplateHorizontalAlign.Center;
case "Right":
return PdfTemplateHorizontalAlign.Right;
default:
return PdfTemplateHorizontalAlign.None;
}
}
private PdfTemplateVerticalAlign SelectedVerticalAlign(string selectedValue)
{
switch (selectedValue)
{
case "None":
return PdfTemplateVerticalAlign.None;
case "Top":
return PdfTemplateVerticalAlign.Top;
case "Center":
return PdfTemplateVerticalAlign.Center;
case "Bottom":
return PdfTemplateVerticalAlign.Bottom;
default:
return PdfTemplateVerticalAlign.None;
}
}
private StampWithHtmlGeneratedPdfViewModel SetViewModel()
{
var model = new StampWithHtmlGeneratedPdfViewModel();
var contentRootPath = Path.Combine(m_hostingEnvironment.ContentRootPath, "wwwroot");
HttpRequest request = ControllerContext.HttpContext.Request;
UriBuilder uriBuilder = new UriBuilder();
uriBuilder.Scheme = request.Scheme;
uriBuilder.Host = request.Host.Host;
if (request.Host.Port != null)
uriBuilder.Port = (int)request.Host.Port;
uriBuilder.Path = request.PathBase.ToString() + request.Path.ToString();
uriBuilder.Query = request.QueryString.ToString();
string currentPageUrl = uriBuilder.Uri.AbsoluteUri;
string rootUrl = currentPageUrl.Substring(0, currentPageUrl.Length - "StampWithHtmlGeneratedPdf".Length);
model.StampHtml = System.IO.File.ReadAllText(Path.Combine(contentRootPath, "DemoFiles/Html/Stamp_HTML.html"));
model.StampHtmlBaseUrl = rootUrl + "DemoFiles/Html/";
model.StampUrl = rootUrl + "DemoFiles/Html/Stamp_HTML.html";
return model;
}
}
}<!DOCTYPE html>
<html>
<head>
<title>HTML Stamp with Page Numbers</title>
</head>
<!-- Use background-color: rgba(r, g, b, a) to apply background opacity (a = 0 transparent, 1 opaque) -->
<body style="background-color: rgba(255, 255, 255, 0.9); font-family: 'Times New Roman'; font-size: 16px; margin: 5px">
<table style="width: 100%; border: 3px solid royalblue">
<tr>
<td>
<a href="http://www.hiqpdf.com">
<img alt="Logo Image" src="Images/HiQPdfLogo.png" />
</a>
</td>
<td>
<table>
<tr>
<td style="font-size: 30px; font-weight: bold; color: #BE1200">
HTML Stamp with Page Numbers
</td>
</tr>
<tr>
<td>
<span style="font-size: 16px">Page <span style="color:blue">{page_number}</span> of <span style="color:green">{total_pages}</span> pages</span>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>