How do I use HTML with CSS and Images to create a PDF in C#

IronPDF is a useful tool for generating PDF documents in .Net projects.

A common use of this library is “HTML to PDF” rendering - where HTML is used as the design language for rendering a PDF document. A logical question is: how can we use CSS stylesheets and Image files in our HTML to PDF Conversion?

Rendering a PDF from HTML string with Image and CSS assets

The answer in the case of HTML String to PDF is that we should set a BaseUri when working with assets.

All assets such as CSS, JavaScript files and images will be loaded relative to that base URL.

The BaseURL may be a web url starting with “http” to load remote assets, or a local file path to access assets on your disk.

e.g.

var PDF = Renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>",@"C:\site\assets\");
PDF.SaveAs("html-with-assets.pdf");
Dim PDF As var = Renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", "C:\site\assets\")
PDF.SaveAs("html-with-assets.pdf")
VB   C#

Another trick is to use the IronPdf.Util.ImageToDataUri method to convert any System.Drawing.Image or Bitmap object into a html string which can be embedded in html without saving to disk.

Var DataURI = IronPdf.Util.ImageToDataUri(myImageObject)
var PDF = Renderer.RenderHtmlAsPdf("<img src='"+ DataURI +"'>");
PDF.SaveAs("html-with-embeded-image.pdf");
Dim DataURI As Var = IronPdf.Util.ImageToDataUri(myImageObject)
PDF.SaveAs("html-with-embeded-image.pdf")
VB   C#

HTML Headers and Footers with Images and Assets

When we render HTML headers and footers to a new or existing PDF, they are treated as standalone HTML documents and do not inherit the BaseURL from the PDF its self.

We should set a BaseURL from which assets may be loaded:

IronPdf.HtmlToPdf Renderer = new IronPdf.HtmlToPdf();
Renderer.PrintOptions.Header = new HtmlHeaderFooter()
{
  Height = 20,
  HtmlFragment = "<img src='logo.png'>",
  BaseUrl = new Uri(@"C:\assets\images\").AbsoluteUri
};
Dim Renderer As IronPdf.HtmlToPdf = New IronPdf.HtmlToPdf
Renderer.PrintOptions.Header = New HtmlHeaderFooter
VB   C#

HTML file to PDF with CSS, JS and Image Assets

When rendering an HTML file to PDF, all assets will be assumed local to that file.

 var Renderer = new IronPdf.HtmlToPdf();
 var PDF = Renderer.RenderHTMLFileAsPdf(“C:\\Assets\\TestInvoice1.html”);
 PDF.SaveAs("Invoice.pdf");
Dim Renderer As var = New IronPdf.HtmlToPdf
Dim PDF As var = Renderer.RenderHTMLFileAsPdf(C:= Assets, TestInvoice1.html)
PDF.SaveAs("Invoice.pdf")
VB   C#

In the above example, all JS, CSS and image files will be loaded from the C:\Assets folder on the disk - the same directory that the HTML file is located.

For convenience, you may use PdfPrintOptions.CustomCssUrl to specify an additional stylesheet that is only used for P.Net PDF rendering if you so desire.