Convert HTML to PDF in MVC with iTextSharp in MVC Razor

77,900

Solution 1

There's a detailed and step-by-step tutorial on CodeProject you might follow. It illustrates how you could serve an ASP.NET MVC View as PDF file using iTextSharp for the conversion. Bear in mind though that iTextSharp was not meant for converting HTML to PDF so it might not cope very well with complex HTML pages and CSS styles.

Solution 2

Here is how you implement this solution using the Razor engine NOT with the weird <itext.. markup.

This way you have full control over the pdf presentation using standard html output.

The project with an example solution and source code is available here with nuget installation instructions:

https://github.com/andyhutch77/MvcRazorToPdf

Install-Package MvcRazorToPdf

This also uses the new itextsharp licence, so does not suffer from any of the negatives mentioned in the other answers.

Solution 3

You should check out RazorPDF which is using iText to generate the PDF, but in a friendlier way.

Solution 4

public virtual void printpdf(string html)    
{
     String htmlText = html.ToString();
     Document document = new Document();
     string filePath = HostingEnvironment.MapPath("~/Content/Pdf/");
     PdfWriter.GetInstance(document, new FileStream(filePath + "\\pdf-"+Filename+".pdf", FileMode.Create));

     document.Open();    
     iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document);       
     hw.Parse(new StringReader(htmlText));    
     document.Close();    
}

just pass html string in to parameter that string you will get by renderpartialview text = viewname....

Solution 5

Here is a complete example for MVC Razor in C# using the evo html to pdf for .net to convert the current MVC view to PDF and send the resulted PDF to browser for download:

[HttpPost]
public ActionResult ConvertCurrentPageToPdf(FormCollection collection)
{
    object model = null;
    ViewDataDictionary viewData = new ViewDataDictionary(model);

    // The string writer where to render the HTML code of the view
    StringWriter stringWriter = new StringWriter();

    // Render the Index view in a HTML string
    ViewEngineResult viewResult = ViewEngines.Engines.FindView(ControllerContext, "Index", null);
    ViewContext viewContext = new ViewContext(
            ControllerContext,
            viewResult.View,
            viewData,
            new TempDataDictionary(),
            stringWriter
            );
    viewResult.View.Render(viewContext, stringWriter);

    // Get the view HTML string
    string htmlToConvert = stringWriter.ToString();

    // Get the base URL
    String currentPageUrl = this.ControllerContext.HttpContext.Request.Url.AbsoluteUri;
    String baseUrl = currentPageUrl.Substring(0, currentPageUrl.Length - "Convert_Current_Page/ConvertCurrentPageToPdf".Length);

    // Create a HTML to PDF converter object with default settings
    HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();

    // Convert the HTML string to a PDF document in a memory buffer
    byte[] outPdfBuffer = htmlToPdfConverter.ConvertHtml(htmlToConvert, baseUrl);

    // Send the PDF file to browser
    FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf");
    fileResult.FileDownloadName = "Convert_Current_Page.pdf";

    return fileResult;
}
Share:
77,900

Related videos on Youtube

Ravi
Author by

Ravi

Updated on July 09, 2022

Comments

  • Ravi
    Ravi almost 2 years

    I am trying to convert HTML to PDF with iTextSharp in MVC Razor, but everything I have tried has not worked. Does anyone know how to accomplish this?

  • real_yggdrasil
    real_yggdrasil over 10 years
    Hi Rosdi Kasim. Appearantly the latest iTextSharp version (5.4.4) is not working properly with RazorPDF and has rendered it useless.
  • Rosdi Kasim
    Rosdi Kasim over 10 years
    @real_yggdrasil Be careful.. latest iTextSharp (starting from 5.x) has different license. Also 'rendered useless' is not helpful.. try submit your question with some example or detailed description..
  • Dhwani
    Dhwani over 10 years
    I want to know that if iTextSharp was not meant for converting HTML to PDF, which one with free source?
  • Sinaesthetic
    Sinaesthetic about 10 years
    I disagree. It has been rendered useless in that it does nothing and has not been updated since 2012.
  • Edgar Froes
    Edgar Froes about 10 years
    Man, you rock, thanks. Can i change the page orientation somehow?
  • hutchonoid
    hutchonoid about 10 years
    @EdgarSalazar No problem. As it uses the iTextXmlWorker underneath, I think you should be able to resolve this by styling a div to your landscape proportions.
  • hutchonoid
    hutchonoid over 9 years
    @sports yes, table example here: github.com/andyhutch77/MvcRazorToPdf/blob/master/…
  • Nic
    Nic almost 9 years
    IF TODAY DATE >14.07.2015 DO NOT LOOK TO THIS ANSWER!
  • klm_
    klm_ over 8 years
    this dll does not support culture specific characters
  • Ariel Moraes
    Ariel Moraes over 8 years
    @MDDDC why not? Where should I look then?
  • Amedee Van Gasse
    Amedee Van Gasse about 8 years
    Your answer uses HTMLWorker, which is deprecated. You should use XMLWorker.
  • Vivek Shukla
    Vivek Shukla about 8 years
    it giving error XMLWorker does not exist in current Context
  • Amedee Van Gasse
    Amedee Van Gasse about 8 years
    Which version of iTextSharp are you using? Can you reproduce it in iTextSharp 5.5.9?
  • Mehmet Taha Meral
    Mehmet Taha Meral over 7 years
    This step by step tutorial is not "Razor". It is aspx, web forms... It is not up to date.
  • Vivek Shukla
    Vivek Shukla almost 6 years
    Yes its iTextSharp 5.5.9
  • Amedee Van Gasse
    Amedee Van Gasse almost 6 years
    Can you reproduce it in iText 7.1.2 + pdfHTML?
  • mahdi moghimi
    mahdi moghimi almost 6 years
    I worked with Rotativa , it works based on popup and need to unblock popup blocker. Moreover after use ViewAsPdf or ActionAsPdf all Sessions will be cleared.