views:

100

answers:

1

I am using ASP.NET 3.5 with iTextSharp and I have the following code:

var templatePath = Server.MapPath(@"~/Templates/template1.pdf");
var newFilePath = Server.MapPath(@"~/TempFiles/new.pdf");

PdfReader pdfReader = new PdfReader(templatePath);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFilePath, FileMode.Create));
AcroFields pdfFormFields = pdfStamper.AcroFields;
pdfFormFields.SetField("Box1", "007");
pdfFormFields.SetField("Box2", "123456");
pdfStamper.FormFlattening = false;
pdfStamper.Close();
Response.ClearContent();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment;filename=new.pdf"));
Response.WriteFile(newFilePath);
Response.End();

The above code fills out a pdf file and saves the new file to the TempFiles folder. It then prompts the user to either save or open the file. Can I achieve the same functionality without saving the file to the TempFiles location?

+3  A: 

Yes, you can write directly to the output stream of the response. I haven't used PdfStamper, but here's how I do it when generating new PDFs:

doc = new iTextSharp.text.Document(PageSize.A4);
writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, Response.OutputStream);
writer.SetFullCompression();
doc.Open();

It looks like you pass a stream into the PdfStamper constructor, so the following should work:

var templatePath = Server.MapPath(@"~/Templates/template1.pdf");

PdfReader pdfReader = new PdfReader(templatePath);
Response.ClearContent();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment;filename=new.pdf"));
PdfStamper pdfStamper = new PdfStamper(pdfReader, Response.OutputStream);
AcroFields pdfFormFields = pdfStamper.AcroFields;
pdfFormFields.SetField("Box1", "007");
pdfFormFields.SetField("Box2", "123456");
pdfStamper.FormFlattening = false;
pdfStamper.Close();
Response.End();
T.J. Crowder