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 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM