这个是例子是网上淘来的,哈哈,很有用的!
首先要到网上下载itextsharp.dll,然后添加引用,主程序如下:
03 |
using System.Configuration; |
05 |
using System.Web.Security; |
07 |
using System.Web.UI.WebControls; |
08 |
using System.Web.UI.WebControls.WebParts; |
09 |
using System.Web.UI.HtmlControls; |
12 |
using iTextSharp.text; |
13 |
using iTextSharp.text.pdf; |
15 |
public partial class _Default : System.Web.UI.Page |
17 |
static DataTable datatable = new DataTable( "testpdf" ); |
18 |
protected void Page_Load( object sender, EventArgs e) |
24 |
datatable.Columns.Add( new DataColumn( "编号" )); |
25 |
datatable.Columns.Add( new DataColumn( "用户名" )); |
26 |
for ( int i = 1; i < 5; i++) |
28 |
dr = datatable.NewRow(); |
29 |
dr[0] = System.Convert.ToString(i); |
30 |
dr[1] = "测试" + System.Convert.ToString(i); |
31 |
datatable.Rows.Add(dr); |
35 |
protected void Button1_Click( object sender, EventArgs e) |
39 |
Document document = new Document(); |
40 |
PdfWriter.GetInstance(document, new FileStream(Server.MapPath( "Test.pdf" ), FileMode.Create)); |
42 |
BaseFont bfChinese = BaseFont.CreateFont( "C:\\WINDOWS\\Fonts\\simsun.ttc,1" , BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); |
43 |
Font fontChinese = new Font(bfChinese, 12, Font.NORMAL, new Color(0, 0, 0)); |
46 |
document.Add( new Paragraph( this .TextBox1.Text.ToString(), fontChinese)); |
48 |
iTextSharp.text.Image jpeg01 = iTextSharp.text.Image.GetInstance(Server.MapPath( "Images/gyl.jpg" )); |
50 |
iTextSharp.text.Image jpeg02 = iTextSharp.text.Image.GetInstance(Server.MapPath( "Images/yy.jpg" )); |
53 |
PdfPTable table = new PdfPTable(datatable.Columns.Count); |
55 |
for ( int i = 0; i < datatable.Rows.Count; i++) |
57 |
for ( int j = 0; j < datatable.Columns.Count; j++) |
59 |
table.AddCell( new Phrase(datatable.Rows[i][j].ToString(), fontChinese)); |
65 |
Response.Write( "<script>alert('导出成功!');</script>" ); |
67 |
catch (DocumentException de) |
69 |
Response.Write(de.ToString()); |
01 |
<%@ Page Language= "C#" AutoEventWireup= "true" CodeFile= "Default.aspx.cs" Inherits= "_Default" %> |
10 |
<form id= "form1" runat= "server" > |
13 |
请输入一些文字用于测试:<asp:TextBox ID= "TextBox1" runat= "server" ></asp:TextBox> |
14 |
<asp:Button ID= "Button1" runat= "server" OnClick= "Button1_Click" Text= "导出" /></div> |