[itextsharp][000]建立第一個HelloWorld的Pdf

[itextsharp][000]建立第一個HelloWorld的Pdf

首先要宣告一個document類別,用來宣告一個pdf檔案的大小,這裡的紙張大小是以A4為例,A4的尺寸為寬度210公分長度297公分,換算成Rectangle的單位的話是593f,842f,可依照自己的需要字型換算:

Document doc = new Document(new iTextSharp.text.Rectangle(593f, 842f), 0, 0, 0, 0);

然後利用PdfWriter類別來設定pdf檔案所在的路徑:

PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(path + "HelloWorld.pdf", FileMode.Create));

然後利用Paragraph類別簡單的新增一段文字(這個類別預設會換行喔!)

doc.Add(new Paragraph("Hello World!"));

完整程式碼如下:

Document doc = new Document(new iTextSharp.text.Rectangle(593f, 842f), 0, 0, 0, 0);
string path = Application.StartupPath + "\\ch1\\";
if(Directory.Exists(path) == false)
{
	Directory.CreateDirectory(path);
}
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(path + "HelloWorld.pdf", FileMode.Create));
doc.Open();
doc.Add(new Paragraph("Hello World!"));
doc.Close();		

最後執行出來的結果:

附註:

iTextSharp_4_1_6的dll測試結果:

程式碼都一樣不用改

輸出pdf結果一樣

 

本文使用iTextSharp版本:5.5.8