2015-05-27 53 views
1

我可以创建一个简单的pdf文件,如“Hello world”,但我想用pdf生成pdf文件中的表格。我正在使用itextsharp库。用pdf生成表使用itextsharp vb.net从sql

这是我到目前为止尝试过的。

Protected Sub Create_PdfTable_Click(sender As Object, e As EventArgs) Handles Create_PdfTable.Click 
    Dim table As New PdfPTable(2) 

    table.TotalWidth = 216.0F 

    table.LockedWidth = True 

    Dim widths As Single() = New Single() {1.0F, 2.0F} 
    table.SetWidths(widths) 
    table.HorizontalAlignment = 0 

    table.SpacingBefore = 20.0F 
    table.SpacingAfter = 30.0F 

    Dim cell As New PdfPCell(New Phrase("Table Batch")) 
    cell.Colspan = 2 
    cell.Border = 0 
    cell.HorizontalAlignment = 1 
    table.AddCell(cell) 
    Dim connect As String = "server=localhost\SQLEXPRESS;database=my_db;uid=sa;password=Pass;" 
    Using conn As New SqlConnection(connect) 
     Dim pdfDoc As New Document() 
     Dim pdfWrite As PdfWriter = PdfWriter.GetInstance(pdfDoc, New FileStream("D://Projects/pdf/" & DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") & ".pdf", FileMode.Create)) 
     pdfDoc.Open() 

     Dim query As String = "SELECT TOP 10 batch_id, batch_name FROM tbl_batch" 
     Dim cmd As New SqlCommand(query, conn) 
     Try 
      conn.Open() 
      Using rdr As SqlDataReader = cmd.ExecuteReader() 
       While rdr.Read() 
        table.AddCell(rdr(0).ToString()) 
        table.AddCell(rdr(1).ToString()) 
       End While 
      End Using 
     Catch ex As Exception 
      Response.Write(ex.Message) 
     End Try 

     pdfDoc.Add(table) 
    End Using 
End Sub 

此代码正在生成一个空白pdf文件,我该如何解决这个问题?

+0

乍一看,该iTextSharp的代码看起来不错,但你肯定的SQL代码的作品?您是否曾尝试在表中使用硬编码内容的情况下首先创建“Hello World”表?如果这样做,你可以消除iTextSharp的罪魁祸首。 –

+0

@Bruno Lowagie我的查询正在工作 – Elyor

+0

这不是我的问题;我的问题是:没有查询的表是否工作(就像你已经设法得到一个“Hello World”的例子一样)。同时,我看到你解决了这个问题。您确实需要关闭文档(5步骤中的第5步)。 –

回答

2

经过几个小时的研究,我找到了答案。只需要在pdfDoc.Add(table)之后关闭文档。

像:

pdfDoc.Add(table) 
pdfDoc.Close()