C# 使用 ASP.NET MVC 导出 PDF 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18470277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:18:16  来源:igfitidea点击:

Exporting a PDF-file with ASP.NET MVC

c#.netasp.net-mvcrazor

提问by Lamloumi Afif

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?

如何更改此代码以获得此结果?

采纳答案by fmgp

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

回答by Darin Dimitrov

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

回答by BenM

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