maciejka
maciejka

Reputation: 948

Save PDF file in Downloads folder in ASP .NET MVC

In my method in controller I use the following code to save pdf.

HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(htmlContent);
            HtmlNode node = doc.GetElementbyId("DetailsToPDF");
            HtmlToPdfConverter htmlToPdf = new HtmlToPdfConverter();
            var pdfBytes = htmlToPdf.GeneratePdf("<html><body>" + node.InnerHtml + "</body></html>");

            Response.ContentType = "application/pdf";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.AddHeader("Content-Disposition", "attachment; filename=TEST.pdf");
            Response.BinaryWrite(pdfBytes);
            Response.Flush();
            Response.End();

Everything has passed without any exceptions in debugger. However file is not saved. What am I doing wrong?

Upvotes: 1

Views: 5879

Answers (2)

thmshd
thmshd

Reputation: 5847

The recommended way to return a File in ASP.NET MVC is using the File() helper method:

public ActionResult Download()
{
  // Starting with pdfBytes here...
  // ...
  var pdfBytes = htmlToPdf.GeneratePdf("<html><body>" + node.InnerHtml + "</body></html>");
  var contentDisposition = new System.Net.Mime.ContentDisposition
  {
      FileName = "TEST.pdf",
      Inline = false
  };
  Response.AppendHeader("Content-Disposition", contentDisposition.ToString());
  return File(pdfBytes, "application/pdf");
}

Upvotes: 2

Anil Jambukiya
Anil Jambukiya

Reputation: 1

string path = Server.MapPath("~/Content/files/newPDFFile.pdf");
    WebClient client = new WebClient();
    Byte[] buffer = client.DownloadData(path);
    if (buffer != null)
    {

        Response.Clear();
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=" + "PDFfile.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.BinaryWrite(buffer);
        Response.End();
    }

Upvotes: 0

Related Questions