Home » c# » c# – How to return PDF using iText-Exceptionshub

c# – How to return PDF using iText-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

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);
How to&Answers:

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