views:

31

answers:

2

I have trying to generate simple pdfs from my app so that I can later move on to generating pdf with dynamic data... anyways. here's what i got.. the file is being generated but I want a way to also have the browser prompt the download of the file... (I actually dont even want to store the pdf file in my server but Im not sure how to get it to just provide it to the user without first storing it in the server drive... please help.

public ActionResult GetPDF()
        {
            Document document = new Document();
            PdfWriter.GetInstance(document, new FileStream(Server.MapPath("../Content/test.pdf"), FileMode.Create));
            document.Open();
            string strHTML = "<B>I Love ASP.Net!</B>";
            HTMLWorker htmlWorker = new HTMLWorker(document);
            htmlWorker.Parse(new StringReader(strHTML));
            document.Close();

            return File(document, "application/pdf", Server.HtmlEncode(filename));//this doesnt work, obviuously


        }
+1  A: 

Use a FileStreamResult Action

public FileStreamResult Export(int? ID)
{        
    MemoryStream stream = new MemoryStream();

    //Start of PDF work using iTextSharp PDF library
    Document pdf = new Document();
    PdfWriter writer = PdfWriter.GetInstance(pdf, stream);    
    pdf.Open();    
    pdf.Add(new Phrase("test"));    
    pdf.Close();
    //End of PDF work using iTextSharp PDF library

    //Where the download magic happens
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;filename=Log.pdf");
    Response.Buffer = true;
    Response.Clear();
    Response.OutputStream.Write(stream.GetBuffer(), 0, stream.GetBuffer().Length);
    Response.OutputStream.Flush();
    Response.End();

    return new FileStreamResult(Response.OutputStream, "application/pdf");
}
Dustin Laine
tblImage.AddCell(); pdf.Add(Image);Those two lines are giving me error :S
NachoF
Sorry, took a bunch out, You just need the bottom portion, I will update to make it clear.
Dustin Laine
A: 

you need to do something like...

change

PdfWriter.GetInstance(document, new FileStream(Server.MapPath("../Content/test.pdf"), FileMode.Create));

to

var memorystream ms = new memorystream;
PdfWriter.GetInstance(document, ms);

and then at the end...

Response.Clear;
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=PDFFile.pdf");

ms.Write(Response.OutputStream);
Basiclife
This gives me a couple of errors.. mainly with ms.Write, which doesnt take Response.OutputStream as paramter... im on mvc2 if it makes a difference
NachoF