Introduction
This tip shows you how to generate a web page to PDF. This is the easiest, simplest, fastest and of course, free way to generate PDF or images for web pages. The tool is named as “wkhtmltopdf
” and “wkhtmltoimage
”. Both are in EXE format. It is written in C++ and also its source is open and licensed under open source.
Because it is an EXE, we can use this tool in both Windows and web applications. And because it is in C++, it can be used for Windows platform as well as in Linux based systems.
I will be explaining how to use it in web applications to generate PDF and push that PDF to client.
The rest can be taken care of by considering this as an example.
You can download the EXE from here.
And trust me, this is a really cool kit as it provides a lot of flexibility to hide or extend the content of the page in nearly every manner.
Now as we know, we can invoke any EXE from a process object in C# or in VB.NET.
I am going to take an example of VB.NET because my current project is in VB.NET. Here is some code:
url of the page to be printed
Dim fileToPrintURL As String = "www.somesite.com/pagename"
Dim PDFSharedFolder As String = "e:\\"
Dim filename As String = "Page" + TimeOfDay.Ticks.ToString() + ".pdf"
Dim filenameWithSharedPAth As String = PDFSharedFolder + filename
Dim process As New Process
process.StartInfo.UseShellExecute = False
process.StartInfo.CreateNoWindow = True
process.StartInfo.FileName = Server.MapPath("~/bin/PrintPDF/") + "wkhtmltopdf.exe"
process.StartInfo.Arguments = "--username " + username + " --password " + _
password + " """ + fileToPrintURL + """ " + _
"""" + filenameWithSharedPAth + """"
process.StartInfo.RedirectStandardOutput = True
process.StartInfo.RedirectStandardError = True
process.Start()
process.WaitForExit()
Your file is now generated at the specified path with all the UI CSS stuff and images.
If you wish to hide some content on a web page on which you are having dev control, then pass this CSS to that page (Hint: I am not spoonfeeding).
@media print
{
#header { display:none;}
.bar-menu { display:none;}
}
And a lot of help is available here.