i




 
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#
Hi,
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
Code:
http://code.google.com/p/wkhtmltopdf/

How program works?
first of all to run this utility, we need to run the following command
Code:
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
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);
        }

//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;
        }

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:\\");
        }

the below function execute the batch file.
Code:
public void Execute_Batch_File()
        {
            Process p = null;
            try
            {
                string targetDir;
                targetDir = string.Format(GetFilePath());
                p = new Process();
                p.StartInfo.WorkingDirectory = targetDir;
                p.StartInfo.FileName = "execute.bat";
                p.StartInfo.CreateNoWindow = false;
                p.Start();
                p.WaitForExit();
            }
            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: 429)

[Image: 2604595733.png]
Quote
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!
Quote
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:

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

and

change
Code:
System.Diagnostics.Process.Start("c:\\");
to
Code:
System.Diagnostics.Process.Start("d:\\");

hope this will fix your issue.

[Image: 2604595733.png]
Quote
01-28-2013, 04:21 PM
Post: #4
RE: Html to pdf conversion in c#
hi how to use convert into own application
Quote
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]
Quote
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
Quote
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'.
Quote
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

Quote
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...
Quote
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:

http://www.aspose.com/.net/pdf-component.aspx

I hope it will help you.
Quote
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-
Quote
05-15-2014, 07:10 AM
Post: #12
RE: Html to pdf conversion in c#
hi all.

Here is my solution on this issue:
Code:
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.
doc.SaveToFile("sample.pdf");
doc.Close();
//Launching the Pdf file.
System.Diagnostics.Process.Start("sample.pdf");
}
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.

chris
Quote


Possibly Related Threads...
Thread: Author Replies Views: Last Post
  PDF to Image Conversion in ASP.NET magnum_2007 7 3,506 07-25-2014 09:13 AM
Last Post: alxe_2014
  Html to Pdf conversion in asp.net c# nisar87 7 38,391 06-17-2014 06:31 AM
Last Post: dev_chirs
  pdf to html conversion in asp.net c# nisar87 6 3,350 12-16-2013 07:16 AM
Last Post: felin
  pdf to image conversion in asp.net c# nisar87 8 20,188 11-25-2013 09:37 AM
Last Post: felin
  Weburl to PDF conversion in asp.net nisar87 21 7,400 07-05-2013 12:42 PM
Last Post: argha_cl



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