c# - ASP.NET 核心 : Create and Open PDF (in browser)

标签 c# pdf asp.net-core itext

在 ASP.NET Core 中工作并使用 iTextSharp,我正在构建一个 PDF 并将其保存到本地系统。我现在想在浏览器中打开该文件,但似乎无法正常工作,因为我在一次尝试中遇到 FileStream 错误,而在另一次尝试中什么也没有。

我的逻辑在下面的 Controller 中。我用 //region description 替换了不必要的代码。重要的代码(我尝试过的东西)位于 TODO: Open the file 区域。

Controller

    [HttpPost]
    public (JsonResult, IActionResult) CreatePDF([FromBody] ReportViewModel model)
    {
        try
        {

            // region Logic code
            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
            {
                // Create the document
                iTextSharp.text.Document document = new iTextSharp.text.Document();
                // Place the document in the PDFWriter
                iTextSharp.text.pdf.PdfWriter PDFWriter =
                    iTextSharp.text.pdf.PdfWriter.GetInstance(document, memoryStream);

                // region Initialize Fonts

                // Open the document
                document.Open();

                // region Add content to document

                // Close the document
                document.Close();

                #region Create and Write the file
                // Create the directory
                string directory = $"{_settings.Value.ReportDirectory}\\";
                System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(directory));

                // region Create the fileName

                // Combine the directory and the fileName
                directory = System.IO.Path.Combine(directory, fileName);

                // Create the file
                byte[] content = memoryStream.ToArray();
                using (System.IO.FileStream fs = System.IO.File.Create(directory))
                {
                    fs.Write(content, 0, (int)content.Length);
                }
                #endregion

                #region TODO: Open the file
                // TRY: File(Stream, type) => Newtonsoft.Json.JsonSerializationException:
                // Error getting value from 'ReadTimeout' on 'System.IO.FileStream'.
                // ---> System.InvalidOperationException: Timeouts are supported for this stream.
                System.IO.FileStream fileStream = new System.IO.FileStream(directory, System.IO.FileMode.Open);
                var returnPDF = File(fileStream, contentType: "application/pdf");

                // TRY: File(path, type) => Newtonsoft.Json.JsonSerializationException:
                // Error getting value from 'ReadTimeout' on 'System.IO.FileStream'.
                // ---> System.InvalidOperationException: Timeouts are supported for this stream.
                returnPDF = File(System.IO.File.OpenRead(directory), contentType: "application/pdf" );

                // TRY: File(byte[], type) => Nothing happened
                returnPDF = File(content, contentType: "apllication/pdf");
                #endregion

                return ( Json(new { isError = false }), returnPDF );
            }
        }
        catch (System.Exception ex)
        {
            Serilog.Log.Error($"ReportController.CreatePDF() - {ex}");
            return ( Json(new { isError = true, errorMessage = ex.Message }), null );
        }
    }

对有用的 Stackoverflow 答案的引用

最佳答案

无需从目录中再次加载文件,您只需创建一个 FileContentResult 并将 byte[] 传递给它,您已经分配了它。

return ( Json(new { isError = false }), new FileContentResult(content, "application/pdf"));

请记住,浏览器不会以这种方式下载文件。它会提取响应流但不会下载它,因为它在您的 json 响应中,因此响应内容类型将为 application/json。

您可以改为只返回一个 IActionResult 并像那样做:

return new FileContentResult(content, "application/pdf");

如果您坚持使用“isError”信息,那么您可以另外提供一个 url,而不是文件结果。为此,您可以注册 IActionContextAccessor ConfigureServices(...) 方法中的类。

services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();

提供单独的路线并使用 IUrlHelperFactory生成一个 url。

可以找到样本here .

当响应 isError 等于 false 时,可以在前端以编程方式“单击”此 url。

关于c# - ASP.NET 核心 : Create and Open PDF (in browser),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51614338/

相关文章:

azure - KeyVaultErrorException : Operation returned an invalid status code 'Forbidden'

c# - 根据用户时区显示UTC时间

c# - 释放 COM 对象的正确方法?

java - 将图像包装到 Jframe

python - 如何在 Sphinx 文档中包含 PDF?

c# - Store 没有实现 IUserRoleStore<TUser> ASP.NET Core Identity

c# - 在 ASP.NET MVC 中上传和显示图像

c# - xamarin 表单 - webview 不安全连接 http

ruby-on-rails - 如何在 Rails 2.3.5 中将 prawnto-rendered .pdf 附加到电子邮件中?

c# - 自定义身份验证中间件 - 如何检查请求是匿名的还是授权的?