C# 中使用iTextSharp组件创建简单PDF

iTextSharp下载地址:http://sourceforge.net/projects/itextsharp/

 

下载的压缩包中的第一个文件解压:

将iTextSharp.dll文件拷贝到项目的bin目录,然后在项目中添加引用:

然后在后台代码添加引用:

1 using iTextSharp.text;
2 using iTextSharp.text.pdf;
3 using System.IO;
4 using System.Diagnostics;
 1 //创建PDF
 2 private void CreatePdf()
 3 {
 4     //定义一个Document,并设置页面大小为A4,竖向 
 5     iTextSharp.text.Document doc = new Document(PageSize.A4);
 6     try
 7     {
 8         //写实例 
 9         PdfWriter.GetInstance(doc, new FileStream("D:\\Hello.pdf", FileMode.Create));
10         #region 设置PDF的头信息,一些属性设置,在Document.Open 之前完成
11         doc.AddAuthor("作者幻想Zerow");
12         doc.AddCreationDate();
13         doc.AddCreator("创建人幻想Zerow");
14         doc.AddSubject("Dot Net 使用 itextsharp 类库创建PDF文件的例子");
15         doc.AddTitle("此PDF由幻想Zerow创建,嘿嘿");
16         doc.AddKeywords("ASP.NET,PDF,iTextSharp,幻想Zerow");
17         //自定义头 
18         doc.AddHeader("Expires", "0");
19         #endregion //打开document
20         doc.Open();
21         //载入字体 
22         BaseFont.AddToResourceSearch("iTextAsian.dll");
23         BaseFont.AddToResourceSearch("iTextAsianCmaps.dll");
24         //"UniGB-UCS2-H" "UniGB-UCS2-V"是简体中文,分别表示横向字 和 // 纵向字 //" STSong-Light"是字体名称 
25         BaseFont baseFT = BaseFont.CreateFont(@"c:\windows\fonts\SIMHEI.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
26         iTextSharp.text.Font font = new iTextSharp.text.Font(baseFT); //写入一个段落, Paragraph 
27         doc.Add(new Paragraph("您好, PDF !", font));
28         //关闭document 
29         doc.Close();
30         //打开PDF,看效果 
31         Process.Start("D:\\Hello.pdf");
32     }
33     catch (DocumentException de) { Console.WriteLine(de.Message); Console.ReadKey(); }
34     catch (IOException io) { Console.WriteLine(io.Message); Console.ReadKey(); }
35 }

posted @ 2013-03-16 10:39  Kenyep  阅读(11786)  评论(1编辑  收藏  举报