2013-06-03 45 views
1

我正在嘗試爲我的網站生成PDF文件。目前,我試圖從數據庫中獲取數據並將其顯示在我的PDF文件中,但我的主要優先事項實際上是從asp:label獲取值並將其導出爲pdf格式。不幸的是,當我打開生成的PDF文件時,我得到了這個錯誤。打開由asp.net生成的PDF文件時出錯

錯誤:打開此文檔時出錯。該文件已經被其他應用程序

protected void btnPDF_Click(object sender, EventArgs e) 
    { 

     var doc1 = new Document(); 
     var filename = DDLCase.SelectedItem.Text + ".pdf"; 
     var output = new FileStream(Path.Combine("C:\\Users\\apr12mpsip\\Desktop", filename), FileMode.Create); 
     doc1.Open(); 

     PdfPTable table = new PdfPTable(3); 
     PdfPCell cell = new PdfPCell(new Phrase("Header spanning 3 columns")); 
     cell.Colspan = 3; 
     cell.HorizontalAlignment = 1; 
     table.AddCell(cell); 
     table.AddCell("Col 1 Row 1"); 
     table.AddCell("Col 2 Row 1"); 

     doc1.Add(table); 

     SqlConnection con = new SqlConnection("Data Source = localhost; Initial Catalog = project; Integrated Security = SSPI"); 

     SqlCommand cm = new SqlCommand("Select typeofcrime, citizenreport from MemberReport where memberreportid='"+DDLCase.SelectedValue+"'", con); 
     con.Open(); 
     SqlDataReader dr; 
     dr = cm.ExecuteReader(); 
     while (dr.Read()) 
     { 
      table.AddCell(dr[0].ToString()); 
      table.AddCell(dr[1].ToString()); 
     } 
     dr.Close(); 


     doc1.Close(); 

    } 

我檢查我的代碼和我找不到解決的錯誤,併成功獲得價值的任何方式打開或使用。

+0

接收嘗試doc1.Dispose();關閉它之後。 – highwingers

+0

該方法沒有幫助。 –

+0

是否配置了輸出對象? – highwingers

回答

1

你做

var doc1 = new Document(); 
var filename = DDLCase.SelectedItem.Text + ".pdf"; 
var output = new FileStream(Path.Combine("C:\\Users\\apr12mpsip\\Desktop", filename), FileMode.Create); 
doc1.Open(); 
[... fetching some data and adding that to`doc1 ...] 
doc1.Close(); 

它躍起,你不以任何方式關聯的outputDocument doc1.因此,你的文件是不是在所有的但也不是永遠關閉寫入到眼睛。

最有可能你還想要實例化一個PdfWriter其寫入outputdoc1:

var doc1 = new Document(); 
var filename = DDLCase.SelectedItem.Text + ".pdf"; 
var output = new FileStream(Path.Combine("C:\\Users\\apr12mpsip\\Desktop", filename), FileMode.Create); 
PdfWriter.GetInstance(doc1, output); // instantiate a PdfWriter for doc1 and output 
doc1.Open(); 
[... fetching some data and adding that to`doc1 ...] 
doc1.Close(); 
+0

我能夠顯示出我的標題跨越3列。但是,我如何顯示數據庫中的值? –

+0

這完全是一個不同的問題。請自行將它作爲一個stackoverflow問題,並提供所需的信息,特別是您想要實現的內容(您希望如何顯示數據),您嘗試過的內容(您當前的任務代碼)以及以何種方式當前的輸出不符合您的要求。 – mkl

+0

好的。瞭解。謝謝。 –