Pergunta

I am unable to open my pdf file. It says some other process is using it. However I had stopped running my program. Am I doing something wrong?

My button runs the select procedure, stores it in a data table

 protected void btnPrint_Click(object sender, EventArgs e)
    {
    Connection con = new Connection();
    SqlDataAdapter da;
    DataTable ds;
    con.con = new SqlConnection(con.str);
    con.cmd.CommandText = "aSelectProcedure";
    con.cmd.CommandType = CommandType.StoredProcedure;
    da = new SqlDataAdapter();
    da.SelectCommand = con.cmd;
    ds = new DataTable();
    try
        {
        con.con.Open();
        da.Fill(ds);

        }
    catch (Exception ex)
        {

        }
    finally
        {
        con.con.Close();
        con.con.Dispose();
        ExportToPdf(ds);
        }

    }

I am printing the data table here:

public void ExportToPdf(DataTable dt)
    {
    string pdfFilePath = @"D:/myPdf.pdf";
    Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
    PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(pdfFilePath, FileMode.Create));
    doc.Open();
   if (dt != null)
     {
         //Craete instance of the pdf table and set the number of column in that table
         PdfPTable PdfTable = new PdfPTable(dt.Columns.Count);
         PdfPCell PdfPCell = null;
         Font font8 = FontFactory.GetFont("ARIAL", 7);
         //Add Header of the pdf table
         PdfPCell = new PdfPCell(new Phrase(new Chunk("ID", font8)));
         PdfTable.AddCell(PdfPCell);
         PdfPCell = new PdfPCell(new Phrase(new Chunk("Name", font8)));
         PdfTable.AddCell(PdfPCell);
         //How add the data from datatable to pdf table
         for (int rows = 0; rows < dt.Rows.Count; rows++)
         {
             for (int column = 0; column < dt.Columns.Count; column++)
             {
                 PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8)));
                 PdfTable.AddCell(PdfPCell);
             }
         }
         PdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table
         Paragraph paragraph = new Paragraph("Using ITextsharp I am going to show how to create simple table in PDF document ");
         doc.Add(paragraph);// add paragraph to the document
         doc.Add(PdfTable); // add pdf table to the document
Foi útil?

Solução

Did you close document after adding paragraphs and such? In iTextSharp , sample code says :

pdfDoc.Open();

//Some content added in between

pdfDoc.Close();

I don't know if you closed it, since it's not in your sample. Sometimes, when working with files, if you do not close them, they get corrupted and unable to open. That could be a problem.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top