C# 中使用iTextSharp組件建立PDF的簡單方法

來源:互聯網
上載者:User

將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(); }
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.