在MVC和.NET中使用iText 7生成PDF供下载

在MVC和.NET中使用iText 7生成PDF供下载,.net,pdf,model-view-controller,itext7,.net,Pdf,Model View Controller,Itext7,我一直在尝试让一个MVC应用程序生成一个PDF(填充有数据)并提示下载给用户。我已经设置了一个测试方法,只是想看看它是如何完成的,我正在尝试在内存中创建文档,因为我知道浏览器并不总是知道如果只传递一个字节流该怎么做 以下是我正在使用的方法: //Test Report public ActionResult Report() { MemoryStream stream = new MemoryStream(); PdfWri

我一直在尝试让一个MVC应用程序生成一个PDF(填充有数据)并提示下载给用户。我已经设置了一个测试方法,只是想看看它是如何完成的,我正在尝试在内存中创建文档,因为我知道浏览器并不总是知道如果只传递一个字节流该怎么做

以下是我正在使用的方法:

    //Test Report
    public ActionResult Report()
    {
        MemoryStream stream = new MemoryStream();        
        PdfWriter wri = new PdfWriter(stream);
        PdfDocument pdf = new PdfDocument(wri);
        Document doc = new Document(pdf);
        doc.Add(new Paragraph("Hello World!"));
        doc.Close();

        return new FileStreamResult(stream, "application/pdf");
     }
每次尝试加载Report()方法时,我都会收到一个错误,说明流已关闭,无法访问。我已经研究了一些不同的解释来解释为什么会这样,但它们似乎都是针对iTextSharp和iText 5的,所以解决方案不起作用


这里我做错了什么?

尝试处理任何IDisposable对象并返回原始数组

public ActionResult Report()
{ 
  byte[] pdfBytes;
  using (var stream = new MemoryStream())
  using (var wri = new PdfWriter(stream))
  using (var pdf = new PdfDocument(wri))
  using (var doc = new Document(pdf))
  {
    doc.Add(new Paragraph("Hello World!"));
    doc.Flush();
    pdfBytes = stream.ToArray();
  }
  return new FileContentResult(pdfBytes, "application/pdf");
 }

在文档关闭之前抓取字节不是一个好主意,结果pdf还没有完成。是的,我也抓到了,并添加了一个doc.closed();刷新之前。@Taborator使其成为doc.Close();(减去D)它就像一个符咒!