I have this demo code for iTextSharp
Document document = new Document();
try
{
PdfWriter.GetInstance(document, new FileStream("Chap0101.pdf", FileMode.Create));
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();
How do I get the controller to return the pdf document to the browser?
EDIT:
Running this code does open Acrobat but I get an error message "The file is damaged and could not be repaired"
public FileStreamResult pdf()
{
MemoryStream m = new MemoryStream();
Document document = new Document();
PdfWriter.GetInstance(document, m);
document.Open();
document.Add(new Paragraph("Hello World"));
document.Add(new Paragraph(DateTime.Now.ToString()));
m.Position = 0;
return File(m, "application/pdf");
}
Any ideas why this does not work?
If you return a
FileResult
from your action method, and use theFile()
extension method on the controller, doing what you want is pretty easy. There are overrides on theFile()
method that will take the binary contents of the file, the path to the file, or aStream
.Return a
FileContentResult
. The last line in your controller action would be something like: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:I got it working with this code.
You must specify :
For the file to be opened directly in the browser instead of being downloaded