Articles in this section
Category / Section

How to Inject Custom CSS to HTML Before Rendering into a PDF document

2 mins read

The Syncfusion HTML to PDF Converter is a .NET library for converting webpages, SVG, MHTML, and HTML to PDF using C#. It is reliable and accurate. The result preserves all graphics, texts, fonts, and the original HTML document or webpage layout.

Using this library, you can inject CSS to be applied to HTML or a URL before rendering it into a PDF document.

Steps to inject custom CSS to HTML before rendering into a PDF document

  1. Create a new .NET console application project.

    Console application creation

  2. Install the Syncfusion.HtmlToPdfConverter.Net.Windows NuGet package as a reference to your .NET application from NuGet.org.

    NuGet_references.png

  3. Include the following namespaces in the Program.cs file.

using Syncfusion.Drawing;
using Syncfusion.HtmlConverter;
using Syncfusion.Pdf;
  1. Use the following code example to inject custom CSS to be applied to HTML or a URL before rendering it into a PDF document.
//Initialize the HTML to PDF converter.
HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter();
BlinkConverterSettings blinkConverterSettings = new BlinkConverterSettings();
//Set the Blink viewport size.
blinkConverterSettings.ViewPortSize = new Size(1280, 0);
blinkConverterSettings.Margin.All = 30;
//Set the custom CSS.
blinkConverterSettings.Css = "body {\r\n background-color: lightyellow; \r\n}";
htmlConverter.ConverterSettings = blinkConverterSettings;
//Convert the URL to a PDF document.
PdfDocument document = htmlConverter.Convert("https://www.google.com");

using (FileStream stream = new FileStream("Sample.pdf", FileMode.Create))
{
   //Save a PDF document.
   document.Save(stream);
}

A complete working sample can be downloaded from Inject-custom-CSS-to-HTML.zip.

By executing the program, you will get a PDF document as follows.

Output.png

Take a moment to peruse the documentation, where you can find converting HTML pages to PDF documents along with respective customization options and features.

Refer to here to explore the rich set of Syncfusion Essential PDF features.

An online sample link for converting HTML to PDF document.

Note: Starting with v16.2.0.x, if you reference Syncfusion assemblies from the trial setup or the NuGet feed, include a license key in your projects. Refer to the link to learn how to generate and register the Syncfusion license key in your application and use the components without a trial message.

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied