6

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?

1
  • 2
    Please post the relevant code. You should not expect people to go there and read the whole entire article. Commented Aug 27, 2013 at 15:58

3 Answers 3

6

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");
}
Sign up to request clarification or add additional context in comments.

Comments

3

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");

Comments

1

Use:

This is for VB.NET (C# below)

    Public Function PDF() As FileResult
        Return File("../PDFFile.pdf", "application/pdf")
    End Function

In your action method. Where PDFFIle is your file name.

For C#

Public FileResult PDF(){
    return File("../PDFFile.pdf", "application/pdf");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.