2010-03-08 100 views
0

我使用ASP.NET 3.5與iTextSharp的,我有下面的代碼保存在新的文件:避免磁盤

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位置的情況下實現相同的功能嗎?

+1

@庫馬爾:你只接受了大約一半問題的答案。您可能想要檢查其他人是否值得選擇接受的答案。 – 2010-03-08 04:51:41

回答

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