Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / CSS

Web Page to PDF or Image

5.00/5 (2 votes)
7 Sep 2013CPOL1 min read 14.2K  
How to convert a web page to PDF or image

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:

VB.NET
url of the page to be printed
Dim fileToPrintURL As String = "www.somesite.com/pagename"
Dim PDFSharedFolder As String = "e:\\"

'this will be the name of the file ".pdf" generated one
Dim filename As String = "Page" + TimeOfDay.Ticks.ToString() + ".pdf"

'shared folder with write permissions and file name to be generated at which place
Dim filenameWithSharedPAth As String = PDFSharedFolder + filename

'create an object of process 
Dim process As New Process

'set some initials
process.StartInfo.UseShellExecute = False
process.StartInfo.CreateNoWindow = True

'now the path of the exe downloaded from the link above
process.StartInfo.FileName = Server.MapPath("~/bin/PrintPDF/") + "wkhtmltopdf.exe"

'and some arguments (based on req) as I need to pass it 
'from authentication so user name and password

process.StartInfo.Arguments = "--username " + username + " --password " + _
password + " """ + fileToPrintURL + """ " + _
"""" + filenameWithSharedPAth + """"

'again some setting
process.StartInfo.RedirectStandardOutput = True
process.StartInfo.RedirectStandardError = True

'start the process
process.Start()

'end the process
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).

CSS
@media print
{
    #header { display:none;}
    .bar-menu { display:none;}
}

And a lot of help is available here.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)