在 ASP.NET 中创建 PDF 文档






4.74/5 (59投票s)
如何在 ASP.NET 中创建 PDF 文档。
引言
本文简要介绍了如何使用这个免费库从 ASP.NET 网页创建 PDF 文档:http://sourceforge.net/projects/itextsharp/。
代码
首先,我将创建一个简单的“Hello PDF”。 接下来,我将创建一个包含表格的更复杂的 PDF 文档。 要开始创建 PDF 文档,您需要从 http://sourceforge.net/projects/itextsharp/ 下载 iTextSharp 库,并在您的项目中引用它。 PDF 文档由网页“ShowPDF.aspx” “动态”创建。 此页面还执行“Response.Redirect
”以跳转到创建的 PDF。 我们将首先导入所需的命名空间
Imports System
Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.pdf
接下来,在 Page_Load
事件中,我们确定用户请求了哪个文档
Partial Class ShowPDF
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
If Request.QueryString("id") = 1 Then
ShowHello()
Else
ShowTable()
End If
End Sub
End Class
ShowHello
函数创建一个只包含一个字符串“Hello World”的简单文档,然后将用户重定向到新创建的文档
Sub ShowHello()
Dim doc As Document = New Document
PdfWriter.GetInstance(doc, New FileStream(Request.PhysicalApplicationPath + _
"\1.pdf", FileMode.Create))
doc.Open()
doc.Add(New Paragraph("Hello World"))
doc.Close()
Response.Redirect("~/1.pdf")
End Sub
一个更复杂的例子
ShowTable
函数稍微复杂一些。 它也创建一个 PDF 文档并将用户重定向到它
Sub ShowTable()
Dim doc As Document = New Document
PdfWriter.GetInstance(doc, New FileStream(Request.PhysicalApplicationPath + _
"\2.pdf", FileMode.Create))
doc.Open()
Dim table As Table = New Table(3)
table.BorderWidth = 1
table.BorderColor = New Color(0, 0, 255)
table.Padding = 3
table.Spacing = 1
Dim cell As Cell = New Cell("header")
cell.Header = True
cell.Colspan = 3
table.AddCell(cell)
cell = New Cell("example cell with colspan 1 and rowspan 2")
cell.Rowspan = 2
cell.BorderColor = New Color(255, 0, 0)
table.AddCell(cell)
table.AddCell("1.1")
table.AddCell("2.1")
table.AddCell("1.2")
table.AddCell("2.2")
table.AddCell("cell test1")
cell = New Cell("big cell")
cell.Rowspan = 2
cell.Colspan = 2
cell.HorizontalAlignment = Element.ALIGN_CENTER
cell.VerticalAlignment = Element.ALIGN_MIDDLE
cell.BackgroundColor = New Color(192, 192, 192)
table.AddCell(cell)
table.AddCell("cell test2")
doc.Add(table)
doc.Close()
Response.Redirect("~/2.pdf")
End Sub
使用 iTextSharp 库 (http://sourceforge.net/projects/itextsharp/) 可以非常容易地从 Web 应用程序创建 PDF 文档。