Wednesday, 29 July 2015

Exporting HTML to PDF in ASP.NET MVC C#

In this tutorial we are going to set up dev environment to use html to pdf converter and convert previously saved wikipedia page to pdf.

1. Download and install application from http://wkhtmltopdf.org/ - FREE to use
2. Create new Asp.NET MVC application.
3. Add location to exe file in your web config file(this is installation path for previously installed wkhtmltopdf) - something like that :

 <add key="HtmlToPdfPath" value="C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe"/>


4. Download  https://en.wikipedia.org/wiki/CERN page and save it in My documents folder under PdfExample folder.



5. Create new api controller and call it HtmlPdf.
6. Alter Get(int value) web api method :

public string Get(string name)
        {
            string path = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "PdfExample");

            if (File.Exists(string.Format("{0}\\{1}", path, name)))
            {
                try
                {
                    string nameWithoutExtension = name.Replace(".html", string.Empty);
                    var psi = new ProcessStartInfo(System.Configuration.ConfigurationManager.AppSettings["HtmlToPdfPath"], string.Format("{0} {1}.pdf", name, nameWithoutExtension));
                    psi.WorkingDirectory = path + "/";

                    var proc = Process.Start(psi);
                    proc.WaitForExit();

                    return "completed";
                }
                catch (Exception ex)
                {
                    return ex.InnerException.ToString();
                }
                
            }
            else
            {
                return "Failed to convert";
            }


        }
}

7. Run your application and open url:

http://localhost:yourport/api/htmlpdf?name=CERN.html

8. In your folder PdfExample you can see pdf version of Cern wikipedia html website.