如何使用 iTextSharp 从数据表中生成一页一行的 PDF
How to generate PDF one page one row from datatable using iTextSharp
我创建了一个发布了许多二维码的网络表单页面,我想要的是我可以从我拥有的数据库中一页一页地打印凭证。这是我尝试编写的代码
Private Sub MySub(Param As String)
Try
Dim obj As New ReportObjects
Dim dt0 As New DataTable
Dim ds As New DataSet
ds = obj.MyStoredProcedure(Param)
obj.Dispose()
dt0 = ds.Tables(0)
obj.Dispose()
dt0.Dispose()
ds.Dispose()
For i As Integer = 0 To dt0.Rows.Count - 1
Dim qrGenerator As QRCodeGenerator = New QRCodeGenerator()
Dim qrCode As QRCodeGenerator.QRCode = qrGenerator.CreateQrCode(dt0.Rows(i).Item("VoucherNo"), QRCodeGenerator.ECCLevel.Q)
Using bitMap As Bitmap = qrCode.GetGraphic(20)
Using ms As MemoryStream = New MemoryStream()
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
byteImage = ms.ToArray()
End Using
End Using
Dim base64 As String = Convert.ToBase64String(byteImage)
Dim imageBytes As Byte() = Convert.FromBase64String(base64)
Dim image As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(imageBytes)
Using memoryStream As System.IO.MemoryStream = New System.IO.MemoryStream()
Dim document As Document = New Document(PageSize.A4, 1.0F, 1.0F, 1.0F, 1.0F)
Dim writer As PdfWriter = PdfWriter.GetInstance(document, memoryStream)
document.Open()
document.NewPage()
document.Add(image)
document.Add(New Phrase("Valid From : " & dt0.Rows(i).Item("StartDT").ToString() & " To " & dt0.Rows(i).Item("EndDT").ToString()))
document.Close()
Dim bytes As Byte() = memoryStream.ToArray()
memoryStream.Close()
Response.Clear()
Response.ContentType = "application/pdf"
Response.AddHeader("Content-Disposition", "attachment; filename=Image.pdf")
Response.ContentType = "application/pdf"
Response.Buffer = True
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.BinaryWrite(bytes)
Response.End()
End Using
Next
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Sub
我的代码遇到的问题是代码不生成多个页面。它只产生一页,数据是我 table 的第一行。我使用 iTextSharp 生成 PDF。
你的回答会很有帮助。谢谢
下面展示了如何使用NuGet包创建一个每页有一个二维码的PDF文档iTextSharp and QRCoder。大多数代码来自 OP,但需要重新排列。我添加了代码以允许指定 QR 码的大小。包含用于测试的代码。
以下假设您使用的是 VB.NET ASP.NET Web Application (.NET Framework)
项目。为了进行测试,我使用了 Empty
项目模板。在“添加文件夹和核心引用”下,我选中了 Web Forms。在“高级”下,我取消选中 配置 HTTPS。
打开解决方案资源管理器
- 在 VS 菜单中,单击 查看
- Select 解决方案资源管理器
Download/install NuGet 包:
- 在解决方案资源管理器中,右键单击 <解决方案名称>
- Select管理 NuGet 包...
- 点击浏览
- 搜索:QRCoder
- Select 所需版本(例如:1.4.1)
- 单击安装
- 搜索:iTextSharp
- Select 所需版本(例如:5.5.13.2)
- 单击安装
添加网络表单(名称:default.aspx)
- 在 VS 菜单中,单击 项目
- Select 添加新项目...
- SelectWeb 表单(名称:default.aspx)
- 单击添加
default.aspx
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="default.aspx.vb" Inherits="WebApplicationArya._default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button runat="server" id="btnCreateQRCode" Text="Create QRCode" Onclick="btnCreateQRCode_Click" />
</div>
</form>
</body>
</html>
修改default.aspx.vb
- 在解决方案资源管理器中,右键单击 default.aspx 和 select 查看代码
default.aspx.vb
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports QRCoder
Public Class _default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Private Function CreateTestData() As DataTable
Dim dt0 As New DataTable
'for testing
dt0.Columns.Add("VoucherNo", System.Type.GetType("System.Int32"))
dt0.Columns.Add("StartDT", System.Type.GetType("System.DateTime"))
dt0.Columns.Add("EndDT", System.Type.GetType("System.DateTime"))
Dim dr As DataRow
For i As Integer = 0 To 6 Step 1
'create new row
dr = dt0.NewRow()
dr("VoucherNo") = "123" & i.ToString()
dr("StartDT") = DateTime.Now
dr("EndDT") = DateTime.Now.AddDays(30)
'add
dt0.Rows.Add(dr)
Next
Return dt0
End Function
Private Sub CreatePdf(dt0 As DataTable, Optional qrCodeSize As Single = 150.0F)
Dim pdfBytes As Byte() = Nothing
'Dim writer As PdfWriter = Nothing
Try
Using memoryStream As System.IO.MemoryStream = New System.IO.MemoryStream()
Using document As Document = New Document(PageSize.A4, 1.0F, 1.0F, 1.0F, 1.0F)
Using writer As PdfWriter = PdfWriter.GetInstance(document, memoryStream)
'open
document.Open()
'create new PDF page for each QRCode
For i As Integer = 0 To dt0.Rows.Count - 1 Step 1
Dim byteImage As Byte()
Dim qrGenerator As QRCodeGenerator = New QRCodeGenerator()
'create QRCode for each VoucherNo in DataTable
Dim qrGenerator1 As QRCodeGenerator = New QRCodeGenerator()
Dim qrCodeData1 As QRCodeData = qrGenerator1.CreateQrCode(dt0.Rows(i).Item("VoucherNo"), QRCodeGenerator.ECCLevel.Q)
Dim qrCode1 As QRCode = New QRCode(qrCodeData1)
Using bitMap As System.Drawing.Bitmap = qrCode1.GetGraphic(20)
Using ms As System.IO.MemoryStream = New System.IO.MemoryStream()
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
byteImage = ms.ToArray()
End Using
End Using
Dim image As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(byteImage)
'Dim base64 As String = Convert.ToBase64String(byteImage)
'Dim imageBytes As Byte() = Convert.FromBase64String(base64)
'Dim image As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(imageBytes)
'set size
'image.ScaleAbsolute(200.0F, 200.0F)
'ex: 200.0F, 200.0F
image.ScaleAbsolute(qrCodeSize, qrCodeSize)
'add new page
document.NewPage()
'add QRCode image
document.Add(image)
'add text
document.Add(New Phrase("Valid From : " & dt0.Rows(i).Item("StartDT").ToString() & " To " & dt0.Rows(i).Item("EndDT").ToString() & " (image" & i.ToString() & ")"))
Next
'close
document.Close()
'convert PDF to byte()
pdfBytes = memoryStream.ToArray()
End Using
End Using
End Using
'send data
SendData(pdfBytes)
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Sub
Private Sub SendData(pdfBytes As Byte())
Response.Clear()
Response.ContentType = "application/pdf"
Response.AddHeader("Content-Disposition", "attachment; filename=Image.pdf")
Response.ContentType = "application/pdf"
Response.Buffer = True
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.BinaryWrite(pdfBytes)
'Response.End()
End Sub
Protected Sub btnCreateQRCode_Click(sender As Object, e As EventArgs)
'ToDo: Replace "CreateTestData" with function to retrieve data
'get test data
Dim dt0 As DataTable = CreateTestData()
'create PDF containing QRCodes
'CreatePdf(dt0)
'create PDF; set size for QR codes
CreatePdf(dt0, 100.0F)
End Sub
End Class
注意:您需要将“CreateTestData”函数替换为检索数据的函数。
资源:
- QRCoder (NuGet)
- QRCoder (Github)
- How to easily implement QRCoder in ASP.NET Core using C#
- iTextSharp: How to resize an image to fit a fix size?
- Adding Data to a DataTable
- DataColumn.DataType Property
我创建了一个发布了许多二维码的网络表单页面,我想要的是我可以从我拥有的数据库中一页一页地打印凭证。这是我尝试编写的代码
Private Sub MySub(Param As String)
Try
Dim obj As New ReportObjects
Dim dt0 As New DataTable
Dim ds As New DataSet
ds = obj.MyStoredProcedure(Param)
obj.Dispose()
dt0 = ds.Tables(0)
obj.Dispose()
dt0.Dispose()
ds.Dispose()
For i As Integer = 0 To dt0.Rows.Count - 1
Dim qrGenerator As QRCodeGenerator = New QRCodeGenerator()
Dim qrCode As QRCodeGenerator.QRCode = qrGenerator.CreateQrCode(dt0.Rows(i).Item("VoucherNo"), QRCodeGenerator.ECCLevel.Q)
Using bitMap As Bitmap = qrCode.GetGraphic(20)
Using ms As MemoryStream = New MemoryStream()
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
byteImage = ms.ToArray()
End Using
End Using
Dim base64 As String = Convert.ToBase64String(byteImage)
Dim imageBytes As Byte() = Convert.FromBase64String(base64)
Dim image As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(imageBytes)
Using memoryStream As System.IO.MemoryStream = New System.IO.MemoryStream()
Dim document As Document = New Document(PageSize.A4, 1.0F, 1.0F, 1.0F, 1.0F)
Dim writer As PdfWriter = PdfWriter.GetInstance(document, memoryStream)
document.Open()
document.NewPage()
document.Add(image)
document.Add(New Phrase("Valid From : " & dt0.Rows(i).Item("StartDT").ToString() & " To " & dt0.Rows(i).Item("EndDT").ToString()))
document.Close()
Dim bytes As Byte() = memoryStream.ToArray()
memoryStream.Close()
Response.Clear()
Response.ContentType = "application/pdf"
Response.AddHeader("Content-Disposition", "attachment; filename=Image.pdf")
Response.ContentType = "application/pdf"
Response.Buffer = True
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.BinaryWrite(bytes)
Response.End()
End Using
Next
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Sub
我的代码遇到的问题是代码不生成多个页面。它只产生一页,数据是我 table 的第一行。我使用 iTextSharp 生成 PDF。
你的回答会很有帮助。谢谢
下面展示了如何使用NuGet包创建一个每页有一个二维码的PDF文档iTextSharp and QRCoder。大多数代码来自 OP,但需要重新排列。我添加了代码以允许指定 QR 码的大小。包含用于测试的代码。
以下假设您使用的是 VB.NET ASP.NET Web Application (.NET Framework)
项目。为了进行测试,我使用了 Empty
项目模板。在“添加文件夹和核心引用”下,我选中了 Web Forms。在“高级”下,我取消选中 配置 HTTPS。
打开解决方案资源管理器
- 在 VS 菜单中,单击 查看
- Select 解决方案资源管理器
Download/install NuGet 包:
- 在解决方案资源管理器中,右键单击 <解决方案名称>
- Select管理 NuGet 包...
- 点击浏览
- 搜索:QRCoder
- Select 所需版本(例如:1.4.1)
- 单击安装
- 搜索:iTextSharp
- Select 所需版本(例如:5.5.13.2)
- 单击安装
添加网络表单(名称:default.aspx)
- 在 VS 菜单中,单击 项目
- Select 添加新项目...
- SelectWeb 表单(名称:default.aspx)
- 单击添加
default.aspx
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="default.aspx.vb" Inherits="WebApplicationArya._default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button runat="server" id="btnCreateQRCode" Text="Create QRCode" Onclick="btnCreateQRCode_Click" />
</div>
</form>
</body>
</html>
修改default.aspx.vb
- 在解决方案资源管理器中,右键单击 default.aspx 和 select 查看代码
default.aspx.vb
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports QRCoder
Public Class _default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Private Function CreateTestData() As DataTable
Dim dt0 As New DataTable
'for testing
dt0.Columns.Add("VoucherNo", System.Type.GetType("System.Int32"))
dt0.Columns.Add("StartDT", System.Type.GetType("System.DateTime"))
dt0.Columns.Add("EndDT", System.Type.GetType("System.DateTime"))
Dim dr As DataRow
For i As Integer = 0 To 6 Step 1
'create new row
dr = dt0.NewRow()
dr("VoucherNo") = "123" & i.ToString()
dr("StartDT") = DateTime.Now
dr("EndDT") = DateTime.Now.AddDays(30)
'add
dt0.Rows.Add(dr)
Next
Return dt0
End Function
Private Sub CreatePdf(dt0 As DataTable, Optional qrCodeSize As Single = 150.0F)
Dim pdfBytes As Byte() = Nothing
'Dim writer As PdfWriter = Nothing
Try
Using memoryStream As System.IO.MemoryStream = New System.IO.MemoryStream()
Using document As Document = New Document(PageSize.A4, 1.0F, 1.0F, 1.0F, 1.0F)
Using writer As PdfWriter = PdfWriter.GetInstance(document, memoryStream)
'open
document.Open()
'create new PDF page for each QRCode
For i As Integer = 0 To dt0.Rows.Count - 1 Step 1
Dim byteImage As Byte()
Dim qrGenerator As QRCodeGenerator = New QRCodeGenerator()
'create QRCode for each VoucherNo in DataTable
Dim qrGenerator1 As QRCodeGenerator = New QRCodeGenerator()
Dim qrCodeData1 As QRCodeData = qrGenerator1.CreateQrCode(dt0.Rows(i).Item("VoucherNo"), QRCodeGenerator.ECCLevel.Q)
Dim qrCode1 As QRCode = New QRCode(qrCodeData1)
Using bitMap As System.Drawing.Bitmap = qrCode1.GetGraphic(20)
Using ms As System.IO.MemoryStream = New System.IO.MemoryStream()
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
byteImage = ms.ToArray()
End Using
End Using
Dim image As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(byteImage)
'Dim base64 As String = Convert.ToBase64String(byteImage)
'Dim imageBytes As Byte() = Convert.FromBase64String(base64)
'Dim image As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(imageBytes)
'set size
'image.ScaleAbsolute(200.0F, 200.0F)
'ex: 200.0F, 200.0F
image.ScaleAbsolute(qrCodeSize, qrCodeSize)
'add new page
document.NewPage()
'add QRCode image
document.Add(image)
'add text
document.Add(New Phrase("Valid From : " & dt0.Rows(i).Item("StartDT").ToString() & " To " & dt0.Rows(i).Item("EndDT").ToString() & " (image" & i.ToString() & ")"))
Next
'close
document.Close()
'convert PDF to byte()
pdfBytes = memoryStream.ToArray()
End Using
End Using
End Using
'send data
SendData(pdfBytes)
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Sub
Private Sub SendData(pdfBytes As Byte())
Response.Clear()
Response.ContentType = "application/pdf"
Response.AddHeader("Content-Disposition", "attachment; filename=Image.pdf")
Response.ContentType = "application/pdf"
Response.Buffer = True
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.BinaryWrite(pdfBytes)
'Response.End()
End Sub
Protected Sub btnCreateQRCode_Click(sender As Object, e As EventArgs)
'ToDo: Replace "CreateTestData" with function to retrieve data
'get test data
Dim dt0 As DataTable = CreateTestData()
'create PDF containing QRCodes
'CreatePdf(dt0)
'create PDF; set size for QR codes
CreatePdf(dt0, 100.0F)
End Sub
End Class
注意:您需要将“CreateTestData”函数替换为检索数据的函数。
资源:
- QRCoder (NuGet)
- QRCoder (Github)
- How to easily implement QRCoder in ASP.NET Core using C#
- iTextSharp: How to resize an image to fit a fix size?
- Adding Data to a DataTable
- DataColumn.DataType Property