开发者

Avoid saving new file on the disk

开发者 https://www.devze.com 2022-12-22 01:02 出处:网络
I am using ASP.NET 3.5 with iTextSharp and I have the following code: var templatePath = Server.MapPath(@\"~/Templates/template1.pdf\");

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;
pdfFormField开发者_JAVA百科s.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?


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();
0

精彩评论

暂无评论...
验证码 换一张
取 消