我可以创建一个像“Hello world”这样的简单pdf文件,但我想使用vb.net在pdf文件中生成一个表。我正在使用itextsharp库。
这是我到目前为止所尝试过的。
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 :(得分:2)
经过几个小时的研究,我才找到答案。只需在pdfDoc.Add(table)
之后关闭文档。
像:
pdfDoc.Add(table)
pdfDoc.Close()