c# - 如何在 MVC 中将 PDF 返回给浏览器?

标签 c# asp.net asp.net-mvc pdf itextsharp

我有这个 iTextSharp 的演示代码

    Document document = new Document();
    try
    {
        PdfWriter.GetInstance(document, new FileStream("Chap0101.pdf", FileMode.Create));

        document.Open();

        document.Add(new Paragraph("Hello World"));

    }
    catch (DocumentException de)
    {
        Console.Error.WriteLine(de.Message);
    }
    catch (IOException ioe)
    {
        Console.Error.WriteLine(ioe.Message);
    }

    document.Close();

如何让 Controller 返回pdf文档给浏览器?

编辑:

运行此代码确实打开了 Acrobat,但我收到一条错误消息“文件已损坏且无法修复”

  public FileStreamResult pdf()
    {
        MemoryStream m = new MemoryStream();
        Document document = new Document();
        PdfWriter.GetInstance(document, m);
        document.Open();
        document.Add(new Paragraph("Hello World"));
        document.Add(new Paragraph(DateTime.Now.ToString()));
        m.Position = 0;

        return File(m, "application/pdf");
    }

知道为什么这不起作用吗?

最佳答案

返回一个FileContentResult。 Controller 操作的最后一行类似于:

return File("Chap0101.pdf", "application/pdf");

如果您动态生成此 PDF,最好使用 MemoryStream,并在内存中创建文档而不是保存到文件中。代码将类似于:

Document document = new Document();

MemoryStream stream = new MemoryStream();

try
{
    PdfWriter pdfWriter = PdfWriter.GetInstance(document, stream);
    pdfWriter.CloseStream = false;

    document.Open();
    document.Add(new Paragraph("Hello World"));
}
catch (DocumentException de)
{
    Console.Error.WriteLine(de.Message);
}
catch (IOException ioe)
{
    Console.Error.WriteLine(ioe.Message);
}

document.Close();

stream.Flush(); //Always catches me out
stream.Position = 0; //Not sure if this is required

return File(stream, "application/pdf", "DownloadName.pdf");

关于c# - 如何在 MVC 中将 PDF 返回给浏览器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1510451/

相关文章:

asp.net-mvc - 为 MVC5 中的操作授权参数

c# - 根据 ASP.NET 查询从模型返回部分列表

asp.net-mvc - 在asp.net MVC3中调用局部 View

c# - 使用 'hwnd'注册到窗口消息

c# - 使用 'ReplaceWith' 迭代 XElement 集合仅在我首先使用 'ToList()' 时有效

javascript - 在哪里存储访问和刷新 token

javascript - 从代码隐藏调用javascript方法

c# - 在 GAC 中枚举程序集

c# - 如何直接在 .aspx 中获取 AspNet Identity 用户 ID?

c# - LINQ to SQL 关联 - "Properties do not have matching types"