1

I am trying to return a PDF with simple text, but getting the following error when downloading the document: Failed to load PDF document. Any ideas on how to resolve this is appreciated.

MemoryStream ms = new MemoryStream(); PdfWriter writer = new PdfWriter(ms); PdfDocument pdfDocument = new PdfDocument(writer); Document document = new Document(pdfDocument); document.Add(new Paragraph("Hello World")); //document.Close(); //writer.Close(); ms.Position = 0; string pdfName = $"IP-Report-{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.pdf"; return File(ms, "application/pdf", pdfName); 
2
  • 1
    Are you using .Net Framework or .Net Core? You shouldn't have both the .net tag and the .net-core tag. Commented Feb 18, 2020 at 19:25
  • Thanks - I have removed .NET. Commented Feb 18, 2020 at 19:32

1 Answer 1

6

You have to close the writer without closing the underlying stream, which will flush its internal buffer. As is, the document isn't being written to the memory stream in its entirety. Everything but ms should be in a using, too.

You can verify this is occuring by checking the length of ms in your code vs. the code below.

When the using (PdfWriter writer =...) closes, it will close the writer, which causes it to flush its pending writes to the underlying stream ms.

MemoryStream ms = new MemoryStream(); using (PdfWriter writer = new PdfWriter(ms)) using (PdfDocument pdfDocument = new PdfDocument(writer)) using (Document document = new Document(pdfDocument)) { /* * Depending on iTextSharp version, you might instead use: * writer.SetCloseStream(false); */ writer.CloseStream = false; document.Add(new Paragraph("Hello World")); } ms.Position = 0; string pdfName = $"IP-Report-{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.pdf"; return File(ms, "application/pdf", pdfName); 
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I appreciate the details. I just need to update this line from writer.CloseStream = false; to writer.SetCloseStream(false);
@TerryDoll I'll integrate that into my answer for future readers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.