Bryan
Bryan

Reputation: 8697

Error opening PDF file generated by asp.net

I'm trying to generate a PDF for my website. Currently, I'm attempting to get the data from the database and display it out on my PDF file, however my main priority was actually to get the value from the asp:label and export it into pdf format. Unfortunately, when i open the PDF file generated, i got this error.

Error : There was an error opening this document. This file is already open or in use by another application

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

    }

I checked my codes and i couldn't find any ways to solve the error and get the value successfully.

Upvotes: 1

Views: 2041

Answers (1)

mkl
mkl

Reputation: 95888

You do

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

It leaps to the eye that you do not in any way associate the output with the Document doc1. Thus, your file is not written to at all but neither is it ever closed.

Most likely you additionally want to instantiate a PdfWriter which writes to output and receives from 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();

Upvotes: 1

Related Questions