2009-05-28 70 views
0

點擊時有一個按鈕,將文本插入到pdf中的表單域中,並將填充的pdf保存到目錄中。當我編輯pdf時,我想在瀏覽器中打開pdf,但Process.Start()不起作用。是否有更好的方法在生成PDF後立即顯示PDF?下面是按鈕的代碼:嘗試使用iTextSharp創建PDF後打開PDF,但無法使其正常工作?

protected void btnGenerateQuote_Click(object sender, EventArgs e) 
{ 
    string address = txtAddress.Text; 
    string company = txtCompany.Text; 
    string outputFilePath = @"C:\Quotes\Quote-" + company + "-.pdf"; 
    PdfReader reader = null; 
    try 
    { 
     reader = new PdfReader(@"C:\Quotes\Quote_Template.pdf"); 
     using (FileStream pdfOutputFile = new FileStream 
              (outputFilePath, FileMode.Create)) 
     { 
      PdfStamper formFiller = null; 
      try 
      { 
       formFiller = new PdfStamper(reader, pdfOutputFile); 
       AcroFields quote_template = formFiller.AcroFields; 
       //Fill the form 
       quote_template.SetField("OldAddress", address); 
       //Flatten - make the text go directly onto the pdf 
       //   and close the form. 
       //formFiller.FormFlattening = true; 
      } 
      finally 
      { 
       if (formFiller != null) 
       { 
        formFiller.Close(); 
       } 
      } 
     } 
    } 
    finally 
    { 
     reader.Close(); 
    } 
    //Process.Start(outputFilePath); // does not work 
} 

回答

4

因爲這是關於ASP.NET根據標籤,你不應該使用的Process.Start(),但例如像這樣的代碼:

private void respondWithFile(string filePath, string remoteFileName) 
{ 
    if (!File.Exists(filePath)) 
     throw new FileNotFoundException(
       string.Format("Final PDF file '{0}' was not found on disk.", 
          filePath)); 
    var fi = new FileInfo(filePath); 
    Response.Clear(); 
    Response.AddHeader("Content-Disposition", 
        String.Format("attachment; filename=\"{0}\"", 
           remoteFileName)); 
    Response.AddHeader("Content-Length", fi.Length.ToString()); 
    Response.ContentType = "application/octet-stream"; 
    Response.WriteFile(fi.FullName); 
    Response.End(); 
} 

這將使瀏覽器提供保存/打開對話框。

+0

「application/pdf」更準確的內容類型使得瀏覽器的檢測更容易。 – devstuff 2009-05-29 06:59:55

相關問題