简体   繁体   English

使用ASP.NET MVC导出PDF文件

[英]Exporting a PDF-file with ASP.NET MVC

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 我有一个ASP.NET MVC4应用程序,我想在其中导出一个HTML页面到PDF文件,我使用这个代码,它的工作正常: 代码

This code converts a html page to online PDF, I'd like to download directly the file. 此代码将html页面转换为在线PDF,我想直接下载该文件。

How can I change this code to obtain this result? 如何更改此代码以获得此结果?

With a FileContentResult: 使用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");
}

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

Use: 采用:

This is for VB.NET (C# below) 这是针对VB.NET(下面的C#)

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

In your action method. 在你的行动方法。 Where PDFFIle is your file name. PDFFIle是您的文件名。

For C# 对于C#

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM