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?
I know this question is old but I thought I would share this as I could not find anything similar.
I wanted to create my views/models as normal using Razor and have them rendered as Pdfs.
This way I had control over the pdf presentation using standard html output rather than figuring out how to layout the document using iTextSharp.
The project and source code is available here with nuget installation instructions:
https://github.com/andyhutch77/MvcRazorToPdf
You can create a custom class to modify the content type and add the file to the response.
http://haacked.com/archive/2008/05/10/writing-a-custom-file-download-action-result-for-asp.net-mvc.aspx
if the filename is generating dynamically then how to define filename here, it is generating through guid here.
You would normally do a Response.Flush followed by a Response.Close, but for some reason the iTextSharp library doesn't seem to like this. The data doesn't make it through and Adobe thinks the PDF is corrupt. Leave out the Response.Close function and see if your results are better:
I've run into similar problems and I've stumbled accross a solution. I used two posts, one from stack that shows the method to return for download and another one that shows a working solution for ItextSharp and MVC.
View page:
Scan controller: