Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting a PDF-file with ASP.NET MVC

I have an ASP.NET MVC4 application in which I'd like to export a html page to PDF-file, I use this code and it's works fine: code

This code converts a html page to online PDF, I'd like to download directly the file.

How can I change this code to obtain this result?

like image 520
Lamloumi Afif Avatar asked Aug 27 '13 15:08

Lamloumi Afif


2 Answers

Make it as an attachment and give it a filename when returning the result:

protected ActionResult ViewPdf(string pageTitle, string viewName, object model)
{
    // Render the view html to a string.
    string htmlText = this.htmlViewRenderer.RenderViewToString(this, viewName, model);

    // Let the html be rendered into a PDF document through iTextSharp.
    byte[] buffer = standardPdfRenderer.Render(htmlText, pageTitle);

    // Return the PDF as a binary stream to the client.
    return File(buffer, "application/pdf", "myfile.pdf");
}

What makes the file appear as attachment and popup the Save As dialog is the following line:

return File(buffer, "application/pdf", "myfile.pdf");
like image 30
Darin Dimitrov Avatar answered Sep 22 '22 10:09

Darin Dimitrov


With a FileContentResult:

protected FileContentResult ViewPdf(string pageTitle, string viewName, object model)
{
    // Render the view html to a string.
    string htmlText = this.htmlViewRenderer.RenderViewToString(this, viewName, model);

    // Let the html be rendered into a PDF document through iTextSharp.
    byte[] buffer = standardPdfRenderer.Render(htmlText, pageTitle);

    // Return the PDF as a binary stream to the client.
    return File(buffer, "application/pdf","file.pdf");
}
like image 198
fmgp Avatar answered Sep 20 '22 10:09

fmgp