Thread Rating:
  • 1 Votes - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Html to pdf conversion in c#
04-29-2012, 05:47 PM
Post: #1
Html to pdf conversion in c#
I have developed a small program that convert any webpage into pdf including all css and images.

I used free utility wkhtmltopdf for conversion, you can read more about this utility from their official website

How program works?
first of all to run this utility, we need to run the following command
wkhtmltopdf http://dotnetobject.com dotnetobject.pdf

This will convert the dotnetobject page complete layout into pdf file.

to run this command, i firstly created a batch file dynamically, and after creation, i executed that batch file to generate a pdf file.

//the below click event first verify the url validity. and then execute the the function which generate pdf file
private void btn_Convert_Click(object sender, EventArgs e)
            Uri uri = null;
            if (!Uri.TryCreate(txt_url.Text, UriKind.Absolute, out uri) || null == uri)
                //Invalid URL
                MessageBox.Show("Enter a valid URL");


//this function get the correct path where wkhtmltopdf exe is exist inside the project.
private string GetFilePath()
            string[] DirPath = Application.StartupPath.Split(new string[] { "\\bin" }, StringSplitOptions.None);
            string str_Path = Path.Combine(DirPath[0], "wkhtmltopdf");
            return str_Path;

the below function modify the batch file based on new url, and after successfully creation, it execute the batch file to generate pdf.
private void Modify_And_Execute_Batch_File(string WebUrl)
            StreamWriter SW = null;
            if (File.Exists(GetFilePath() + "\\execute.bat"))
                File.Delete(GetFilePath() + "\\execute.bat");
            SW = File.CreateText(GetFilePath() + "\\execute.bat");
            string str_Command = "wkhtmltopdf " + WebUrl + " c:\\" + WebUrl.Replace("http://", "") + ".pdf";

            System.IO.File.WriteAllText("execute.bat", str_Command);

            //execute batch file after creation

            //this will open the pdf folder

the below function execute the batch file.
public void Execute_Batch_File()
            Process p = null;
                string targetDir;
                targetDir = string.Format(GetFilePath());
                p = new Process();
                p.StartInfo.WorkingDirectory = targetDir;
                p.StartInfo.FileName = "execute.bat";
                p.StartInfo.CreateNoWindow = false;
            catch (Exception ex)
                Console.WriteLine("Exception Occurred :{0},{1}",
                            ex.Message, ex.StackTrace.ToString());
this program saves the pdf file in c:\\ directory.
you can get complete working code from the attachment, if you have any question, please feel free to ask.

Attached File(s)
.rar  HtmltoPdf.rar (Size: 8.66 MB / Downloads: 649)

[Image: 2604595733.png]
10-23-2012, 06:08 PM
Post: #2
RE: Html to pdf conversion in c#
When i try to run your code i just get the following error in the .bat-file: QPainter::begin(): Returned false===============================] 100%
Error: Unable to write to destination
Any help would be greeeeeaaaat!
10-24-2012, 06:58 AM
Post: #3
RE: Html to pdf conversion in c#
Actually i have checked again, there is no issue at my end. You may have issue with your C: drive as it has not allowing you to create the file may be because of some restriction.
I recommend you to change the path from Drive C: to Drive D:

string str_Command = "wkhtmltopdf " + WebUrl + " c:\\" + WebUrl.Replace("http://", "") + ".pdf";
string str_Command = "wkhtmltopdf " + WebUrl + " d:\\" + WebUrl.Replace("http://", "") + ".pdf";



hope this will fix your issue.

[Image: 2604595733.png]
01-28-2013, 04:21 PM
Post: #4
RE: Html to pdf conversion in c#
hi how to use convert into own application
01-28-2013, 07:28 PM
Post: #5
RE: Html to pdf conversion in c#
Hello Sahil!
can you explain what exactly you want? code is already attached. you can download and use it in your project.

[Image: 2604595733.png]
03-20-2013, 08:25 AM (This post was last modified: 03-20-2013 09:43 AM by shibz.)
Post: #6
RE: Html to pdf conversion in c#
I cannot find the file where it is located..i mean where is the batch file present..and how to provide multiple urls
03-20-2013, 10:54 AM
Post: #7
RE: Html to pdf conversion in c#
i get an error at System.IO.File.WriteAllText("execute.bat", str_Command);
saying that Could not find a part of the path 'C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\wkhtmltopdf\execute.bat'.
03-26-2013, 11:11 AM
Post: #8
RE: Html to pdf conversion in c#
The problem is that you are mapping the path inside some other application. Therefore, framework is mapping the path of that application domain instead of what you want. Tell me the exact scenario in which you are using the application?

View Asad Ali's profile on LinkedIn

07-08-2013, 11:39 AM
Post: #9
RE: Html to pdf conversion in c#
Hello, I want to hide a portion via java script of the web page prior generating the pdf of that web page itself.... but that hidden element is showing in pdf... please help...
12-16-2013, 07:14 AM
Post: #10
RE: Html to pdf conversion in c#
You can convert html to pdf in c#/.net with Aspose.PDF for .NET Library:


