1

I am trying to create a PDF using iText 7 in my Asp.Net application. Unfortunately whenever I try to open the PDF it tells me that the file is broken and can't be opened. I have no idea why because my code seems fine to me. This is what I have:

public ActionResult CreateLieferschein()
{
    MemoryStream stream = new MemoryStream();

    PdfWriter writer = new PdfWriter(stream);
    var pdf = new PdfDocument(writer);
    var document = new Document(pdf);
    document.Add(new Paragraph("Hello World!"));

    return File(stream, "application/pdf", "test.pdf");
}
Tom el Safadi
  • 6,164
  • 5
  • 49
  • 102

1 Answers1

2

It looks like you're missing the call to document.Close()

Here's the example from their docs, see the last line:

var writer = new PdfWriter(dest);
var pdf = new PdfDocument(writer);
var document = new Document(pdf);
document.Add(new Paragraph("Hello World!"));
document.Close();
Daniel Szabo
  • 7,181
  • 6
  • 48
  • 65
  • By the way do you know how to download this file with an Ajax request? I would open a new question if you do. – Tom el Safadi Aug 02 '18 at 23:05
  • @Anokrize I think you're really close -- just grab the bytes from your newly created pdf file and pass them to the `return File(...)` call. See here: https://stackoverflow.com/a/3207274/183624 – Daniel Szabo Aug 02 '18 at 23:10