【问题标题】:How can I create and display a PDF file for a .net core MVC web application?如何为 .net core MVC Web 应用程序创建和显示 PDF 文件?
【发布时间】:2023-03-04 13:29:01
【问题描述】:

我有一个能够创建和显示 PDF 文件的 asp 应用程序。我需要为 .net 核心应用程序复制相同的功能。我对 .net core MVC 不太熟悉,所以不知道如何实现。

DisplayPDF.aspx.cs

public partial class DisplayPDF : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // get application id from query string
        string strFile = Request.QueryString["File"];

        if (!string.IsNullOrEmpty(strFile))
        {
            string fileToOpen = string.Empty;

            // get file path to requested application id's pdf file
            string filePath = System.IO.Path.GetDirectoryName(Request.PhysicalApplicationPath) +
                "\\Sessions\\" + Session.SessionID + "\\" + strFile;

            fileToOpen = "sessions/" + Session.SessionID + "/" + strFile;
            if (!System.IO.File.Exists(filePath))
            {
                LabelError.Visible = true;
                LabelError.Text = "The pdf was not generated.  Try the action again.  If the problem persists contact website support.";
            }

            Response.Redirect(fileToOpen);
        }
        else
        {
            // need to have query string parameter
            throw new ApplicationException("Query string parameter is missing");
        }

    }
}

DisplayPDF.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DisplayPDF.aspx.cs" Inherits="Test.WS.App.DisplayPDF" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Display PDF</title>
    <meta name="robots" content="noindex,nofollow" />
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="LabelError" runat="server" Visible="false"></asp:Label>
    </div>
    </form>
</body>
</html>

重定向到 DisplayPDF 页面

if(System.IO.File.Exists(filePath)){
    ScriptManager.RegisterClientScriptBlock(
        Page,
        Page.GetType(),
        "ShowPDF",
        "window.open('DisplayPDF.aspx?file=" + System.IO.GetFileName(filePath) + "?dt=" + DateTime.Now.Ticks.ToString() + "');",
        true);
}
else
{
    MessageBox.Show("Report was not generated.");
}

【问题讨论】:

    标签: c# asp.net asp.net-core-mvc


    【解决方案1】:

    基于这个webform代码,你可以在core mvc中显示pdf如下:

    请注意,我的 pdf 文件放在核心的“wwwroot”文件夹下 项目。

    DisplayPDFController.cs:

     public class DisplayPDFController : Controller
    {
        private IWebHostEnvironment _hostingEnvironment;
    
        public DisplayPDFController(IWebHostEnvironment environment)
        {
            _hostingEnvironment = environment;
        }
        public IActionResult Index()
        {
    
            return View();
        }
        [HttpPost]
        public string Index(string fileName)
        {
            string filePath = Path.Combine(_hostingEnvironment.WebRootPath, @"Files\" + fileName);
            if (System.IO.File.Exists(filePath))
            {
                return filePath;
            }
            else
            {
                return "Report was not generated.";
            }
        }
        public FileResult ShowPDF(string path)
        {
            var fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read);
            return File(fileStream, "application/pdf");
        }
    }
    

    Index.cshtml 视图:

    @{
        Layout = null;
    }
    
    <!DOCTYPE html>
    
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Index</title>
        <script src="~/lib/jquery/dist/jquery.js"></script>
        <script>
            $(function () {
                $("#show").click(function () {
                    event.preventDefault();
                    $.ajax({
                        type: 'POST',
                        data: { fileName: $("#Text1").val() },
                        url: "/DisplayPDF/Index",
                        success: function (response) {
                            if (response == 'Report was not generated.') {
                                alert(response);
                            } else {
                                window.open("/DisplayPDF/ShowPDF?path=" + response, "_blank");
                            }
                        },
                    });
                })
            })
        </script>
    </head>
    <body>
        <form>
            <input id="Text1" type="text" placeholder="FileName" />
            <input id="show" type="submit" value="show pdf" />
        </form>
    
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-21
      • 2017-09-29
      • 2015-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      • 2020-03-14
      相关资源
      最近更新 更多