Published October 1, 2021
Wkhtmltopdf C# Comparison with Code Examples
Choosing the best component to work with PDF files programmatically can be a daunting task, but one that ultimately can save you time and effort. We'll explore the necessary code and step-by-step tutorials for working with PDFs using wkhtmltopdf and IronPDF, as well as their systems compatability and licensing structure to help you decide what's best for your project.
Read below for tutorials on how to create PDF files, use pre-defined functions such as implementing headers & footers, generate files, and more.
Overview
About IronPDF
IronPDF is a component for working with PDF files provided by the Iron Software C# library. Using IronPDF, we can easily create PDF files by URL or HTML string, and set Headers, Foorters, Watermarks, Margins and other PDF file properties programmatically. IronPDF is well known for its reputable library of products, clear documentation and natural language, making it easy to implement in developer projects.
About wkhtmltopdf
wkhtmltopdf is a C++ software binary to render PDF files. It can be used to create PDF files by URL or HTML string. It also provides a way to set Headers, Footers, Margins and other properties of PDF files by working on the basis of Command Line Interface (CLI). However, it is not designed in .NET framework, so it may be difficult to integrate with .NET applications (read more for our workaround). In addition, it is not consistently maintained by a company with updates. Instead, it was originally created by Jakob Truelsen and maintained by Ashish Kulkarni, a couple of developers.
How to Use Wkhtmltopdf C# Example
- Download wkhtmlpdf.exe file and install it
- Start a new process to execute the command with wkhtmltopdf.exe file
- Create a method in C# and call it the Main()
- Copy code from section URL to PDF Using wkhtmltopdf
- Run the C# code
Quick Comparison
1. IronPDF vs. wkhtmltopdf
To help you choose which component may be best for your project, we will provide code samples and a tutorial walk through on how to create, edit, and manage PDF files using both wkhtmltopdf and IronPDF. Here is a quick overview of the features and usability of both resources.
IronPDF | wkhtmltopdf |
---|---|
IronPDF converts HTML to PDF | wkhtmltopdf converts HTML to PDF |
Supports Windows, Linux and macOS | Supports Windows, Ubuntu, Amazon Linux and macOS |
Designed in .NET Framework using C# | Designed in C++ |
A Dynamic Link Library (.dll), becomes part of your project | A .exe file, used separately |
IronPDF sets Headers, Footers, and directional margins | wkhtmltopdf sets Headers, Footers, and directional margins |
`RenderDelay` function to delay rendering, ensure WebPage loads successfully | `javascript-delay` function to delay rendering until JavaScript execution finishes |
Frequently updated with new features and product fixes | Infrequent product updates |
Great for .NET projects | Great for CLI / Shell projects |
Predefined functions to watermark specific pages | No predefined function to add watermarks |
Render Edit, Fill, Parse and Sign PDFs. | Rendering only. |
Technical support team always available | No known technical support |
Step 1: Installation
2. IronPDF Install
IronPDF can be installed into your system by using two different approaches, and you can use whatever is easiest for your project needs.
2.1. Install Using NuGet Package
The first approach is to use the NuGet Package Manager
of Visual Studio. Open it and browse IronPDF
(provided by Iron
), then install it.
PM > Install-Package IronPdf
2.2 Download IronPdf.dll
The second approach is to download the IronPDF.dll file. After downloading, provide the path of this file in the project references in order to add its reference.
Note: You can import the libraries of IronPDF
by writing the following line using IronPdf;
2.3. IronPDF Supported Platforms
IronPDF is compatible with many languages and platforms.
.NET framework 4.0 or above using
- Windows
- Azure
.NET Standard 2.0 & Core 2 & 3 using
- Windows
- macOS
- Linux
- Azure
Cloud hosting services includes
- Microsoft Azure
- Docker
- AWS
IronPDF can be used for
- ASP.NET MVC Applications
- ASP.NET Web Forms Applications
- Console Applications
- Cloud Applications
- Services
- Functions
- Desktop Applications
2.4. IronPDF Dependencies
The following dependencies are required for using IronPDF.
For .NET Framework 4.0 or above:
- Iron.Assets.Rendering.Windows (>= 20.0.0)
For .NET Standard 2.0 or above
- Iron.Assets.Rendering.Universal (>= 20.0.0)
- System.Drawing.Common (>= 4.7.0)
How To Tutorials
Install Wkhtmltopdf
- Download the latest wkhtmlpdf.exe file, related to your system specifications.
- If it's compressed, uncompress it and run the file.
- Restart all running servers.
After the installation, if you install 32-bit, it will create a new folder named wkhtmltopdf
in C:\Program Files (x86)
, which include some necessary files.
If you install 64-bit, then this folder will create C:\Program Files
.
Once the folder is created, wkhtmltopdf will be successfully installed on your system.
3. Create PDF from URL
When we talk about about dealing with PDF files, the basic use case that comes to mind is how to create a PDF file from a URL.
3.1. URL to PDF using IronPDF
Using IronPDF, we can use the simple conversion below.
/**
URL to PDF
anchor-url-to-pdf-using-ironpdf
**/
using IronPdf;
{
var converter = new ChromePdfRenderer();
//Specify URL
using var PDF = converter.RenderUrlAsPdf("URL");
//Save the file
PDF.SaveAs("Sample.pdf");
Console.WriteLine("successfully created!");
Console.ReadKey();
}
/**
URL to PDF
anchor-url-to-pdf-using-ironpdf
**/
using IronPdf;
{
var converter = new ChromePdfRenderer();
//Specify URL
using var PDF = converter.RenderUrlAsPdf("URL");
//Save the file
PDF.SaveAs("Sample.pdf");
Console.WriteLine("successfully created!");
Console.ReadKey();
}
'''
'''URL to PDF
'''anchor-url-to-pdf-using-ironpdf
'''*
Private ReadOnly Property IronPdf() As using
Dim converter = New ChromePdfRenderer()
'Specify URL
Dim PDF = converter.RenderUrlAsPdf("URL")
'Save the file
PDF.SaveAs("Sample.pdf")
Console.WriteLine("successfully created!")
Console.ReadKey()
End Property
The above code will create a Sample.pdf
file of a complete WebPage from the specified URL, and save it in the specified location.
Note:
- If you do not specify a path and just give the file name, then the PDF file will be created in the
bin\Debug
folder of your project. - If you want to create a PDF file in another location e.g, in
Local Disk E
, then you can writeE:\\Sample.pdf
.
Now, let's see how to create a PDF file by URL using wkhtmltopdf.
3.2. URL to PDF Using wkhtmltopdf
As we discussed above, wkhtmltopdf is not designed in .NET framework. But we can still use it in our .NET applications.
For this, we will start a new process to execute the command with wkhtmltopdf.exe
file, as in the following example.
To avoid any complexity and confusion, we create a method and call it the Main()
function as follows:
using System.Text;
using System.Diagnostics;
static void Main(string[] args)
{
//function calling
ConvertChromePdfRenderer("URL", "Sample.pdf");
Console.WriteLine("successfully created!");
Console.ReadKey();
}
//function declaration
public static void ConvertChromePdfRenderer(string url, string filename)
{
//function definition
StringBuilder paramsBuilder = new StringBuilder();
//make CLI command
paramsBuilder.AppendFormat("\"{0}\" \"{1}\"", url, filename);
//create new process
using (Process process = new Process())
{
//specify wkhtmltopdf.exe file path to execute above CLI
process.StartInfo.FileName = "C:\\Program Files (x86)\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";
//assign CLI as process argument
process.StartInfo.Arguments = paramsBuilder.ToString();
//setting the credentials
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
//start execution
process.Start();
if (!process.WaitForExit(60000))
{
process.Kill();
}
}
}
using System.Text;
using System.Diagnostics;
static void Main(string[] args)
{
//function calling
ConvertChromePdfRenderer("URL", "Sample.pdf");
Console.WriteLine("successfully created!");
Console.ReadKey();
}
//function declaration
public static void ConvertChromePdfRenderer(string url, string filename)
{
//function definition
StringBuilder paramsBuilder = new StringBuilder();
//make CLI command
paramsBuilder.AppendFormat("\"{0}\" \"{1}\"", url, filename);
//create new process
using (Process process = new Process())
{
//specify wkhtmltopdf.exe file path to execute above CLI
process.StartInfo.FileName = "C:\\Program Files (x86)\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";
//assign CLI as process argument
process.StartInfo.Arguments = paramsBuilder.ToString();
//setting the credentials
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
//start execution
process.Start();
if (!process.WaitForExit(60000))
{
process.Kill();
}
}
}
Imports System.Text
Imports System.Diagnostics
Shared Sub Main(ByVal args() As String)
'function calling
ConvertChromePdfRenderer("URL", "Sample.pdf")
Console.WriteLine("successfully created!")
Console.ReadKey()
End Sub
'function declaration
Public Shared Sub ConvertChromePdfRenderer(ByVal url As String, ByVal filename As String)
'function definition
Dim paramsBuilder As New StringBuilder()
'make CLI command
paramsBuilder.AppendFormat("""{0}"" ""{1}""", url, filename)
'create new process
Using process As New Process()
'specify wkhtmltopdf.exe file path to execute above CLI
process.StartInfo.FileName = "C:\Program Files (x86)\wkhtmltopdf\bin\wkhtmltopdf.exe"
'assign CLI as process argument
process.StartInfo.Arguments = paramsBuilder.ToString()
'setting the credentials
process.StartInfo.UseShellExecute = False
process.StartInfo.RedirectStandardOutput = True
process.StartInfo.RedirectStandardError = True
'start execution
process.Start()
If Not process.WaitForExit(60000) Then
process.Kill()
End If
End Using
End Sub
Please do not use this code above in production. It is not thread safe and will cause deadlocks in server applications !
This code will create the following command and execute it with wkhtmltopdf.exe
usingthe process "URL" "FileName.pdf"
The above code also creates a Sample.pdf
file, just like we created using IronPDF, and saves it in the specified location.
We can easily observe how much easier it is to work with IronPDF within just a few lines of code. When we use wkhtmltopdf, we need to run a separate process which affects the system performance in addition to writing many lines of code.
Now, let's talk about both components provided functions and understand their functionality.
4. Functions to work with PDFs
When we evaluate two different components and we need to select the best one, then it is very important to know which component provides the most functions, how easily we can use them in the project, and which require the least lines of code.
4.1. IronPDF Functions
We can use IronPDF functions within Curly Brackets {}
as follows:
{page}
to print the current page number.{total-pages}
to print total number of pages.{url}
to print the URL of rendered web page.{date}
to print current date.{time}
to print current time.{html-title}
to print webpage title.{pdf-title}
to print document title.
How can we use the above functions in our project? Let's see the following example.
/**
PDF Functions
anchor-ironpdf-functions
**/
using IronPdf;
{
var converter = new IronPdf.ChromePdfRenderer();
//setting header
converter.RenderingOptions.TextHeader = new TextHeaderFooter()
{
RightText = "{date} {time}"
};
//setting footer
converter.RenderingOptions.TextFooter = new TextHeaderFooter()
{
CenterText= "Page {page} of {total-pages}"
};
using var PDF = converter.RenderUrlAsPdf("URL");
PDF.SaveAs("Sample.pdf");
Console.WriteLine("successfully created..!");
Console.ReadKey();
}
/**
PDF Functions
anchor-ironpdf-functions
**/
using IronPdf;
{
var converter = new IronPdf.ChromePdfRenderer();
//setting header
converter.RenderingOptions.TextHeader = new TextHeaderFooter()
{
RightText = "{date} {time}"
};
//setting footer
converter.RenderingOptions.TextFooter = new TextHeaderFooter()
{
CenterText= "Page {page} of {total-pages}"
};
using var PDF = converter.RenderUrlAsPdf("URL");
PDF.SaveAs("Sample.pdf");
Console.WriteLine("successfully created..!");
Console.ReadKey();
}
'''
'''PDF Functions
'''anchor-ironpdf-functions
'''*
Private ReadOnly Property IronPdf() As using
Dim converter = New IronPdf.ChromePdfRenderer()
'setting header
converter.RenderingOptions.TextHeader = New TextHeaderFooter() With {.RightText = "{date} {time}"}
'setting footer
converter.RenderingOptions.TextFooter = New TextHeaderFooter() With {.CenterText= "Page {page} of {total-pages}"}
Dim PDF = converter.RenderUrlAsPdf("URL")
PDF.SaveAs("Sample.pdf")
Console.WriteLine("successfully created..!")
Console.ReadKey()
End Property
This code will create a PDF file of the specified URL WebPage, print date and time in the header on right side, and print the current page number in the center of the footer.
4.2. wkhtmltopdf Functions
Some basic functions of wkhtmltopdf are given below. These functions can be used within Square Brackets []
as follows
[page]
to print current page number.[topage]
to print the last page number or total number of pages.[webpage]
to print the URL of the page being converted.[date]
to print current date.[time]
to print current time.[title]
to print title of current page.
Read more about wkhtmltopdf functions here.
Let's see an example of how to use these functions in the project.
using System.Text;
using System.Diagnostics;
static void Main(string[] args)
{
ConvertChromePdfRenderer("URL", "Sample.pdf");
Console.WriteLine("ok");
Console.ReadKey();
}
public static void ConvertChromePdfRenderer(string url, string filename)
{
StringBuilder paramsBuilder = new StringBuilder();
paramsBuilder.AppendFormat("--header-right \"[date][time]\" --footer-center \"Page[page] of[topage]\" \"{0}\" \"{1}\"", url, filename);
using (Process process = new Process())
{
process.StartInfo.FileName = "C:\\Program Files (x86)\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";
process.StartInfo.Arguments = paramsBuilder.ToString();
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.Start();
if (!process.WaitForExit(60000))
{
process.Kill();
}
}
}
using System.Text;
using System.Diagnostics;
static void Main(string[] args)
{
ConvertChromePdfRenderer("URL", "Sample.pdf");
Console.WriteLine("ok");
Console.ReadKey();
}
public static void ConvertChromePdfRenderer(string url, string filename)
{
StringBuilder paramsBuilder = new StringBuilder();
paramsBuilder.AppendFormat("--header-right \"[date][time]\" --footer-center \"Page[page] of[topage]\" \"{0}\" \"{1}\"", url, filename);
using (Process process = new Process())
{
process.StartInfo.FileName = "C:\\Program Files (x86)\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";
process.StartInfo.Arguments = paramsBuilder.ToString();
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.Start();
if (!process.WaitForExit(60000))
{
process.Kill();
}
}
}
Imports System.Text
Imports System.Diagnostics
Shared Sub Main(ByVal args() As String)
ConvertChromePdfRenderer("URL", "Sample.pdf")
Console.WriteLine("ok")
Console.ReadKey()
End Sub
Public Shared Sub ConvertChromePdfRenderer(ByVal url As String, ByVal filename As String)
Dim paramsBuilder As New StringBuilder()
paramsBuilder.AppendFormat("--header-right ""[date][time]"" --footer-center ""Page[page] of[topage]"" ""{0}"" ""{1}""", url, filename)
Using process As New Process()
process.StartInfo.FileName = "C:\Program Files (x86)\wkhtmltopdf\bin\wkhtmltopdf.exe"
process.StartInfo.Arguments = paramsBuilder.ToString()
process.StartInfo.UseShellExecute = False
process.StartInfo.RedirectStandardOutput = True
process.StartInfo.RedirectStandardError = True
process.Start()
If Not process.WaitForExit(60000) Then
process.Kill()
End If
End Using
End Sub
This code will create the following command and execute it with wkhtmltopdf.exe
using the process: --header-right "[date][time]" --footer-center "Page[page] of[topage]" "URL" "Sample.pdf"
It will also create the same PDF file as we created with IronPDF, with datetime
in the header on the right side and current page of total page
in the center of the footer.
5. Create PDF from HTML String
It is a very common requirement to create a PDF file using HTML string. For this, both components provide a way to create PDF files. Keep in mind that IronPDF was developed in .NET framework and wkhtmltopdf developed in C++
, so for this reason both components have completely different way to deals with PDF files.
5.1. HTML String to PDF using IronPDF
/**
HTML String to PDF
anchor-html-string-to-pdf-using-ironpdf
**/
using IronPdf;
{
var converter = new ChromePdfRenderer();
//HTML string
string HTML = "<h1>Hello IronPDF!</h1> <h2>Welcome to PDF File</h2> ";
//convert HTML string to PDF file
using var PDF = converter.RenderHtmlAsPdf(HTML);
//Save the file
PDF.SaveAs("Sample.pdf");
Console.WriteLine("successfully created..!");
Console.ReadKey();
}
/**
HTML String to PDF
anchor-html-string-to-pdf-using-ironpdf
**/
using IronPdf;
{
var converter = new ChromePdfRenderer();
//HTML string
string HTML = "<h1>Hello IronPDF!</h1> <h2>Welcome to PDF File</h2> ";
//convert HTML string to PDF file
using var PDF = converter.RenderHtmlAsPdf(HTML);
//Save the file
PDF.SaveAs("Sample.pdf");
Console.WriteLine("successfully created..!");
Console.ReadKey();
}
'''
'''HTML String to PDF
'''anchor-html-string-to-pdf-using-ironpdf
'''*
Private ReadOnly Property IronPdf() As using
Dim converter = New ChromePdfRenderer()
'HTML string
Dim HTML As String = "<h1>Hello IronPDF!</h1> <h2>Welcome to PDF File</h2> "
'convert HTML string to PDF file
Dim PDF = converter.RenderHtmlAsPdf(HTML)
'Save the file
PDF.SaveAs("Sample.pdf")
Console.WriteLine("successfully created..!")
Console.ReadKey()
End Property
Output:
Here is a screenshot of the newly created Sample.pdf
file by IronPDF:
Note:
- If we do not specify the complete path and just write the file name, as we did in above code, then the PDF file will be created in the
bin\Debug
folder of the project.
5.2. HTML String to PDF using wkhtmltopdf
Working with wkhtmltopdf is a little bit complex, so to make it more clear for better understanding, we define a function and call it Main()
function as follows
using System.Text;
using System.Diagnostics;
static void Main(string[] args)
{
//Html string
string HTML = "<h1>Hello wkhtmltopdf!</h1><h2>Welcome to PDF File</h2>";
//Function calling
ConvertChromePdfRenderer(HTML, "Sample.pdf");
Console.WriteLine("ok");
Console.ReadKey();
}
//Function Declaration
public static void ConvertChromePdfRenderer(string html, string path)
{
//Function Definition
StringBuilder paramsBuilder = new StringBuilder();
//Build command
paramsBuilder.AppendFormat("\"-\" \"{0}\"", path);
//process to execute above command
using (Process process = new Process())
{
//path of wkhtmltopdf.exe file
string filepath= "C:\\Program Files (x86)\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";
//specify path
process.StartInfo.FileName = filepath;
//set command by argument
process.StartInfo.Arguments = paramsBuilder.ToString();
//set credentials
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardInput = true;
//start process
process.Start();
using (var stream = process.StandardInput)
{
byte[] buffer = Encoding.UTF8.GetBytes(html);
stream.BaseStream.Write(buffer, 0, buffer.Length);
stream.WriteLine();
}
}
}
using System.Text;
using System.Diagnostics;
static void Main(string[] args)
{
//Html string
string HTML = "<h1>Hello wkhtmltopdf!</h1><h2>Welcome to PDF File</h2>";
//Function calling
ConvertChromePdfRenderer(HTML, "Sample.pdf");
Console.WriteLine("ok");
Console.ReadKey();
}
//Function Declaration
public static void ConvertChromePdfRenderer(string html, string path)
{
//Function Definition
StringBuilder paramsBuilder = new StringBuilder();
//Build command
paramsBuilder.AppendFormat("\"-\" \"{0}\"", path);
//process to execute above command
using (Process process = new Process())
{
//path of wkhtmltopdf.exe file
string filepath= "C:\\Program Files (x86)\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";
//specify path
process.StartInfo.FileName = filepath;
//set command by argument
process.StartInfo.Arguments = paramsBuilder.ToString();
//set credentials
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardInput = true;
//start process
process.Start();
using (var stream = process.StandardInput)
{
byte[] buffer = Encoding.UTF8.GetBytes(html);
stream.BaseStream.Write(buffer, 0, buffer.Length);
stream.WriteLine();
}
}
}
Imports System.Text
Imports System.Diagnostics
Shared Sub Main(ByVal args() As String)
'Html string
Dim HTML As String = "<h1>Hello wkhtmltopdf!</h1><h2>Welcome to PDF File</h2>"
'Function calling
ConvertChromePdfRenderer(HTML, "Sample.pdf")
Console.WriteLine("ok")
Console.ReadKey()
End Sub
'Function Declaration
Public Shared Sub ConvertChromePdfRenderer(ByVal html As String, ByVal path As String)
'Function Definition
Dim paramsBuilder As New StringBuilder()
'Build command
paramsBuilder.AppendFormat("""-"" ""{0}""", path)
'process to execute above command
Using process As New Process()
'path of wkhtmltopdf.exe file
Dim filepath As String= "C:\Program Files (x86)\wkhtmltopdf\bin\wkhtmltopdf.exe"
'specify path
process.StartInfo.FileName = filepath
'set command by argument
process.StartInfo.Arguments = paramsBuilder.ToString()
'set credentials
process.StartInfo.UseShellExecute = False
process.StartInfo.RedirectStandardError = True
process.StartInfo.RedirectStandardInput = True
'start process
process.Start()
Using stream = process.StandardInput
Dim buffer() As Byte = Encoding.UTF8.GetBytes(html)
stream.BaseStream.Write(buffer, 0, buffer.Length)
stream.WriteLine()
End Using
End Using
End Sub
Output:
A screenshot of newly created Sample.pdf
file by wkhtmltopdf:
5.3. Another Comparison of IronPDF and WkhtmlToPdf
WkhtmlToPdf is an open source product. It does not have all of the same features that IronPDF has. Here I tried to understand the key differences between them.
The best way to compare, is to do a practical test.
I converted the Web App Admin Theme page to PDF using WkHtmlToPdf, and then used IronPDF.
WkhtmlToPdf Quality of Rendering
There is a clear difference between IronPDF and WkHtmlToPdf quality of rendering PDF.
UI Design
When I converted the Web App Admin Theme page, WkHtmlToPdf misses all the CSS files that have to be applied on the web page.
The CSS and JS files are important to the UI design. WkHtmlToPdf starts rendering the page without loading these necessary files.
In comparison IronPDF renders the CSS and JS files with high accuracy.
Colors
The WkHtmlToPdf file rendering does not capture the colors in the background. Again, IronPDF has a better outcome with more accurate colors shown in the rendering.
Headers
In the WkHtmlToPdf rendering the header is completely missing. In the IronPDF rendering the header is featured and in correct position.
Buttons
The placement of buttons on a webpage is obviously important. Changing a button, and a CTA (Call to Action) changes the intent. In the WkHtmlToPdf the buttons are not placed in their exact position. It is totally different from the original web page design.
On the other hand, if we talk about the IronPDF file, we see the button placement is accurate.
Conclusion
The way IronPDF pauses and waits for all files to load before it renders. This step in itself improves the outcome. IronPDF overall gives a more accurate result.
5.4. Comparison Conclusion
After reading the above article and understanding both of the above examples, it is clear that IronPDF provides a simple way to create a PDF file, and that its generated PDF file is more readable than wkhtmltopdf because it automatically adjusts the margins on the left and right sides.
IronPdf also allows us to parse, edit, merge and sign PDFs.
On the other hand, wkhtmltopdf is more complex because we need to add a separate process and run it, which affects the performance of the project.
6. Add Headers and Footers
Both components provide the functions to add Headers and Footers in a PDF file, but both have different programming structures (IronPDF with .NET Framework, and wkhtmltopdf in C++).
6.1. Add Headers and Footers using IronPDF
IronPDF provides the following functions to set the properties of both Headers and Footers. It can be written in CamelCase
.
- CenterText to write the text of the Header or Footer in the center.
- DrawDividerLine to draw a horizontal line to separate the content from Header or Footer.
- FontFamily to specify font family of Header or Footer.
- FontSize to set font size of Header and Footer.
- LeftText to write text on the left side in Header or Footer.
- RightText to write text on the right side in Header or Footer.
- Spacing to set spacing between page content and Header or Footer.
/**
Add Header Footer
anchor-add-headers-and-footers-using-ironpdf
**/
using IronPdf;
{
var converter = new IronPdf.ChromePdfRenderer();
converter.RenderingOptions.TextHeader = new TextHeaderFooter()
{
LeftText = "MyTask",
RightText = "{date} - {time}",
DrawDividerLine = true,
};
converter.RenderingOptions.TextFooter = new TextHeaderFooter()
{
RightText = "Page {page} of {total-pages}"
};
using var PDF = converter.RenderHtmlAsPdf("<h1 style='text-align:center'>Welcome To IronPdf</h1>");
PDF.SaveAs("Sample.pdf");
Console.WriteLine("successfully created..!");
Console.ReadKey();
}
/**
Add Header Footer
anchor-add-headers-and-footers-using-ironpdf
**/
using IronPdf;
{
var converter = new IronPdf.ChromePdfRenderer();
converter.RenderingOptions.TextHeader = new TextHeaderFooter()
{
LeftText = "MyTask",
RightText = "{date} - {time}",
DrawDividerLine = true,
};
converter.RenderingOptions.TextFooter = new TextHeaderFooter()
{
RightText = "Page {page} of {total-pages}"
};
using var PDF = converter.RenderHtmlAsPdf("<h1 style='text-align:center'>Welcome To IronPdf</h1>");
PDF.SaveAs("Sample.pdf");
Console.WriteLine("successfully created..!");
Console.ReadKey();
}
'''
'''Add Header Footer
'''anchor-add-headers-and-footers-using-ironpdf
'''*
Private ReadOnly Property IronPdf() As using
Dim converter = New IronPdf.ChromePdfRenderer()
converter.RenderingOptions.TextHeader = New TextHeaderFooter() With {
.LeftText = "MyTask",
.RightText = "{date} - {time}",
.DrawDividerLine = True
}
converter.RenderingOptions.TextFooter = New TextHeaderFooter() With {.RightText = "Page {page} of {total-pages}"}
Dim PDF = converter.RenderHtmlAsPdf("<h1 style='text-align:center'>Welcome To IronPdf</h1>")
PDF.SaveAs("Sample.pdf")
Console.WriteLine("successfully created..!")
Console.ReadKey()
End Property
Output:
This is a screenshot of the newly created Sample.pdf
file by IronPDF.
We can easily see the mytask
text is printed left side of Header, date time
is printed on right side of Header and current page of total pages
printed on right side of Footer.
Note:
- If we do not specify the complete path and just write the file name, as we did in above code then the PDF file will be created in the
bin\Debug
folder of the project.
6.2. Add Headers and Footers using wkhtmltopdf
wkhtmltopdf also provides many functions to deal with Headers and Footers of a PDF file. It provides separate functions for Header and for Footer. For this, we need to put two dashes (--
) before every property name and a single dash (-
) to joint the property name as follows:
Setting Header Properties
- --header-center to print the Header text in center.
- --header-right to print the Header text on right side.
- --header-left to print the Header text on left side.
- --header-font-name to specify font family for Header text.
- --header-font-size to specify font size for Header text.
- --header-line to draw Header line which separate the Header from content.
- --no-header-line remove Header line between Header and content of page.
- --header-spacing to specify the space between Header and content of page.
Setting Footer Properties
- --footer-center to print the Footer text in center.
- --footer-right to print the Footer text on right side.
- --footer-left to print the Footer text on left side.
- --footer-font-name to specify font family for Footer text.
- --footer-font-size to specify font size for Footer text.
- --footer-line to draw Footer line which separate the Footer from content.
- --no-footer-line remove footer line between Footer and content of page
- --footer-spacing to specify the space between Footer and content of page.
Read more about the header and footer wkhtmltopdf functions and more.
In this example, to avoid the complexity we will create a function separately, so that we can easily understand its working. We will create the same PDF file as we create in the above example:
using System.Text;
using System.Diagnostics;
static void Main(string[] args)
{
ConvertChromePdfRenderer("<h1 style='text-align:center'>Welcom to wkhtmltopdf</h1>", "MyTask", "Sample.pdf");
Console.WriteLine("Successfully Created");
Console.ReadKey();
}
public static void ConvertChromePdfRenderer(string html, string header, string path)
{
StringBuilder paramsBuilder = new StringBuilder();
paramsBuilder.AppendFormat("--header-left \"{0}\" --header-right \"[date] - [time]\" --header-line --footer-right \"Page[page] of[topage]\" \"-\" \"{1}\"", header, path);
using (Process process = new Process())
{
process.StartInfo.FileName = "C:\\Program Files (x86)\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";
process.StartInfo.Arguments = paramsBuilder.ToString();
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardInput = true;
process.Start();
using (var stream = process.StandardInput)
{
byte[] buffer = Encoding.UTF8.GetBytes(html);
stream.BaseStream.Write(buffer, 0, buffer.Length);
stream.WriteLine();
}
}
}
using System.Text;
using System.Diagnostics;
static void Main(string[] args)
{
ConvertChromePdfRenderer("<h1 style='text-align:center'>Welcom to wkhtmltopdf</h1>", "MyTask", "Sample.pdf");
Console.WriteLine("Successfully Created");
Console.ReadKey();
}
public static void ConvertChromePdfRenderer(string html, string header, string path)
{
StringBuilder paramsBuilder = new StringBuilder();
paramsBuilder.AppendFormat("--header-left \"{0}\" --header-right \"[date] - [time]\" --header-line --footer-right \"Page[page] of[topage]\" \"-\" \"{1}\"", header, path);
using (Process process = new Process())
{
process.StartInfo.FileName = "C:\\Program Files (x86)\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";
process.StartInfo.Arguments = paramsBuilder.ToString();
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardInput = true;
process.Start();
using (var stream = process.StandardInput)
{
byte[] buffer = Encoding.UTF8.GetBytes(html);
stream.BaseStream.Write(buffer, 0, buffer.Length);
stream.WriteLine();
}
}
}
Imports System.Text
Imports System.Diagnostics
Shared Sub Main(ByVal args() As String)
ConvertChromePdfRenderer("<h1 style='text-align:center'>Welcom to wkhtmltopdf</h1>", "MyTask", "Sample.pdf")
Console.WriteLine("Successfully Created")
Console.ReadKey()
End Sub
Public Shared Sub ConvertChromePdfRenderer(ByVal html As String, ByVal header As String, ByVal path As String)
Dim paramsBuilder As New StringBuilder()
paramsBuilder.AppendFormat("--header-left ""{0}"" --header-right ""[date] - [time]"" --header-line --footer-right ""Page[page] of[topage]"" ""-"" ""{1}""", header, path)
Using process As New Process()
process.StartInfo.FileName = "C:\Program Files (x86)\wkhtmltopdf\bin\wkhtmltopdf.exe"
process.StartInfo.Arguments = paramsBuilder.ToString()
process.StartInfo.UseShellExecute = False
process.StartInfo.RedirectStandardError = True
process.StartInfo.RedirectStandardInput = True
process.Start()
Using stream = process.StandardInput
Dim buffer() As Byte = Encoding.UTF8.GetBytes(html)
stream.BaseStream.Write(buffer, 0, buffer.Length)
stream.WriteLine()
End Using
End Using
End Sub
The above code will execute the following command using wkhtmltopdf.exe
file
--header-left "MyTask" --header-right "[date] - [time]" --header-line --footer-right "Page[page] of[topage]" "-" "Sample.pdf"
output
This is a screenshot of the newly created Sample.pdf
file by wkhtmltopdf.
7. Add and Adjust Margins
Let's take the use case that we want to create a PDF file by URL, and set the margins. Both components provide the functions to set the margin from Left, Top, Right and Bottom.
7.1 Add and Adjust Margins using IronPDF
/**
Adjust Margins
anchor-add-and-adjust-margins-using-ironpdf
**/
using IronPdf;
{
//create rendering converter
var converter = new ChromePdfRenderer();
converter.RenderingOptions.MarginTop = 20;
converter.RenderingOptions.MarginLeft = 40;
//Specify URL
using var PDF = converter.RenderUrlAsPdf("https://en.wikipedia.org/wiki/PDF");
//Save the file
PDF.SaveAs("Sample.pdf");
Console.WriteLine("successfully created..!");
Console.ReadKey();
}
/**
Adjust Margins
anchor-add-and-adjust-margins-using-ironpdf
**/
using IronPdf;
{
//create rendering converter
var converter = new ChromePdfRenderer();
converter.RenderingOptions.MarginTop = 20;
converter.RenderingOptions.MarginLeft = 40;
//Specify URL
using var PDF = converter.RenderUrlAsPdf("https://en.wikipedia.org/wiki/PDF");
//Save the file
PDF.SaveAs("Sample.pdf");
Console.WriteLine("successfully created..!");
Console.ReadKey();
}
'''
'''Adjust Margins
'''anchor-add-and-adjust-margins-using-ironpdf
'''*
Private ReadOnly Property IronPdf() As using
'create rendering converter
Dim converter = New ChromePdfRenderer()
converter.RenderingOptions.MarginTop = 20
converter.RenderingOptions.MarginLeft = 40
'Specify URL
Dim PDF = converter.RenderUrlAsPdf("https://en.wikipedia.org/wiki/PDF")
'Save the file
PDF.SaveAs("Sample.pdf")
Console.WriteLine("successfully created..!")
Console.ReadKey()
End Property
Output:
Here is the screenshot of the Sample.pdf
file by IronPDF.
It is clear that above code created a PDF file from specified URL, and set margin-left 40 mm
and margin-top 20 mm
. Now, let's do the same using wkhtmltopdf.
7.2 Add and Adjust Margins using wkhtmltopdf
To work with wkhtmltopdf, we need to execute the separate process using wkhtmltopdf.exe
file. To avoid the complexity, we will define a new function and call it main()
function as follows
using System.Text;
using System.Diagnostics;
static void Main(string[] args)
{
ConvertChromePdfRenderer(20, 40, "https://en.wikipedia.org/wiki/PDF", "Sample.pdf");
Console.WriteLine("ok");
Console.ReadKey();
}
public static void ConvertChromePdfRenderer(int margin_top, int margin_left, string url, string filename)
{
StringBuilder paramsBuilder = new StringBuilder();
paramsBuilder.AppendFormat("--margin-top \"{0}\" --margin-left \"{1}\" \"{2}\" \"{3}\"", margin_top, margin_left, url, filename);
using (Process process = new Process())
{
process.StartInfo.FileName = "C:\\Program Files (x86)\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";
process.StartInfo.Arguments = paramsBuilder.ToString();
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.Start();
if (!process.WaitForExit(60000))
{
process.Kill();
}
}
}
using System.Text;
using System.Diagnostics;
static void Main(string[] args)
{
ConvertChromePdfRenderer(20, 40, "https://en.wikipedia.org/wiki/PDF", "Sample.pdf");
Console.WriteLine("ok");
Console.ReadKey();
}
public static void ConvertChromePdfRenderer(int margin_top, int margin_left, string url, string filename)
{
StringBuilder paramsBuilder = new StringBuilder();
paramsBuilder.AppendFormat("--margin-top \"{0}\" --margin-left \"{1}\" \"{2}\" \"{3}\"", margin_top, margin_left, url, filename);
using (Process process = new Process())
{
process.StartInfo.FileName = "C:\\Program Files (x86)\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";
process.StartInfo.Arguments = paramsBuilder.ToString();
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.Start();
if (!process.WaitForExit(60000))
{
process.Kill();
}
}
}
Imports System.Text
Imports System.Diagnostics
Shared Sub Main(ByVal args() As String)
ConvertChromePdfRenderer(20, 40, "https://en.wikipedia.org/wiki/PDF", "Sample.pdf")
Console.WriteLine("ok")
Console.ReadKey()
End Sub
Public Shared Sub ConvertChromePdfRenderer(ByVal margin_top As Integer, ByVal margin_left As Integer, ByVal url As String, ByVal filename As String)
Dim paramsBuilder As New StringBuilder()
paramsBuilder.AppendFormat("--margin-top ""{0}"" --margin-left ""{1}"" ""{2}"" ""{3}""", margin_top, margin_left, url, filename)
Using process As New Process()
process.StartInfo.FileName = "C:\Program Files (x86)\wkhtmltopdf\bin\wkhtmltopdf.exe"
process.StartInfo.Arguments = paramsBuilder.ToString()
process.StartInfo.UseShellExecute = False
process.StartInfo.RedirectStandardOutput = True
process.StartInfo.RedirectStandardError = True
process.Start()
If Not process.WaitForExit(60000) Then
process.Kill()
End If
End Using
End Sub
This code will execute the following command using wkhtmltopdf.exe
by using the process of: --margin-top "20" --margin-left "40" "https://en.wikipedia.org/wiki/PDF" "Sample.pdf"
Output:
Here is the Sample.pdf
file by wkhtmltopdf.
It creates the same PDF file as we create using IronPDF.
7.3. Conclusion
Performance of any project is very important, and unfortunately wkhtmltopdf affects the performance because it needs to execute a separate Process and Thread. On the other hand, if we use IronPDF, then there is no need to run separate Process and Thread executions.
Licensing and Pricing
8. Licensing and Pricing
Let's talk about licensing and pricing about both products.
8.1. IronPDF Licensing and Pricing
IronPDF is free for development and offers a free 30 day deployment trial. For full deployment use, licenses start from $749, with packages available for multiple developers, projects, and royalty-free redistribution products at IronPDF licensing.
IronPDF releases a new version almost every month, keeping up with the latest technology and bug fixes. The component is reliable and backed by a full-time engineering team at IronSoftware, offering high quality and performance to their customers.
8.2. wkhtmltopdf Licensing and Pricing
wkhtmltopdf is an open source component and free to use. Therefore, it does not provides any type of software updates, bug fixes, support, hot fixes, or company guarantee. If we use wkhtmltopdf in the project, then it is up to us to debug and manage its success on our own.
Summary
9. Final Comparison IronPDF to wkhtmltopdf
IronPDF | wkhtmltopdf |
---|---|
IronPDF becomes part of the project | wkhtmltopdf doesn't become part of the project |
No separate process required | Need to run separate process |
Automatically sets space for readability | No automatic space between header and page content |
Can enable or disable javascript | Can enable and disable javascript |
Can print on different paper sizes | Can print on different paper sizes |
Lots of documentation available | Little documentation available |
No need to specify separate file path | Need to specify the path of `wkhtmltopdf.exe` file |
`C#` library, need to add its reference in the project | CLI-based, executes commands using Process in .NET applications. I would not recommend for use in web or server applications. |
Provides generalized way to convert `.aspx` page to PDF file | Does not provide a generalized way to convert `.aspx` page to PDF |
Can add page breaks in PDF files easily | Page breaks may require research. |
Free for development, licenses provide version updates and engineer support | Open source, no known support |
Tutorial Quick Access
Explore the IronPDF API Reference
Explore the API Reference for IronPDF C# Library, including details of all of IronPDF’s features, classes, method fields, namespaces, and enums.
View the API Reference