How to return PDF to browser in MVC?
Return a FileContentResult
. The last line in your controller action would be something like:
return File("Chap0101.pdf", "application/pdf");
If you are generating this PDF dynamically, it may be better to use a MemoryStream
, and create the document in memory instead of saving to file. The code would be something like:
Document document = new Document();MemoryStream stream = new MemoryStream();try{ PdfWriter pdfWriter = PdfWriter.GetInstance(document, stream); pdfWriter.CloseStream = false; document.Open(); document.Add(new Paragraph("Hello World"));}catch (DocumentException de){ Console.Error.WriteLine(de.Message);}catch (IOException ioe){ Console.Error.WriteLine(ioe.Message);}document.Close();stream.Flush(); //Always catches me outstream.Position = 0; //Not sure if this is requiredreturn File(stream, "application/pdf", "DownloadName.pdf");
I got it working with this code.
using iTextSharp.text;using iTextSharp.text.pdf;public FileStreamResult pdf(){ MemoryStream workStream = new MemoryStream(); Document document = new Document(); PdfWriter.GetInstance(document, workStream).CloseStream = false; document.Open(); document.Add(new Paragraph("Hello World")); document.Add(new Paragraph(DateTime.Now.ToString())); document.Close(); byte[] byteInfo = workStream.ToArray(); workStream.Write(byteInfo, 0, byteInfo.Length); workStream.Position = 0; return new FileStreamResult(workStream, "application/pdf"); }
You must specify :
Response.AppendHeader("content-disposition", "inline; filename=file.pdf");return new FileStreamResult(stream, "application/pdf")
For the file to be opened directly in the browser instead of being downloaded