我正在尝试为我的网站生成PDF。目前,我正在尝试从数据库中获取数据并将其显示在我的PDF文件中,但我的主要优先事项实际上是从asp:标签获取值并将其导出为pdf格式。不幸的是,当我打开生成的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 :(得分: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();
它突然意识到你没有以任何方式将output
与Document doc1.
相关联。因此,你的文件根本不会被写入,但它也不会被关闭。
您很可能还想要实例化PdfWriter
,该output
写入doc1:
并从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();
收到
{{1}}