Convert HTML to PDF in ASP.NET MVC

Rameshwar Trivedi picture Rameshwar Trivedi · Feb 1, 2014 · Viewed 50.4k times · Source

Im working in a project which requires current html page to convert in pdf and that pdf will automatically save on button click on server and its reference will be save in database.I can convert the view if its data comes from data base but the data in this form is static that means on the view it has so many radio button and text box in which i can write the detail and check the check box on after clicking save button it will save on the server and and its reference will save in the data base.

the reason is that im not saving the data in database is that the report is less use full for the client but if i save the data in data base then the database become very huge and its become complicate to handle. because the report has approx 100 fields. so please if any one can help me in it.

Answer

Tom picture Tom · Nov 16, 2016

You can use the Free Html To Pdf Converter from SelectPdf (http://selectpdf.com/community-edition/).

Code for MVC looks like this:

[HttpPost]
public ActionResult Convert(FormCollection collection)
{
    // read parameters from the webpage
    string url = collection["TxtUrl"];

    string pdf_page_size = collection["DdlPageSize"];
    PdfPageSize pageSize = (PdfPageSize)Enum.Parse(typeof(PdfPageSize), pdf_page_size, true);

    string pdf_orientation = collection["DdlPageOrientation"];
    PdfPageOrientation pdfOrientation = (PdfPageOrientation)Enum.Parse(
        typeof(PdfPageOrientation), pdf_orientation, true);

    int webPageWidth = 1024;
    try
    {
        webPageWidth = System.Convert.ToInt32(collection["TxtWidth"]);
    }
    catch { }

    int webPageHeight = 0;
    try
    {
        webPageHeight = System.Convert.ToInt32(collection["TxtHeight"]);
    }
    catch { }

    // instantiate a html to pdf converter object
    HtmlToPdf converter = new HtmlToPdf();

    // set converter options
    converter.Options.PdfPageSize = pageSize;
    converter.Options.PdfPageOrientation = pdfOrientation;
    converter.Options.WebPageWidth = webPageWidth;
    converter.Options.WebPageHeight = webPageHeight;

    // create a new pdf document converting an url
    PdfDocument doc = converter.ConvertUrl(url);

    // save pdf document
    byte[] pdf = doc.Save();

    // close pdf document
    doc.Close();

    // return resulted pdf document
    FileResult fileResult = new FileContentResult(pdf, "application/pdf");
    fileResult.FileDownloadName = "Document.pdf";
    return fileResult;
}

VB.NET MVC version of the code can be found here: http://selectpdf.com/convert-from-html-to-pdf-in-asp-net-mvc-csharp-and-vb-net/