將iTextSharp.dll檔案拷貝到項目的bin目錄,然後在項目中添加引用:
然後在後台代碼添加引用:
複製代碼 代碼如下:using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using System.Diagnostics;
//建立PDF
private void CreatePdf()
{
//定義一個Document,並設定頁面大小為A4,豎向
iTextSharp.text.Document doc = new Document(PageSize.A4);
try
{
//寫執行個體
PdfWriter.GetInstance(doc, new FileStream("D:\\Hello.pdf", FileMode.Create));
#region 設定PDF的頭資訊,一些屬性設定,在Document.Open 之前完成
doc.AddAuthor("作者幻想Zerow");
doc.AddCreationDate();
doc.AddCreator("建立人幻想Zerow");
doc.AddSubject("Dot Net 使用 itextsharp 類庫建立PDF檔案的例子");
doc.AddTitle("此PDF由幻想Zerow建立,嘿嘿");
doc.AddKeywords("ASP.NET,PDF,iTextSharp,幻想Zerow");
//自訂頭
doc.AddHeader("Expires", "0");
#endregion //開啟document
doc.Open();
//載入字型
BaseFont.AddToResourceSearch("iTextAsian.dll");
BaseFont.AddToResourceSearch("iTextAsianCmaps.dll");
//"UniGB-UCS2-H" "UniGB-UCS2-V"是簡體中文,分別表示橫向字 和 // 縱向字 //" STSong-Light"是字型名稱
BaseFont baseFT = BaseFont.CreateFont(@"c:\windows\fonts\SIMHEI.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
iTextSharp.text.Font font = new iTextSharp.text.Font(baseFT); //寫入一個段落, Paragraph
doc.Add(new Paragraph("您好, PDF !", font));
//關閉document
doc.Close();
//開啟PDF,看效果
Process.Start("D:\\Hello.pdf");
}
catch (DocumentException de) { Console.WriteLine(de.Message); Console.ReadKey(); }
catch (IOException io) { Console.WriteLine(io.Message); Console.ReadKey(); }
}