2017-09-24 146 views
0

在我的方法在控制器中我使用下面的代碼來保存pdf。保存PDF文件在ASP中的下載文件夾中MVC

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

在調試器中沒有任何異常情況下,所有內容都已通過。但是文件沒有保存。我究竟做錯了什麼?

+0

這實際上不保存文件。它只會要求您的瀏覽器處理該文件。根據瀏覽器的配置方式,它可能會保存它,它可能會顯示它 –

+0

瀏覽器(Chrome)沒有顯示任何內容。我應該在哪裏配置它? – maciejka

+0

實際上你正在使用'BinaryWrite'將文件內容寫入HTTP響應,它不會返回任何要下載的文件。嘗試返回'FileResult' /'FileContentResult',它顯示選項以在瀏覽器中打開或下載文件。 –

回答

1

推薦的方式返回ASP.NET MVC文件使用File() helper方法:

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"); 
} 
+0

在這個解決方案中,我可以在UTF.8上設置編碼嗎? – maciejka

+0

有什麼特別的理由嗎? PDF文件具有自己的編碼,文件結果僅返回字節。如果你得到一些格式不正確的字符,這個問題可能在PDF生成過程本身的某個地方。但是你仍然可以嘗試調用'Response.ContentEncoding = System.Text.Encoding.UTF8;'或'Response.Charset =「utf-8」;'看看它是否有幫助 – thmshd

+0

原因:波蘭語字母:) – maciejka

0
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(); 
    } 
相關問題