Danielle
Danielle

Reputation: 139

Converting HTML to PDF in ASP .NET MVC

I'm trying to convert html to pdf but it is giving error:

Failed to load PDF document. 

I'm trying to generate a simple pdf without using any .dll. Is there any way to generate a PDF without using iTextSharp for example, rotating w7?

Code:

    public ActionResult EventoVisualizarPDF()
    {
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri(ConfigurationManager.AppSettings["UrlAPI"]);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var id = Session["intCodigoGrupoUsuario"];
        var intUsuarioId = Session["intUsuarioId"];
        string url = "";

        url = "api/usuario/GetBuscaUsuario/" + intUsuarioId;

        HttpResponseMessage resposta = client.GetAsync(url).Result;
        var usuario = resposta.Content.ReadAsAsync<Usuario>().Result;

        url = "api/evento/GetEventoByUsuario/" + id;

        HttpResponseMessage response = client.GetAsync(url).Result;

        if (response.IsSuccessStatusCode)
        {
            var eventos = response.Content.ReadAsAsync<IEnumerable<Evento>>().Result;

            string htmlText = this.RenderRazorViewToString("RelatorioEventoPDF", eventos);
            byte[] buffer = System.Text.Encoding.Default.GetBytes(htmlText);
            return File(buffer, "application/pdf");
        }
        else
        {
            string msg = response.IsSuccessStatusCode.ToString();
            throw new Exception(msg);
        }
    }

    public string RenderRazorViewToString(string viewName, object model)
    {
        ViewData.Model = model;
        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
            var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);
            viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
            return sw.GetStringBuilder().ToString();
        }
    }

Upvotes: 0

Views: 2895

Answers (2)

Vinit Patel
Vinit Patel

Reputation: 2464

i Think You have to use itextsharp and here is simple code for generate pdf from html code...

public virtual void print pdf(string html, int id) --> IN String html just pass html page in string fromate and id is just a number for name in pdf. {

String htmlText = html.ToString();

Document document = new Document();

string filePath = HostingEnvironment.MapPath("~/Content/Pdf/");

PdfWriter.GetInstance(document, new FileStream(filePath + "\\pdf-"+id+".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();

}

Upvotes: 1

Pablo Romeo
Pablo Romeo

Reputation: 11396

Unfortunately no, there is no support for PDFs within the .Net framework.

So you will have to use some third party component, such as iTextSharp or PdfSharp. There are quite a few options out there, both open source and commercial.

Now, take into account that many of those components have support for generating pdf from html content directly, so if you render a simplified MVC razor view to a string (just as you are doing) you can easily convert that to a pdf.

Upvotes: 1

Related Questions