2013-08-27 95 views
5

我有,我想一個HTML頁面導出爲PDF文件的ASP.NET應用程序MVC4,我用這個代碼,它的正常工作:code導出PDF文件與ASP.NET MVC

該代碼將html頁面轉換爲在線PDF,我想直接下載該文件。

如何更改此代碼以獲得此結果?

+2

請張貼相關的代碼。你不應該指望人們去那裏閱讀整篇文章。 –

回答

5

隨着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

讓它作爲附件,並給它一個文件名返回結果時:

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

是什麼使文件顯示爲附件和彈出另存爲對話框是以下行:

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

使用:

這是VB.NET(下面C#)

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

在您的操作方法。其中PDFFIle是您的文件名。

對於C#

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