Search code examples
.netpdfmodel-view-controlleritext7

Generate PDF for Download using iText 7 in MVC and .NET


I have been trying to get an MVC application to generate a PDF(populated with data) and prompt to download it to the user. I've setup a test method just to see how it would be done, and I'm trying to create the document in memory since I know browsers don't always know what to do if you just pass it a byte stream.

Here is the method I'm using:

    //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");
     }

Every time I attempt to load the Report() method, I get an error saying that the stream cannot be accessed because it's closed. I've looked into a few different explanations into why this is, but all of them seem to be for iTextSharp and iText 5, so the solutions don't work.

What am I doing wrong, here?


Solution

  • try to dispose any IDisposable object and return a raw array

    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");
     }