无法检查是否正确创建了PDF文件

时间:2014-04-22 09:58:40

标签: c# asp.net pdf printing itextsharp

我无法打开我的pdf文件。它说其他一些进程正在使用它。但是我已经停止运行我的程序了。我做错了吗?

我的按钮运行select程序,将其存储在数据表

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

    }

我在这里打印数据表:

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

1 个答案:

答案 0 :(得分:2)

添加段落之后你是否关闭了文档?在iTextSharp中,示例代码说:

pdfDoc.Open();

//Some content added in between

pdfDoc.Close();

我不知道你是否关闭它,因为它不在你的样本中。有时,在处理文件时,如果不关闭它们,它们会被破坏而无法打开。这可能是个问题。