Mathieu
Mathieu

Reputation: 3093

put generated pdf file without saving it on the server

I have code (in a .ashx-file) that generates a PDF file from a PDF template. The generated pdf gets personalized with a name and a code. I use iTextSharp to do so.

This is the code:

using (var existingFileStream = new FileStream(fileNameExisting, FileMode.Open))
    using (var newFileStream = new FileStream(fileNameNew, FileMode.Create))
    {
        var pdfReader = new PdfReader(existingFileStream);
        var stamper = new PdfStamper(pdfReader, newFileStream);

        var form = stamper.AcroFields;
        var fieldKeys = form.Fields.Keys;

        form.SetField("Name", name);
        form.SetField("Code", code);

        stamper.FormFlattening = true;

        stamper.Close();
        pdfReader.Close();
    }

context.Response.AppendHeader("content-disposition", "inline; filename=zenith_coupon.pdf");
context.Response.TransmitFile(fileNameNew);
context.Response.ContentType = "application/pdf";

This works, but it saves the file on the server. I don't want to do that because there're going to be a lot of people downloading the PDF file and the server will be full in no time.

So my question is, how can I generate a PDF with iTextSharp without saving it and put it to the user?

Upvotes: 2

Views: 4109

Answers (2)

Yahia
Yahia

Reputation: 70369

You can use any Stream (for example MemoryStream) for the intermediate PDF (in your code currently named newFileStream) if you don't want to save it as a file - for sample code see http://www.developerfusion.com/code/6623/dynamically-generating-pdfs-in-net/ and http://forums.asp.net/t/1093198.aspx/1.

Just remember to rewind (i.e. set Position = 0) the MemoryStream before transmitting it to the client (for example by Response.Write or CopyTo (Response.OutputStream) )...

Upvotes: 4

CodeCaster
CodeCaster

Reputation: 151720

Instead of using a FileStream you could use a MemoryStream and then use Response.Write() to output the stream contents.

Upvotes: 5

Related Questions