I hope it will help you.
02-06-2014, 08:56 AM
Post: #11
RE: Html to pdf conversion in c#
Thank you so much, it's verry helpful

-From VietNam-
05-15-2014, 07:10 AM
Post: #12
RE: Html to pdf conversion in c#
hi all.

Here is my solution on this issue:
static void Main(string[] args)
//Create a pdf document.
PdfDocument doc = new PdfDocument();
String url = "http://www.london2012.com/news/articles/paralympic-torch-relay-route-revealed-1258473.html";
doc.LoadFromHTML(url, false, true, true);
//Save pdf file.
//Launching the Pdf file.
Anyway ,this scenario is based on a free PDF component which supports to convert the HTML page with rich elements, such as HTTPS, CSS3, HTML5, JavaScript to PDF format.Hope it can do a bit fover.

03-25-2015, 06:25 AM
Post: #13
RE: Html to pdf conversion in c#
i had tried to create pdf by this code but pdf not created please help
09-06-2016, 10:30 AM (This post was last modified: 09-06-2016 10:41 AM by evopdf.)
Post: #14
RE: Html to pdf conversion in c#
You might also consider the EVO HTML to PDF library for .NET. Here is a complete code sample for ASP.NET using this library:

protected void convertToPdfButton_Click(object sender, EventArgs e)
    // Create a HTML to PDF converter object with default settings
    HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();

    // Set HTML Viewer width in pixels which is the equivalent in converter of the browser window width
    htmlToPdfConverter.HtmlViewerWidth = int.Parse(htmlViewerWidthTextBox.Text);

    // Set HTML viewer height in pixels to convert the top part of a HTML page
    // Leave it not set to convert the entire HTML
    if (htmlViewerHeightTextBox.Text.Length > 0)
        htmlToPdfConverter.HtmlViewerHeight = int.Parse(htmlViewerHeightTextBox.Text);

    // Set PDF page size which can be a predefined size like A4 or a custom size in points
    // Leave it not set to have a default A4 PDF page
    htmlToPdfConverter.PdfDocumentOptions.PdfPageSize = SelectedPdfPageSize();

    // Set PDF page orientation to Portrait or Landscape
    // Leave it not set to have a default Portrait orientation for PDF page
    htmlToPdfConverter.PdfDocumentOptions.PdfPageOrientation = SelectedPdfPageOrientation();

    // Set the maximum time in seconds to wait for HTML page to be loaded
    // Leave it not set for a default 60 seconds maximum wait time
    htmlToPdfConverter.NavigationTimeout = int.Parse(navigationTimeoutTextBox.Text);

    // Set an adddional delay in seconds to wait for JavaScript or AJAX calls after page load completed
    // Set this property to 0 if you don't need to wait for such asynchcronous operations to finish
    if (conversionDelayTextBox.Text.Length > 0)
        htmlToPdfConverter.ConversionDelay = int.Parse(conversionDelayTextBox.Text);

    // The buffer to receive the generated PDF document
    byte[] outPdfBuffer = null;

    if (convertUrlRadioButton.Checked)
        string url = urlTextBox.Text;

        // Convert the HTML page given by an URL to a PDF document in a memory buffer
        outPdfBuffer = htmlToPdfConverter.ConvertUrl(url);
        string htmlString = htmlStringTextBox.Text;
        string baseUrl = baseUrlTextBox.Text;

        // Convert a HTML string with a base URL to a PDF document in a memory buffer
        outPdfBuffer = htmlToPdfConverter.ConvertHtml(htmlString, baseUrl);

    // Send the PDF as response to browser

    // Set response content type
    Response.AddHeader("Content-Type", "application/pdf");

    // Instruct the browser to open the PDF file as an attachment or inline
    Response.AddHeader("Content-Disposition", String.Format("{0}; filename=Getting_Started.pdf; size={1}",
        openInlineCheckBox.Checked ? "inline" : "attachment", outPdfBuffer.Length.ToString()));

    // Write the PDF document buffer to HTTP response

    // End the HTTP response and stop the current page processing

To see how accurate the conversion can be with this library and for more code samples see the EVO HTML to PDF library for .NET Online Demo

Possibly Related Threads...
Thread: Author Replies Views: Last Post
  pdf to html conversion in asp.net c# nisar87 9 9,410 04-12-2016 12:21 PM
Last Post: BenJobs
  pdf to image conversion in asp.net c# nisar87 10 32,591 11-10-2015 02:01 AM
Last Post: dasccca
  Html to Xhtml conversion in c# nisar87 1 5,712 05-17-2015 11:38 PM
Last Post: raju
  PDF to Image Conversion in ASP.NET magnum_2007 7 11,062 07-25-2014 09:13 AM
Last Post: alxe_2014
  Html to Pdf conversion in asp.net c# nisar87 7 56,829 06-17-2014 06:31 AM
Last Post: dev_chirs

User(s) browsing this thread: 1 Guest(s)