Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert HTML to PDF in MVC with iTextSharp in MVC Razor

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?

like image 655
Ravi Avatar asked May 13 '13 07:05

Ravi


3 Answers

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.

like image 51
hutchonoid Avatar answered Oct 20 '22 22:10

hutchonoid


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

like image 4
Rosdi Kasim Avatar answered Oct 20 '22 22:10

Rosdi Kasim


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

like image 4
Vinit Patel Avatar answered Oct 20 '22 22:10

Vinit Patel