我正在使用带有iTextSharp的ASP.NET 3.5,我有以下代码:
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();
以上代码填写pdf文件并将新文件保存到TempFiles文件夹。然后它会提示用户保存或打开文件。如果不将文件保存到TempFiles位置,我可以实现相同的功能吗?
答案 0 :(得分:4)
是的,您可以直接写入响应的输出流。我没有使用PdfStamper
,但这是我在生成新PDF时的方式:
doc = new iTextSharp.text.Document(PageSize.A4);
writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, Response.OutputStream);
writer.SetFullCompression();
doc.Open();
看起来您将流传递到PdfStamper
构造函数中,因此以下内容应该有效:
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();