Html to pdf conversion in c#

added by nisar87
11/14/2012 6:15:08 AM

0 Kicks, 113 Views

Hi, I have developed a small program that convert any webpage into pdf including all css and images. I used free utility [b]wkhtmltopdf[/b] for conversion, you can read more about this utility from their official website [code][/code] How program works? first of all to run this utility, we need to run the following command [code] wkhtmltopdf dotnetobject.pdf [/code] 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 [code] 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"); return; } Modify_And_Execute_Batch_File(txt_url.Text); } [/code] //this function get the correct path where wkhtmltopdf exe is exist inside the project. [code] private string GetFilePath() { string[] DirPath = Application.StartupPath.Split(new string[] { "\\bin" }, StringSplitOptions.None); string str_Path = Path.Combine(DirPath[0], "wkhtmltopdf"); return str_Path; } [/code] the below function modify the batch file based on new url, and after successfully creation, it execute the batch file to generate pdf. [code] 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); SW.Write(str_Command); SW.Close(); //execute batch file after creation Execute_Batch_File(); //this will open the pdf folder System.Diagnostics.Process.Start("c:\\"); }