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

Tab*_*tor 2 .net pdf model-view-controller itext7

我一直在尝试让 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");
     }
Run Code Online (Sandbox Code Playgroud)

每次我尝试加载 Report() 方法时,都会收到一条错误消息,指出该流已关闭,因此无法访问。我研究了几种不同的解释来解释为什么会出现这种情况,但所有这些似乎都适用于 iTextSharp 和 iText 5,因此这些解决方案不起作用。

我在这里做错了什么?

小智 6

尝试处置任何 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");
 }
Run Code Online (Sandbox Code Playgroud)

  • 是的,我也发现了这一点并添加了 doc.Closed(); 在冲洗之前。 (3认同)
  • @Taborator 使其成为 doc.Close(); (减去 D)它就像一个魅力! (2认同)