2013-08-27 250 views
5

Tôi có ứng dụng ASP.NET MVC4 mà tôi muốn xuất trang html sang tệp PDF, tôi sử dụng mã này và hoạt động tốt: codeXuất tệp PDF với ASP.NET MVC

Mã này chuyển đổi một trang html thành PDF trực tuyến, tôi muốn tải xuống trực tiếp tệp.

Tôi làm cách nào để thay đổi mã này để có được kết quả này?

+2

Xin vui lòng gửi mã có liên quan. Bạn không nên mong đợi mọi người đến đó và đọc toàn bộ bài báo. –

Trả lời

5

Với 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"); 
} 
3

Làm cho nó như một tập tin đính kèm và cung cấp cho nó một tên tập tin khi trả lại kết quả:

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

Điều gì làm cho các tập tin xuất hiện như tập tin đính kèm và bật lên hộp thoại Save As là dòng sau:

return File(buffer, "application/pdf", "myfile.pdf"); 
1

Sử dụng:

Điều này dành cho VB.NET (C# bên dưới)

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

Trong phương pháp hành động của bạn. Trong đó PDFFIle là tên tệp của bạn.

Đối với C#

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