日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > C# >内容正文

C#

.NET的那些事儿(9)——C# 2.0 中用iTextSharp制作PDF(基础篇) .

發布時間:2023/12/8 C# 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 .NET的那些事儿(9)——C# 2.0 中用iTextSharp制作PDF(基础篇) . 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

該文主要介紹如何借助iTextSharp在C# 2.0中制作PDF文件,本文的架構大致按照iTextSharp的操作文檔進行翻譯,如果需要查看原文,請點擊一下鏈接:http://itextsharp.sourceforge.net/tutorial/

一、?iTextSharp的介紹和下載

(1)用戶可以瀏覽官網進行查看:http://itextsharp.sourceforge.net/index.html

iText# (iTextSharp) is a port of the iText open source java library written entirely in C# for the .NET platform. iText# is a library that allows you to generate PDF files on the fly. It is implemented as an assembly.

(2)以下鏈接用于下載:http://sourceforge.net/project/platformdownload.php?group_id=72954

下載后為一個解壓縮文件,用戶直接解壓后得到一個dll動態鏈接庫,在創建的項目中直接引入即可使用(本文的所有代碼均在VS 2005環境下測試通過

二、創建一個PDF文檔(原文:http://itextsharp.sourceforge.net/tutorial/ch01.html

2.1 示例代碼分析

創建一個PDF文檔大致包括五個步驟,代碼如下:

[c-sharp] view plaincopyprint?
  • using?System;??
  • using?System.Collections.Generic;??
  • using?System.Text;??
  • using?iTextSharp.text;??
  • using?iTextSharp.text.pdf;??
  • using?System.IO;??
  • ??
  • namespace?MakePDF??
  • {??
  • ????class?Program??
  • ????{??
  • ????????static?void?Main(string[]?args)??
  • ????????{??
  • ????????????Console.WriteLine("Chapter?1?example?1:?Hello?World");??
  • ??
  • ????????????//?step?1:?創建Document對象 ??
  • ????????????Document?document?=?new?Document();??
  • ??
  • ????????????try??
  • ????????????{??
  • ??????????????????
  • ???????????????//step?2:創建一個writer用于監聽Document以及通過PDF-stream指向一個文件 ??
  • ??
  • ????????????????PdfWriter.GetInstance(document,?new?FileStream("Chap0101.pdf",?FileMode.Create));??????????????????
  • ??
  • ??
  • ????????????????//?step?3:?打開document ??
  • ????????????????document.Open();??
  • ??
  • ????????????????//?step?4:?添加一段話到document中 ??
  • ????????????????document.Add(new?Paragraph("Hello?World?PDF"));??
  • ??
  • ????????????}??
  • ????????????catch?(DocumentException?de)??
  • ????????????{??
  • ????????????????Console.Error.WriteLine(de.Message);??
  • ????????????}??
  • ????????????catch?(IOException?ioe)??
  • ????????????{??
  • ????????????????Console.Error.WriteLine(ioe.Message);??
  • ????????????}??
  • ??
  • ????????????//?step?5:?關閉document ??
  • ????????????document.Close();??
  • ??
  • ????????????Console.Read();??
  • ??
  • ????????}??
  • ????}??
  • }??
  • using System; using System.Collections.Generic; using System.Text; using iTextSharp.text; using iTextSharp.text.pdf; using System.IO; namespace MakePDF { class Program { static void Main(string[] args) { Console.WriteLine("Chapter 1 example 1: Hello World"); // step 1: 創建Document對象 Document document = new Document(); try { //step 2:創建一個writer用于監聽Document以及通過PDF-stream指向一個文件 PdfWriter.GetInstance(document, new FileStream("Chap0101.pdf", FileMode.Create)); // step 3: 打開document document.Open(); // step 4: 添加一段話到document中 document.Add(new Paragraph("Hello World PDF")); } catch (DocumentException de) { Console.Error.WriteLine(de.Message); } catch (IOException ioe) { Console.Error.WriteLine(ioe.Message); } // step 5: 關閉document document.Close(); Console.Read(); } } }

    ?

    該段代碼的效果是可以在當前工作目錄下,生成一個名字叫做Chap0101.pdf的PDF文檔

    2.2 第一步:創建Document對象

    (1) Document對象

    iTextSharp.text.Document有三個構造函數,分別為:

    [c-sharp] view plaincopyprint?
  • public?Document();??
  • public?Document(Rectangle?pageSize);??
  • public?Document(Rectangle?pageSize,??
  • ???int?marginLeft,??
  • ???int?marginRight,??
  • ???int?marginTop,??
  • ???int?marginBottom);??
  • public Document(); public Document(Rectangle pageSize); public Document(Rectangle pageSize, int marginLeft, int marginRight, int marginTop, int marginBottom);

    ?

    第一個構造函數調用第二個構造函數,參數為PageSize.A4

    第二個構造函數調用第三個構造函數,其中每個邊距默認值為36

    (2) Page Size

    你可以創建自己的用于特定顏色的Rectangle對象,并將其作為pageSize。我們對前面的代碼進行修改,即創建一個長的、窄的、背景顏色為淡黃色的PDF文檔。代碼如下:

    [c-sharp] view plaincopyprint?
  • using?System;??
  • using?System.Collections.Generic;??
  • using?System.Text;??
  • using?iTextSharp.text;??
  • using?iTextSharp.text.pdf;??
  • using?System.IO;??
  • ??
  • namespace?MakePDF??
  • {??
  • ????class?Program??
  • ????{??
  • ????????static?void?Main(string[]?args)??
  • ????????{??
  • ????????????Console.WriteLine("Chapter?1?example?1:?Hello?World");??
  • ??
  • ????????????//?step?1:?creation?of?a?document-object ??
  • ????????????Rectangle?pageSize?=?new?Rectangle(144,?720);??
  • ????????????pageSize.BackgroundColor?=?new?Color(0xFF,?0xFF,?0xDE);??
  • ????????????Document?document?=?new?Document(pageSize);??
  • ????????????//iTextSharp.text.Document?document?=?new?Document(); ??
  • ??
  • ????????????try??
  • ????????????{??
  • ??
  • ????????????????//?step?2: ??
  • ????????????????//?we?create?a?writer?that?listens?to?the?document ??
  • ????????????????//?and?directs?a?PDF-stream?to?a?file ??
  • ??
  • ????????????????PdfWriter.GetInstance(document,?new?FileStream("Chap0101.pdf",?FileMode.Create));??????????????????
  • ??
  • ??
  • ????????????????//?step?3:?we?open?the?document ??
  • ????????????????document.Open();??
  • ??
  • ????????????????//?step?4:?we?Add?a?paragraph?to?the?document ??
  • ????????????????document.Add(new?Paragraph("Hello?World?PDF"));??
  • ??
  • ????????????}??
  • ????????????catch?(DocumentException?de)??
  • ????????????{??
  • ????????????????Console.Error.WriteLine(de.Message);??
  • ????????????}??
  • ????????????catch?(IOException?ioe)??
  • ????????????{??
  • ????????????????Console.Error.WriteLine(ioe.Message);??
  • ????????????}??
  • ??
  • ????????????//?step?5:?we?close?the?document ??
  • ????????????document.Close();??
  • ??
  • ????????????Console.Read();??
  • ??
  • ????????}??
  • ????}??
  • }??
  • using System; using System.Collections.Generic; using System.Text; using iTextSharp.text; using iTextSharp.text.pdf; using System.IO; namespace MakePDF { class Program { static void Main(string[] args) { Console.WriteLine("Chapter 1 example 1: Hello World"); // step 1: creation of a document-object Rectangle pageSize = new Rectangle(144, 720); pageSize.BackgroundColor = new Color(0xFF, 0xFF, 0xDE); Document document = new Document(pageSize); //iTextSharp.text.Document document = new Document(); try { // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter.GetInstance(document, new FileStream("Chap0101.pdf", FileMode.Create)); // step 3: we open the document document.Open(); // step 4: we Add a paragraph to the document document.Add(new Paragraph("Hello World PDF")); } catch (DocumentException de) { Console.Error.WriteLine(de.Message); } catch (IOException ioe) { Console.Error.WriteLine(ioe.Message); } // step 5: we close the document document.Close(); Console.Read(); } } }

    ?

    大多pageSizes都是采用了PORTRAIT格式,如果你想在LANDSCAPE應用它們,你必須使用rotate(),代碼如下:

    [c-sharp] view plaincopyprint?
  • Document?document?=?new?Document(PageSize.A4.rotate());???
  • Document document = new Document(PageSize.A4.rotate());

    ?

    (3) Margins

    在創建document的過程中,你也可以定義左、右、上、下邊距,代碼如下所示:

    [c-sharp] view plaincopyprint?
  • Document?document?=?new?Document(PageSize.A5,?36,?72,?108,?180);???
  • Document document = new Document(PageSize.A5, 36, 72, 108, 180);

    ?

    注意:如果你修改pageSize,會在下一個頁面創建時產生影響;如果你修改margins,則會在當前頁面立即產生影響。

    2.3 創建Write對象

    一旦成功創建了document,我們必須創建一個或者多個實例用于監聽document,所有的writers繼承于iTextSharp.text.DocWriter類。即你可以iTextSharp.text.pdf.PdfWriter使用來生成PDF文檔,而如果需要生成Tex文檔你必須使用iTextSharp.text.TeX.TeXWriter。

    你可以使用以下的方式創建實例:

    [c-sharp] view plaincopyprint?
  • PdfWriter?writer?=?PdfWriter.getInstance(document,?new?FileStream("Chap01xx.pdf"));??
  • PdfWriter writer = PdfWriter.getInstance(document, new FileStream("Chap01xx.pdf"));

    ?

    在使用過程中,你幾乎不會使用到writer對象(除了你想創建高級的PDF文件或者你想使用一些特定的函數,比如ViewerPreferences或者Encryption),所以獲取這類實例就足夠了。

    該函數的第一個參數即第一步所創建的document對象;

    第二個參數為不同類型的Stream對象,目前我們都只使用System.IO.FileStream,后來我們會使用到System.IO.MemoryStream.?

    2.4 元數據以及打開document

    在你添加實際數據(即內容)是,你可能想加入某些關系到document的元數據,其方法如下:

    [c-sharp] view plaincopyprint?
  • public?boolean?addTitle(String?title)??
  • public?boolean?addSubject(String?subject)??
  • public?boolean?addKeywords(String?keywords)??
  • public?boolean?addAuthor(String?author)??
  • public?boolean?addCreator(String?creator)??
  • public?boolean?addProducer()??
  • public?boolean?addCreationDate()??
  • public?boolean?addHeader(String?name,?String?content)??
  • public boolean addTitle(String title) public boolean addSubject(String subject) public boolean addKeywords(String keywords) public boolean addAuthor(String author) public boolean addCreator(String creator) public boolean addProducer() public boolean addCreationDate() public boolean addHeader(String name, String content)

    ?

    你可以選擇自己的Title,Subject,Keywords,Author以及Creator,但是添加制作者的函數必須一直使用,以及添加創建時間的方法添加的當前系統的時間(事實上,這兩個方法是被自動調用的),你可以用客戶的姓名作為Header,但是這對于PdfWrite沒有任何影響。

    2.5 添加內容

    1、在前面的三個步驟中,你遇到了諸如:Phrase,Paragraph…的對象,在以后的章節會詳細的給予介紹。有些時候,你可能希望writer可以忽略document中的行為,相關的代碼可以查看

    2、如果你想創建兩個writer:writerA和writerB(這個代碼在第二步會丟出異常)

    [c-sharp] view plaincopyprint?
  • PdfWriter?writerA?=?PdfWriter.getInstance(document,?new?FileStream("Chap0111a.pdf",?FileMode.Create));??
  • PdfWriter?writerB?=?PdfWriter.getInstance(document,?new?FileStream("Chap0111b.pdf",?FileMode.Create));??
  • PdfWriter writerA = PdfWriter.getInstance(document, new FileStream("Chap0111a.pdf", FileMode.Create)); PdfWriter writerB = PdfWriter.getInstance(document, new FileStream("Chap0111b.pdf", FileMode.Create));

    ?

    實際上,我們需要對其進行簡單的修改,修改后的代碼如下:

    [c-sharp] view plaincopyprint?
  • writerA.Pause();??
  • document.add(new?Paragraph("This?paragraph?will?only?be?added?to?Chap0111b.pdf,?not?to?Chap0111a.pdf"));??
  • writerA.resume();??
  • writerA.Pause(); document.add(new Paragraph("This paragraph will only be added to Chap0111b.pdf, not to Chap0111a.pdf")); writerA.resume();

    ?

    2.6 關閉document

    關閉document相當重要,因為它會影響和關閉writer寫的輸出流,close方法為finalize方法,但是你不能依靠它,你必須手工對其進行關閉。

    三、Chunks, Phrases 和Paragraphs(原文http://itextsharp.sourceforge.net/tutorial/ch02.html)

    3.1 Chunk

    Chunk是能夠添加到document文本中最小的重要部分。Chunk能夠為其他的元素諸如Phrase以及Paragrph等構建塊,一個Chunk就是一個附有指定字體的字符串,在添加chunk的文本的對象中,所有其他的版面設計參數都應該定義。

    下面的代碼表示我們創建內容為"Hello world"格式為(red, italic COURIER font of size 20)的Chunk:

    [c-sharp] view plaincopyprint?
  • Chunk?chunk?=?new?Chunk("Hello?world",?FontFactory.getFont(FontFactory.COURIER,?20,?Font.ITALIC,?new?Color(255,?0,?0)));??
  • Chunk chunk = new Chunk("Hello world", FontFactory.getFont(FontFactory.COURIER, 20, Font.ITALIC, new Color(255, 0, 0)));

    ?

    ?

    ?

    ?

    3.2 Phrases

    ?

    Phrases是一系列擁有特定的作為額外參數的leading(=兩行之間的空間)的Chunk

    Phrases擁有一個主字體,但是其他的chunks可以擁有不同于這個主字體的其余字體,你可以從多種構造函數中創建Phrases對象。代碼如下:

    [c-sharp] view plaincopyprint?
  • using?System;??
  • using?System.IO;??
    • ??
    • using?iTextSharp.text;??
    • using?iTextSharp.text.pdf;??
    • ??
    • public?class?Chap0202??
    • {??
    • ??
    • ????public?static?void?Main()??
    • ????{??
    • ??
    • ????????Console.WriteLine("Chapter?2?example?2:?Phrases");??
    • ??
    • ????????//?step?1:?creation?of?a?document-object ??
    • ????????Document?document?=?new?Document();??
    • ??
    • ????????try??
    • ????????{??
    • ??
    • ????????????//?step?2: ??
    • ????????????//?we?create?a?writer?that?listens?to?the?document ??
    • ????????????//?and?directs?a?PDF-stream?to?a?file ??
    • ????????????PdfWriter.GetInstance(document,?new?FileStream("Chap0202.pdf",?FileMode.Create));??
    • ??
    • ????????????//?step?3:?we?open?the?document ??
    • ????????????document.Open();??
    • ??
    • ????????????//?step?4:?we?Add?a?paragraph?to?the?document ??
    • ????????????Phrase?phrase0?=?new?Phrase();??
    • ????????????Phrase?phrase1?=?new?Phrase("(1)?this?is?a?phrase/n");??
    • ????????????//?In?this?example?the?leading?is?passed?as?a?parameter ??
    • ????????????Phrase?phrase2?=?new?Phrase(24,?"(2)?this?is?a?phrase?with?leading?24.?You?can?only?see?the?difference?if?the?line?is?long?enough.?Do?you?see?it??There?is?more?space?between?this?line?and?the?previous?one./n");??
    • ????????????//?When?a?Font?is?passed?(explicitely?or?embedded?in?a?chunk), ??
    • ????????????//?the?default?leading?=?1.5?*?size?of?the?font ??
    • ????????????Phrase?phrase3?=?new?Phrase("(3)?this?is?a?phrase?with?a?red,?normal?font?Courier,?size?20.?As?you?can?see?the?leading?is?automatically?changed./n",?FontFactory.GetFont(FontFactory.COURIER,?20,?Font.NORMAL,?new?Color(255,?0,?0)));??
    • ????????????Phrase?phrase4?=?new?Phrase(new?Chunk("(4)?this?is?a?phrase/n"));??
    • ????????????Phrase?phrase5?=?new?Phrase(18,?new?Chunk("(5)?this?is?a?phrase?in?Helvetica,?bold,?red?and?size?16?with?a?given?leading?of?18?points./n",?FontFactory.GetFont(FontFactory.HELVETICA,?16,?Font.BOLD,?new?Color(255,?0,?0))));??
    • ????????????//?A?Phrase?can?contains?several?chunks?with?different?fonts ??
    • ????????????Phrase?phrase6?=?new?Phrase("(6)");??
    • ????????????Chunk?chunk?=?new?Chunk("?This?is?a?font:?");??
    • ????????????phrase6.Add(chunk);??
    • ????????????phrase6.Add(new?Chunk("Helvetica",?FontFactory.GetFont(FontFactory.HELVETICA,?12)));??
    • ????????????phrase6.Add(chunk);??
    • ????????????phrase6.Add(new?Chunk("Times?New?Roman",?FontFactory.GetFont(FontFactory.TIMES_ROMAN,?12)));??
    • ????????????phrase6.Add(chunk);??
    • ????????????phrase6.Add(new?Chunk("Courier",?FontFactory.GetFont(FontFactory.COURIER,?12)));??
    • ????????????phrase6.Add(chunk);??
    • ????????????phrase6.Add(new?Chunk("Symbol",?FontFactory.GetFont(FontFactory.SYMBOL,?12)));??
    • ????????????phrase6.Add(chunk);??
    • ????????????phrase6.Add(new?Chunk("ZapfDingBats",?FontFactory.GetFont(FontFactory.ZAPFDINGBATS,?12)));??
    • ????????????Phrase?phrase7?=?new?Phrase("(7)?if?you?don't?Add?a?newline?yourself,?all?phrases?are?glued?to?eachother!");??
    • ??
    • ????????????document.Add(phrase1);??
    • ????????????document.Add(phrase2);??
    • ????????????document.Add(phrase3);??
    • ????????????document.Add(phrase4);??
    • ????????????document.Add(phrase5);??
    • ????????????document.Add(phrase6);??
    • ????????????document.Add(phrase7);??
    • ??
    • ????????}??
    • ????????catch?(DocumentException?de)??
    • ????????{??
    • ????????????Console.Error.WriteLine(de.Message);??
    • ????????}??
    • ????????catch?(IOException?ioe)??
    • ????????{??
    • ????????????Console.Error.WriteLine(ioe.Message);??
    • ????????}??
    • ??
    • ????????//?step?5:?we?close?the?document ??
    • ????????document.Close();??
    • ??
    • ????????Console.WriteLine("End");??
    • ????????Console.Read();??
    • ????}??
    • }??

    using System; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; public class Chap0202 { public static void Main() { Console.WriteLine("Chapter 2 example 2: Phrases"); // step 1: creation of a document-object Document document = new Document(); try { // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter.GetInstance(document, new FileStream("Chap0202.pdf", FileMode.Create)); // step 3: we open the document document.Open(); // step 4: we Add a paragraph to the document Phrase phrase0 = new Phrase(); Phrase phrase1 = new Phrase("(1) this is a phrase/n"); // In this example the leading is passed as a parameter Phrase phrase2 = new Phrase(24, "(2) this is a phrase with leading 24. You can only see the difference if the line is long enough. Do you see it? There is more space between this line and the previous one./n"); // When a Font is passed (explicitely or embedded in a chunk), // the default leading = 1.5 * size of the font Phrase phrase3 = new Phrase("(3) this is a phrase with a red, normal font Courier, size 20. As you can see the leading is automatically changed./n", FontFactory.GetFont(FontFactory.COURIER, 20, Font.NORMAL, new Color(255, 0, 0))); Phrase phrase4 = new Phrase(new Chunk("(4) this is a phrase/n")); Phrase phrase5 = new Phrase(18, new Chunk("(5) this is a phrase in Helvetica, bold, red and size 16 with a given leading of 18 points./n", FontFactory.GetFont(FontFactory.HELVETICA, 16, Font.BOLD, new Color(255, 0, 0)))); // A Phrase can contains several chunks with different fonts Phrase phrase6 = new Phrase("(6)"); Chunk chunk = new Chunk(" This is a font: "); phrase6.Add(chunk); phrase6.Add(new Chunk("Helvetica", FontFactory.GetFont(FontFactory.HELVETICA, 12))); phrase6.Add(chunk); phrase6.Add(new Chunk("Times New Roman", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12))); phrase6.Add(chunk); phrase6.Add(new Chunk("Courier", FontFactory.GetFont(FontFactory.COURIER, 12))); phrase6.Add(chunk); phrase6.Add(new Chunk("Symbol", FontFactory.GetFont(FontFactory.SYMBOL, 12))); phrase6.Add(chunk); phrase6.Add(new Chunk("ZapfDingBats", FontFactory.GetFont(FontFactory.ZAPFDINGBATS, 12))); Phrase phrase7 = new Phrase("(7) if you don't Add a newline yourself, all phrases are glued to eachother!"); document.Add(phrase1); document.Add(phrase2); document.Add(phrase3); document.Add(phrase4); document.Add(phrase5); document.Add(phrase6); document.Add(phrase7); } catch (DocumentException de) { Console.Error.WriteLine(de.Message); } catch (IOException ioe) { Console.Error.WriteLine(ioe.Message); } // step 5: we close the document document.Close(); Console.WriteLine("End"); Console.Read(); } }

    ?

    ?

    3.3 Phragraph

    ?

    Phragraph是一系列的chunk或者phrase.跟phrase類似,Phragraph也有特定的leading,用戶也可以定義特定的縮排。每個加到document的Phragraph都會自動生成新的一行。Phragraph的構造函數包括如下幾種:

    [c-sharp] view plaincopyprint?
  • Paragraph?p1?=?new?Paragraph(new?Chunk("This?is?my?first?paragraph.",?FontFactory.getFont(FontFactory.HELVETICA,?12)));??
  • Paragraph?p2?=?new?Paragraph(new?Phrase("This?is?my?second?paragraph.",?FontFactory.getFont(FontFactory.HELVETICA,?12)));??
    • Paragraph?p3?=?new?Paragraph("This?is?my?third?paragraph.",?FontFactory.getFont(FontFactory.HELVETICA,?12));???

    Paragraph p1 = new Paragraph(new Chunk("This is my first paragraph.", FontFactory.getFont(FontFactory.HELVETICA, 12))); Paragraph p2 = new Paragraph(new Phrase("This is my second paragraph.", FontFactory.getFont(FontFactory.HELVETICA, 12))); Paragraph p3 = new Paragraph("This is my third paragraph.", FontFactory.getFont(FontFactory.HELVETICA, 12));

    ?

    所有的paragraph對象還可以利用add()添加paragraph對象。代碼如下:

    [c-sharp] view plaincopyprint?
  • p1.add("you?can?add?strings,?");?p1.add(new?Chunk("you?can?add?chunks?"));?p1.add(new?Phrase("or?you?can?add?phrases."));??
  • p1.add("you can add strings, "); p1.add(new Chunk("you can add chunks ")); p1.add(new Phrase("or you can add phrases."));

    ?

    注意:每一個paragraph只能且需有一個leading,如果你想添加其他字體的phrase或者chunk,原先的leading依舊有效,你可以利用方法setLeading修改leading,但是這樣會造成所有paragraph的內容都會擁有新的leading.測試代碼如下:

    [c-sharp] view plaincopyprint?
  • using?System;??
  • using?System.IO;??
    • ??
    • using?iTextSharp.text;??
    • using?iTextSharp.text.pdf;??
    • ??
    • public?class?Chap0205??
    • {??
    • ??
    • ????public?static?void?Main()??
    • ????{??
    • ??
    • ????????Console.WriteLine("Chapter?2?example?5:?Paragraphs");??
    • ??
    • ????????//?step?1:?creation?of?a?document-object ??
    • ????????Document?document?=?new?Document();??
    • ??
    • ????????try??
    • ????????{??
    • ??
    • ????????????//?step?2: ??
    • ????????????//?we?create?a?writer?that?listens?to?the?document ??
    • ????????????//?and?directs?a?PDF-stream?to?a?file ??
    • ????????????PdfWriter.GetInstance(document,?new?FileStream("Chap0205.pdf",?FileMode.Create));??
    • ??
    • ????????????//?step?3:?we?open?the?document ??
    • ????????????document.Open();??
    • ??
    • ????????????//?step?4:?we?Add?a?paragraph?to?the?document ??
    • ????????????Paragraph?p1?=?new?Paragraph(new?Chunk("This?is?my?first?paragraph.?",??
    • ????????????????FontFactory.GetFont(FontFactory.HELVETICA,?10)));??
    • ????????????p1.Add("The?leading?of?this?paragraph?is?calculated?automagically.?");??
    • ????????????p1.Add("The?default?leading?is?1.5?times?the?fontsize.?");??
    • ????????????p1.Add(new?Chunk("You?can?Add?chunks?"));??
    • ????????????p1.Add(new?Phrase("or?you?can?Add?phrases.?"));??
    • ????????????p1.Add(new?Phrase("Unless?you?change?the?leading?with?the?method?setLeading,?the?leading?doesn't?change?if?you?Add?text?with?another?leading.?This?can?lead?to?some?problems.",?FontFactory.GetFont(FontFactory.HELVETICA,?18)));??
    • ????????????document.Add(p1);??
    • ????????????Paragraph?p2?=?new?Paragraph(new?Phrase("This?is?my?second?paragraph.?",??
    • ????????????????FontFactory.GetFont(FontFactory.HELVETICA,?12)));??
    • ????????????p2.Add("As?you?can?see,?it?started?on?a?new?line.");??
    • ????????????document.Add(p2);??
    • ????????????Paragraph?p3?=?new?Paragraph("This?is?my?third?paragraph.",??
    • ????????????????FontFactory.GetFont(FontFactory.HELVETICA,?12));??
    • ????????????document.Add(p3);??
    • ????????}??
    • ????????catch?(DocumentException?de)??
    • ????????{??
    • ????????????Console.Error.WriteLine(de.Message);??
    • ????????}??
    • ????????catch?(IOException?ioe)??
    • ????????{??
    • ????????????Console.Error.WriteLine(ioe.Message);??
    • ????????}??
    • ??
    • ????????//?step?5:?we?close?the?document ??
    • ????????document.Close();??
    • ??
    • ????????Console.WriteLine("End");??
    • ????????Console.Read();??
    • ????}??
    • }??

    using System; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; public class Chap0205 { public static void Main() { Console.WriteLine("Chapter 2 example 5: Paragraphs"); // step 1: creation of a document-object Document document = new Document(); try { // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter.GetInstance(document, new FileStream("Chap0205.pdf", FileMode.Create)); // step 3: we open the document document.Open(); // step 4: we Add a paragraph to the document Paragraph p1 = new Paragraph(new Chunk("This is my first paragraph. ", FontFactory.GetFont(FontFactory.HELVETICA, 10))); p1.Add("The leading of this paragraph is calculated automagically. "); p1.Add("The default leading is 1.5 times the fontsize. "); p1.Add(new Chunk("You can Add chunks ")); p1.Add(new Phrase("or you can Add phrases. ")); p1.Add(new Phrase("Unless you change the leading with the method setLeading, the leading doesn't change if you Add text with another leading. This can lead to some problems.", FontFactory.GetFont(FontFactory.HELVETICA, 18))); document.Add(p1); Paragraph p2 = new Paragraph(new Phrase("This is my second paragraph. ", FontFactory.GetFont(FontFactory.HELVETICA, 12))); p2.Add("As you can see, it started on a new line."); document.Add(p2); Paragraph p3 = new Paragraph("This is my third paragraph.", FontFactory.GetFont(FontFactory.HELVETICA, 12)); document.Add(p3); } catch (DocumentException de) { Console.Error.WriteLine(de.Message); } catch (IOException ioe) { Console.Error.WriteLine(ioe.Message); } // step 5: we close the document document.Close(); Console.WriteLine("End"); Console.Read(); } }

    ?

    以下的代碼我們應用方法setKeepTogether(true)來保證paragraph在一個page上,這個并不經常發生。

    [c-sharp] view plaincopyprint?
  • using?System;??
  • using?System.IO;??
    • ??
    • using?iTextSharp.text;??
    • using?iTextSharp.text.pdf;??
    • ??
    • public?class?Chap0206??
    • {??
    • ??
    • ????public?static?void?Main()??
    • ????{??
    • ??
    • ????????Console.WriteLine("Chapter?2?example?6:?keeping?a?paragraph?together");??
    • ??
    • ????????//?step?1:?creation?of?a?document-object ??
    • ????????Document?document?=?new?Document(PageSize.A6);??
    • ??
    • ????????try??
    • ????????{??
    • ??
    • ????????????//?step?2: ??
    • ????????????//?we?create?a?writer?that?listens?to?the?document ??
    • ????????????//?and?directs?a?PDF-stream?to?a?file ??
    • ????????????PdfWriter?writer?=?PdfWriter.GetInstance(document,?new?FileStream("Chap0206.pdf",?FileMode.Create));??
    • ??
    • ????????????//?step?3:?we?open?the?document ??
    • ????????????document.Open();??
    • ??
    • ????????????//?step?4: ??
    • ????????????Paragraph?p;??
    • ????????????p?=?new?Paragraph("GALLIA?est?omnis?divisa?in?partes?tres,?quarum?unam?incolunt?Belgae,?aliam?Aquitani,?tertiam?qui?ipsorum?lingua?Celtae,?nostra?Galli?appellantur.??Hi?omnes?lingua,?institutis,?legibus?inter?se?differunt.?Gallos?ab?Aquitanis?Garumna?flumen,?a?Belgis?Matrona?et?Sequana?dividit.?Horum?omnium?fortissimi?sunt?Belgae,?propterea?quod?a?cultu?atque?humanitate?provinciae?longissime?absunt,?minimeque?ad?eos?mercatores?saepe?commeant?atque?ea?quae?ad?effeminandos?animos?pertinent?important,?proximique?sunt?Germanis,?qui?trans?Rhenum?incolunt,?quibuscum?continenter?bellum?gerunt.??Qua?de?causa?Helvetii?quoque?reliquos?Gallos?virtute?praecedunt,?quod?fere?cotidianis?proeliis?cum?Germanis?contendunt,?cum?aut?suis?finibus?eos?prohibent?aut?ipsi?in?eorum?finibus?bellum?gerunt.",?FontFactory.GetFont(FontFactory.HELVETICA,?12));??
    • ????????????p.KeepTogether?=?true;??
    • ????????????document.Add(p);??
    • ????????????p?=?new?Paragraph("[Eorum?una,?pars,?quam?Gallos?obtinere?dictum?est,?initium?capit?a?flumine?Rhodano,?continetur?Garumna?flumine,?Oceano,?finibus?Belgarum,?attingit?etiam?ab?Sequanis?et?Helvetiis?flumen?Rhenum,?vergit?ad?septentriones.?Belgae?ab?extremis?Galliae?finibus?oriuntur,?pertinent?ad?inferiorem?partem?fluminis?Rheni,?spectant?in?septentrionem?et?orientem?solem.?Aquitania?a?Garumna?flumine?ad?Pyrenaeos?montes?et?eam?partem?Oceani?quae?est?ad?Hispaniam?pertinet;?spectat?inter?occasum?solis?et?septentriones.]",?FontFactory.GetFont(FontFactory.HELVETICA,?12));??
    • ????????????p.KeepTogether?=?true;??
    • ????????????document.Add(p);??
    • ????????????p?=?new?Paragraph("Apud?Helvetios?longe?nobilissimus?fuit?et?ditissimus?Orgetorix.??Is?M.?Messala,?[et?P.]?M.??Pisone?consulibus?regni?cupiditate?inductus?coniurationem?nobilitatis?fecit?et?civitati?persuasit?ut?de?finibus?suis?cum?omnibus?copiis?exirent:??perfacile?esse,?cum?virtute?omnibus?praestarent,?totius?Galliae?imperio?potiri.??Id?hoc?facilius?iis?persuasit,?quod?undique?loci?natura?Helvetii?continentur:??una?ex?parte?flumine?Rheno?latissimo?atque?altissimo,?qui?agrum?Helvetium?a?Germanis?dividit;?altera?ex?parte?monte?Iura?altissimo,?qui?est?inter?Sequanos?et?Helvetios;?tertia?lacu?Lemanno?et?flumine?Rhodano,?qui?provinciam?nostram?ab?Helvetiis?dividit.??His?rebus?fiebat?ut?et?minus?late?vagarentur?et?minus?facile?finitimis?bellum?inferre?possent;?qua?ex?parte?homines?bellandi?cupidi?magno?dolore?adficiebantur.??Pro?multitudine?autem?hominum?et?pro?gloria?belli?atque?fortitudinis?angustos?se?fines?habere?arbitrabantur,?qui?in?longitudinem?milia?passuum?CCXL,?in?latitudinem?CLXXX?patebant.",?FontFactory.GetFont(FontFactory.HELVETICA,?12));??
    • ????????????p.KeepTogether?=?true;??
    • ????????????document.Add(p);??
    • ????????????p?=?new?Paragraph("His?rebus?Adducti?et?auctoritate?Orgetorigis?permoti?constituerunt?ea?quae?ad?proficiscendum?pertinerent?comparare,?iumentorum?et?carrorum?quam?maximum?numerum?coemere,?sementes?quam?maximas?facere,?ut?in?itinere?copia?frumenti?suppeteret,?cum?proximis?civitatibus?pacem?et?amicitiam?confirmare.??Ad?eas?res?conficiendas?biennium?sibi?satis?esse?duxerunt;?in?tertium?annum?profectionem?lege?confirmant.??Ad?eas?res?conficiendas?Orgetorix?deligitur.??Is?sibi?legationem?ad?civitates?suscipit.??In?eo?itinere?persuadet?Castico,?Catamantaloedis?filio,?Sequano,?cuius?pater?regnum?in?Sequanis?multos?annos?obtinuerat?et?a?senatu?populi?Romani?amicus?appellatus?erat,?ut?regnum?in?civitate?sua?occuparet,?quod?pater?ante?habuerit;?itemque?Dumnorigi?Haeduo,?fratri?Diviciaci,?qui?eo?tempore?principatum?in?civitate?obtinebat?ac?maxime?plebi?acceptus?erat,?ut?idem?conaretur?persuadet?eique?filiam?suam?in?matrimonium?dat.??Perfacile?factu?esse?illis?probat?conata?perficere,?propterea?quod?ipse?suae?civitatis?imperium?obtenturus?esset:??non?esse?dubium?quin?totius?Galliae?plurimum?Helvetii?possent;?se?suis?copiis?suoque?exercitu?illis?regna?conciliaturum?confirmat.??Hac?oratione?Adducti?inter?se?fidem?et?ius?iurandum?dant?et?regno?occupato?per?tres?potentissimos?ac?firmissimos?populos?totius?Galliae?sese?potiri?posse?sperant.",?FontFactory.GetFont(FontFactory.HELVETICA,?12));??
    • ????????????p.KeepTogether?=?true;??
    • ????????????document.Add(p);??
    • ????????????p?=?new?Paragraph("Ea?res?est?Helvetiis?per?indicium?enuntiata.??Moribus?suis?Orgetoricem?ex?vinculis?causam?dicere?coegerunt;?damnatum?poenam?sequi?oportebat,?ut?igni?cremaretur.??Die?constituta?causae?dictionis?Orgetorix?ad?iudicium?omnem?suam?familiam,?ad?hominum?milia?decem,?undique?coegit,?et?omnes?clientes?obaeratosque?suos,?quorum?magnum?numerum?habebat,?eodem?conduxit;?per?eos?ne?causam?diceret?se?eripuit.??Cum?civitas?ob?eam?rem?incitata?armis?ius?suum?exequi?conaretur?multitudinemque?hominum?ex?agris?magistratus?cogerent,?Orgetorix?mortuus?est;?neque?abest?suspicio,?ut?Helvetii?arbitrantur,?quin?ipse?sibi?mortem?consciverit.",?FontFactory.GetFont(FontFactory.HELVETICA,?12));??
    • ????????????p.KeepTogether?=?true;??
    • ????????????document.Add(p);??
    • ??
    • ????????}??
    • ????????catch?(DocumentException?de)??
    • ????????{??
    • ????????????Console.Error.WriteLine(de.Message);??
    • ????????}??
    • ????????catch?(IOException?ioe)??
    • ????????{??
    • ????????????Console.Error.WriteLine(ioe.Message);??
    • ????????}??
    • ??
    • ????????//?step?5:?we?close?the?document ??
    • ????????document.Close();??
    • ??
    • ????????Console.Read();????
    • ????}??
    • }??

    using System; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; public class Chap0206 { public static void Main() { Console.WriteLine("Chapter 2 example 6: keeping a paragraph together"); // step 1: creation of a document-object Document document = new Document(PageSize.A6); try { // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("Chap0206.pdf", FileMode.Create)); // step 3: we open the document document.Open(); // step 4: Paragraph p; p = new Paragraph("GALLIA est omnis divisa in partes tres, quarum unam incolunt Belgae, aliam Aquitani, tertiam qui ipsorum lingua Celtae, nostra Galli appellantur. Hi omnes lingua, institutis, legibus inter se differunt. Gallos ab Aquitanis Garumna flumen, a Belgis Matrona et Sequana dividit. Horum omnium fortissimi sunt Belgae, propterea quod a cultu atque humanitate provinciae longissime absunt, minimeque ad eos mercatores saepe commeant atque ea quae ad effeminandos animos pertinent important, proximique sunt Germanis, qui trans Rhenum incolunt, quibuscum continenter bellum gerunt. Qua de causa Helvetii quoque reliquos Gallos virtute praecedunt, quod fere cotidianis proeliis cum Germanis contendunt, cum aut suis finibus eos prohibent aut ipsi in eorum finibus bellum gerunt.", FontFactory.GetFont(FontFactory.HELVETICA, 12)); p.KeepTogether = true; document.Add(p); p = new Paragraph("[Eorum una, pars, quam Gallos obtinere dictum est, initium capit a flumine Rhodano, continetur Garumna flumine, Oceano, finibus Belgarum, attingit etiam ab Sequanis et Helvetiis flumen Rhenum, vergit ad septentriones. Belgae ab extremis Galliae finibus oriuntur, pertinent ad inferiorem partem fluminis Rheni, spectant in septentrionem et orientem solem. Aquitania a Garumna flumine ad Pyrenaeos montes et eam partem Oceani quae est ad Hispaniam pertinet; spectat inter occasum solis et septentriones.]", FontFactory.GetFont(FontFactory.HELVETICA, 12)); p.KeepTogether = true; document.Add(p); p = new Paragraph("Apud Helvetios longe nobilissimus fuit et ditissimus Orgetorix. Is M. Messala, [et P.] M. Pisone consulibus regni cupiditate inductus coniurationem nobilitatis fecit et civitati persuasit ut de finibus suis cum omnibus copiis exirent: perfacile esse, cum virtute omnibus praestarent, totius Galliae imperio potiri. Id hoc facilius iis persuasit, quod undique loci natura Helvetii continentur: una ex parte flumine Rheno latissimo atque altissimo, qui agrum Helvetium a Germanis dividit; altera ex parte monte Iura altissimo, qui est inter Sequanos et Helvetios; tertia lacu Lemanno et flumine Rhodano, qui provinciam nostram ab Helvetiis dividit. His rebus fiebat ut et minus late vagarentur et minus facile finitimis bellum inferre possent; qua ex parte homines bellandi cupidi magno dolore adficiebantur. Pro multitudine autem hominum et pro gloria belli atque fortitudinis angustos se fines habere arbitrabantur, qui in longitudinem milia passuum CCXL, in latitudinem CLXXX patebant.", FontFactory.GetFont(FontFactory.HELVETICA, 12)); p.KeepTogether = true; document.Add(p); p = new Paragraph("His rebus Adducti et auctoritate Orgetorigis permoti constituerunt ea quae ad proficiscendum pertinerent comparare, iumentorum et carrorum quam maximum numerum coemere, sementes quam maximas facere, ut in itinere copia frumenti suppeteret, cum proximis civitatibus pacem et amicitiam confirmare. Ad eas res conficiendas biennium sibi satis esse duxerunt; in tertium annum profectionem lege confirmant. Ad eas res conficiendas Orgetorix deligitur. Is sibi legationem ad civitates suscipit. In eo itinere persuadet Castico, Catamantaloedis filio, Sequano, cuius pater regnum in Sequanis multos annos obtinuerat et a senatu populi Romani amicus appellatus erat, ut regnum in civitate sua occuparet, quod pater ante habuerit; itemque Dumnorigi Haeduo, fratri Diviciaci, qui eo tempore principatum in civitate obtinebat ac maxime plebi acceptus erat, ut idem conaretur persuadet eique filiam suam in matrimonium dat. Perfacile factu esse illis probat conata perficere, propterea quod ipse suae civitatis imperium obtenturus esset: non esse dubium quin totius Galliae plurimum Helvetii possent; se suis copiis suoque exercitu illis regna conciliaturum confirmat. Hac oratione Adducti inter se fidem et ius iurandum dant et regno occupato per tres potentissimos ac firmissimos populos totius Galliae sese potiri posse sperant.", FontFactory.GetFont(FontFactory.HELVETICA, 12)); p.KeepTogether = true; document.Add(p); p = new Paragraph("Ea res est Helvetiis per indicium enuntiata. Moribus suis Orgetoricem ex vinculis causam dicere coegerunt; damnatum poenam sequi oportebat, ut igni cremaretur. Die constituta causae dictionis Orgetorix ad iudicium omnem suam familiam, ad hominum milia decem, undique coegit, et omnes clientes obaeratosque suos, quorum magnum numerum habebat, eodem conduxit; per eos ne causam diceret se eripuit. Cum civitas ob eam rem incitata armis ius suum exequi conaretur multitudinemque hominum ex agris magistratus cogerent, Orgetorix mortuus est; neque abest suspicio, ut Helvetii arbitrantur, quin ipse sibi mortem consciverit.", FontFactory.GetFont(FontFactory.HELVETICA, 12)); p.KeepTogether = true; document.Add(p); } catch (DocumentException de) { Console.Error.WriteLine(de.Message); } catch (IOException ioe) { Console.Error.WriteLine(ioe.Message); } // step 5: we close the document document.Close(); Console.Read(); } }

    ?

    四、Anchor(錨)、List(列表)和Annotation(注釋)

    (原文:http://itextsharp.sourceforge.net/tutorial/ch03.html)

    ?

    4.1 Anchor

    ?

    我們都知道HTML中的超文本鏈接,只要你點擊指定的文字,你就可以跳轉到網絡中的其他頁面,這種功能在PDF中同樣存在,在后面的章節會詳細的介紹PDF中的鏈接Chapter 11,。但是這是iText的另外一種高級編程,我們這里只是介紹簡單的iText.

    如果你想添加外部的link到document中(比如用URL鏈接到網頁中的另外一個document),你可以簡單的使用Anchor對象,該對象繼承于Phrase對象,它們具有相同的使用方法,但是它還有兩個額外的方法:setName和setReference,具體的使用代碼如下:

    [c-sharp] view plaincopyprint?
  • Anchor?anchor?=?new?Anchor("website",?FontFactory.getFont(FontFactory.HELVETICA,?12,?Font.UNDERLINE,?new?Color(0,?0,?255)));??
  • anchor.Reference?=?"http://itextsharp.sourceforge.net";??
    • anchor.Name?=?"website";???

    Anchor anchor = new Anchor("website", FontFactory.getFont(FontFactory.HELVETICA, 12, Font.UNDERLINE, new Color(0, 0, 255))); anchor.Reference = "http://itextsharp.sourceforge.net"; anchor.Name = "website";

    ?

    如果你想添加內部的鏈接,你需要為鏈接選擇獨特的名字,這就像在HTML中為錨所使用的名字,當你為這個目標設定索引時,你需要在前面添加一個#符號,具體代碼如下:

    [c-sharp] view plaincopyprint?
  • Anchor?anchor1?=?new?Anchor("This?is?an?internal?link");??
  • anchor1.Name?=?"link1";??
    • Anchor?anchor2?=?new?Anchor("Click?here?to?jump?to?the?internal?link");??
    • anchor.Reference?=?"#link1";???

    Anchor anchor1 = new Anchor("This is an internal link"); anchor1.Name = "link1"; Anchor anchor2 = new Anchor("Click here to jump to the internal link"); anchor.Reference = "#link1";

    ?

    ?

    4.2 List

    利用List和ListItem類,你就可以為PDF文件添加列表了,如果你想擁有有序(ordered)列表或者無序列表(unordered)你都可以使用這兩個類。

    ?

    (1) ordered列表

    [c-sharp] view plaincopyprint?
  • List?list?=?new?List(true,?20);??
  • list.Add(new?ListItem("First?line"));??
    • list.Add(new?ListItem("The?second?line?is?longer?to?see?what?happens?once?the?end?of?the?line?is?reached.?Will?it?start?on?a?new?line?"));??
    • list.Add(new?ListItem("Third?line"));???

    List list = new List(true, 20); list.Add(new ListItem("First line")); list.Add(new ListItem("The second line is longer to see what happens once the end of the line is reached. Will it start on a new line?")); list.Add(new ListItem("Third line"));

    ?

    ?

    結果為:

    ?

    (2) 無序列表

    [c-sharp] view plaincopyprint?
  • List?overview?=?new?List(false,?10);??
  • overview.Add(new?ListItem("This?is?an?item"));??
    • overview.Add("This?is?another?item");??

    List overview = new List(false, 10); overview.Add(new ListItem("This is an item")); overview.Add("This is another item");

    ?

    結果為:

    你可以用setListSymbol方法改變列表標識符,代碼如下所示:

    [c-sharp] view plaincopyprint?
  • //?set?a?String?as?listsymbol ??
  • list1.ListSymbol?=?"*";??
    • //?set?a?Chunk?(that?contains?the?bullet?character)?as?listsymbol ??
    • list2.ListSymbol?=?new?Chunk("/u2022",?FontFactory.getFont(FontFactory.HELVETICA,?20));??
    • //?set?an?Images?wrapped?in?a?Chunk?as?listsymbol ??
    • list3.ListSymbol?=?new?Chunk(Image.getInstance("myBullet.gif"),?0,?0);??

    // set a String as listsymbol list1.ListSymbol = "*"; // set a Chunk (that contains the bullet character) as listsymbol list2.ListSymbol = new Chunk("/u2022", FontFactory.getFont(FontFactory.HELVETICA, 20)); // set an Images wrapped in a Chunk as listsymbol list3.ListSymbol = new Chunk(Image.getInstance("myBullet.gif"), 0, 0);

    ?

    還有一些方法用于改變列表的縮排:setIndentationLeft?和?setIndentationRight.

    而列表符的縮排可以在構造函數中給予設定,參考代碼如下:

    [c-sharp] view plaincopyprint?
  • using?System;??
  • using?System.IO;??
    • ??
    • using?iTextSharp.text;??
    • using?iTextSharp.text.pdf;??
    • ??
    • public?class?Chap0302?{??
    • ??????
    • ????public?static?void?Main()?{??
    • ??????????
    • ????????Console.WriteLine("Chapter?3?example?2:?Lists");??
    • ??????????
    • ????????//?step?1:?creation?of?a?document-object ??
    • ????????Document?document?=?new?Document();??
    • ??????????
    • ????????try?{??
    • ??????????????
    • ????????????//?step?2: ??
    • ????????????//?we?create?a?writer?that?listens?to?the?document ??
    • ????????????//?and?directs?a?PDF-stream?to?a?file ??
    • ????????????PdfWriter.getInstance(document,?new?FileStream("Chap0302.pdf",?FileMode.Create));??
    • ??????????????
    • ????????????//?step?3:?we?Open?the?document ??
    • ????????????document.Open();??
    • ??????????????
    • ????????????//?step?4: ??
    • ??????????????
    • ????????????List?list?=?new?List(true,?20);??
    • ????????????list.Add(new?ListItem("First?line"));??
    • ????????????list.Add(new?ListItem("The?second?line?is?longer?to?see?what?happens?once?the?end?of?the?line?is?reached.?Will?it?start?on?a?new?line?"));??
    • ????????????list.Add(new?ListItem("Third?line"));??
    • ????????????document.Add(list);??
    • ??????????????
    • ????????????document.Add(new?Paragraph("some?books?I?really?like:"));??
    • ????????????ListItem?listItem;??
    • ????????????list?=?new?List(true,?15);??
    • ????????????listItem?=?new?ListItem("When?Harlie?was?one",?FontFactory.getFont(FontFactory.TIMES_NEW_ROMAN,?12));??
    • ????????????listItem.Add(new?Chunk("?by?David?Gerrold",?FontFactory.getFont(FontFactory.TIMES_NEW_ROMAN,?11,?Font.ITALIC)));??
    • ????????????list.Add(listItem);??
    • ????????????listItem?=?new?ListItem("The?World?according?to?Garp",?FontFactory.getFont(FontFactory.TIMES_NEW_ROMAN,?12));??
    • ????????????listItem.Add(new?Chunk("?by?John?Irving",?FontFactory.getFont(FontFactory.TIMES_NEW_ROMAN,?11,?Font.ITALIC)));??
    • ????????????list.Add(listItem);??
    • ????????????listItem?=?new?ListItem("Decamerone",?FontFactory.getFont(FontFactory.TIMES_NEW_ROMAN,?12));??
    • ????????????listItem.Add(new?Chunk("?by?Giovanni?Boccaccio",?FontFactory.getFont(FontFactory.TIMES_NEW_ROMAN,?11,?Font.ITALIC)));??
    • ????????????list.Add(listItem);??
    • ????????????document.Add(list);??
    • ??????????????
    • ????????????Paragraph?paragraph?=?new?Paragraph("some?movies?I?really?like:");??
    • ????????????list?=?new?List(false,?10);??
    • ????????????list.Add("Wild?At?Heart");??
    • ????????????list.Add("Casablanca");??
    • ????????????list.Add("When?Harry?met?Sally");??
    • ????????????list.Add("True?Romance");??
    • ????????????list.Add("Le?mari?de?la?coiffeuse");??
    • ????????????paragraph.Add(list);??
    • ????????????document.Add(paragraph);??
    • ??????????????
    • ????????????document.Add(new?Paragraph("Some?authors?I?really?like:"));??
    • ????????????list?=?new?List(false,?20);??
    • ????????????list.ListSymbol?=?new?Chunk("/u2022",?FontFactory.getFont(FontFactory.HELVETICA,?20,?Font.BOLD));??
    • ????????????listItem?=?new?ListItem("Isaac?Asimov");??
    • ????????????list.Add(listItem);??
    • ????????????List?sublist;??
    • ????????????sublist?=?new?List(true,?10);??
    • ????????????sublist.ListSymbol?=?new?Chunk("",?FontFactory.getFont(FontFactory.HELVETICA,?8));??
    • ????????????sublist.Add("The?Foundation?Trilogy");??
    • ????????????sublist.Add("The?Complete?Robot");??
    • ????????????sublist.Add("Caves?of?Steel");??
    • ????????????sublist.Add("The?Naked?Sun");??
    • ????????????list.Add(sublist);??
    • ????????????listItem?=?new?ListItem("John?Irving");??
    • ????????????list.Add(listItem);??
    • ????????????sublist?=?new?List(true,?10);??
    • ????????????sublist.ListSymbol?=?new?Chunk("",?FontFactory.getFont(FontFactory.HELVETICA,?8));??
    • ????????????sublist.Add("The?World?according?to?Garp");??
    • ????????????sublist.Add("Hotel?New?Hampshire");??
    • ????????????sublist.Add("A?prayer?for?Owen?Meany");??
    • ????????????sublist.Add("Widow?for?a?year");??
    • ????????????list.Add(sublist);??
    • ????????????listItem?=?new?ListItem("Kurt?Vonnegut");??
    • ????????????list.Add(listItem);??
    • ????????????sublist?=?new?List(true,?10);??
    • ????????????sublist.ListSymbol?=?new?Chunk("",?FontFactory.getFont(FontFactory.HELVETICA,?8));??
    • ????????????sublist.Add("Slaughterhouse?5");??
    • ????????????sublist.Add("Welcome?to?the?Monkey?House");??
    • ????????????sublist.Add("The?great?pianola");??
    • ????????????sublist.Add("Galapagos");??
    • ????????????list.Add(sublist);??
    • ????????????document.Add(list);??
    • ????????}??
    • ????????catch(DocumentException?de)?{??
    • ????????????Console.Error.WriteLine(de.Message);??
    • ????????}??
    • ????????catch(IOException?ioe)?{??
    • ????????????Console.Error.WriteLine(ioe.Message);??
    • ????????}??
    • ??????????
    • ????????//?step?5:?we?close?the?document ??
    • ????????document.Close();??
    • ????}??
    • }??

    using System; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; public class Chap0302 { public static void Main() { Console.WriteLine("Chapter 3 example 2: Lists"); // step 1: creation of a document-object Document document = new Document(); try { // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter.getInstance(document, new FileStream("Chap0302.pdf", FileMode.Create)); // step 3: we Open the document document.Open(); // step 4: List list = new List(true, 20); list.Add(new ListItem("First line")); list.Add(new ListItem("The second line is longer to see what happens once the end of the line is reached. Will it start on a new line?")); list.Add(new ListItem("Third line")); document.Add(list); document.Add(new Paragraph("some books I really like:")); ListItem listItem; list = new List(true, 15); listItem = new ListItem("When Harlie was one", FontFactory.getFont(FontFactory.TIMES_NEW_ROMAN, 12)); listItem.Add(new Chunk(" by David Gerrold", FontFactory.getFont(FontFactory.TIMES_NEW_ROMAN, 11, Font.ITALIC))); list.Add(listItem); listItem = new ListItem("The World according to Garp", FontFactory.getFont(FontFactory.TIMES_NEW_ROMAN, 12)); listItem.Add(new Chunk(" by John Irving", FontFactory.getFont(FontFactory.TIMES_NEW_ROMAN, 11, Font.ITALIC))); list.Add(listItem); listItem = new ListItem("Decamerone", FontFactory.getFont(FontFactory.TIMES_NEW_ROMAN, 12)); listItem.Add(new Chunk(" by Giovanni Boccaccio", FontFactory.getFont(FontFactory.TIMES_NEW_ROMAN, 11, Font.ITALIC))); list.Add(listItem); document.Add(list); Paragraph paragraph = new Paragraph("some movies I really like:"); list = new List(false, 10); list.Add("Wild At Heart"); list.Add("Casablanca"); list.Add("When Harry met Sally"); list.Add("True Romance"); list.Add("Le mari de la coiffeuse"); paragraph.Add(list); document.Add(paragraph); document.Add(new Paragraph("Some authors I really like:")); list = new List(false, 20); list.ListSymbol = new Chunk("/u2022", FontFactory.getFont(FontFactory.HELVETICA, 20, Font.BOLD)); listItem = new ListItem("Isaac Asimov"); list.Add(listItem); List sublist; sublist = new List(true, 10); sublist.ListSymbol = new Chunk("", FontFactory.getFont(FontFactory.HELVETICA, 8)); sublist.Add("The Foundation Trilogy"); sublist.Add("The Complete Robot"); sublist.Add("Caves of Steel"); sublist.Add("The Naked Sun"); list.Add(sublist); listItem = new ListItem("John Irving"); list.Add(listItem); sublist = new List(true, 10); sublist.ListSymbol = new Chunk("", FontFactory.getFont(FontFactory.HELVETICA, 8)); sublist.Add("The World according to Garp"); sublist.Add("Hotel New Hampshire"); sublist.Add("A prayer for Owen Meany"); sublist.Add("Widow for a year"); list.Add(sublist); listItem = new ListItem("Kurt Vonnegut"); list.Add(listItem); sublist = new List(true, 10); sublist.ListSymbol = new Chunk("", FontFactory.getFont(FontFactory.HELVETICA, 8)); sublist.Add("Slaughterhouse 5"); sublist.Add("Welcome to the Monkey House"); sublist.Add("The great pianola"); sublist.Add("Galapagos"); list.Add(sublist); document.Add(list); } catch(DocumentException de) { Console.Error.WriteLine(de.Message); } catch(IOException ioe) { Console.Error.WriteLine(ioe.Message); } // step 5: we close the document document.Close(); } }

    ?

    ?

    4.3 Annotation

    在iText中支持不同類型的注釋:

    (1) Text:你可以向document添加一些小塊的文本,但是這些文本并不屬于內容的一部分,Annotation有一個標題和一些內容,具體代碼如下:

    [c-sharp] view plaincopyprint?
  • Annotation?a?=?new?Annotation(??
  • ????"authors",??
  • ????"Maybe?it's?because?I?wanted?to?be?an?author?myself?that?I?wrote?iText.");???
  • Annotation a = new Annotation( "authors", "Maybe it's because I wanted to be an author myself that I wrote iText."); ??

    ?

    (2) External links(外部鏈接):你可以指定一個可被點擊的矩形或者字符串(稱為URL)或者URL對象,具體代碼如下:

    [c-sharp] view plaincopyprint?
  • Annotation?annot?=?new?Annotation(100f,?700f,?200f,?800f,?new?URL("http://www.lowagie.com"));??
  • Annotation?annot?=?new?Annotation(100f,?700f,?200f,?800f,?"http://www.lowagie.com");???
  • Annotation annot = new Annotation(100f, 700f, 200f, 800f, new URL("http://www.lowagie.com")); Annotation annot = new Annotation(100f, 700f, 200f, 800f, "http://www.lowagie.com");

    ?

    (3) External PDF file(外部PDF文件):你可以設定一個可點擊的矩形和字符串(文件名稱)和目的文件或者頁碼:

    [c-sharp] view plaincopyprint?
  • Annotation?annot?=?new?Annotation(100f,?700f,?200f,?800f,?"other.pdf",?"mark");??
  • Annotation?annot?=?new?Annotation(100f,?700f,?200f,?800f,?"other.pdf",?2);???
  • Annotation annot = new Annotation(100f, 700f, 200f, 800f, "other.pdf", "mark"); Annotation annot = new Annotation(100f, 700f, 200f, 800f, "other.pdf", 2);

    ?

    (4) Named action(指定的行為):你必須制定一個可點擊的矩形和一個指定的行為:

    [c-sharp] view plaincopyprint?
  • Annotation?annot?=?new?Annotation(100f,?700f,?200f,?800f,?PdfAction.FIRSTPAGE);???
  • Annotation annot = new Annotation(100f, 700f, 200f, 800f, PdfAction.FIRSTPAGE);

    ?

    (5) Application(應用):你必須制定一個可點擊的矩形和一個應用程序

    [c-sharp] view plaincopyprint?
  • Annotation?annot?=?new?Annotation(300f,?700f,?400f,?800f,?"C://winnt/notepad.exe",?null,?null,?null);???
  • Annotation annot = new Annotation(300f, 700f, 400f, 800f, "C://winnt/notepad.exe", null, null, null);

    ?

    ?

    5、HeaderFooters,Chapters,Sections和Graphic對象(原文:http://itextsharp.sourceforge.net/tutorial/ch04.html)

    5.1 HeaderFooter

    HeaderFooter對象是一個能夠為document的每個頁面添加footer和header的對象,這些頁眉和頁腳都包含著標準的短語和當前的頁碼(如果有需要)。如果你需要更加復雜的頁眉和頁腳(有表格或者有page X of Y),您需要閱讀12章節Chapter 12

    下面的核心代碼表示我們第一個添加一個包含頁碼但是么有任何邊界的頁眉。

    [c-sharp] view plaincopyprint?
  • HeaderFooter?footer?=?new?HeaderFooter(new?Phrase("This?is?page:?"),?true);??
  • footer.Border?=?Rectangle.NO_BORDER;??
  • document.Footer?=?footer;??
  • HeaderFooter footer = new HeaderFooter(new Phrase("This is page: "), true); footer.Border = Rectangle.NO_BORDER; document.Footer = footer;

    ?

    具體代碼如下:

    ?

    [c-sharp] view plaincopyprint?
  • using?System;??
  • using?System.IO;??
    • ??
    • using?iTextSharp.text;??
    • using?iTextSharp.text.pdf;??
    • ??
    • public?class?Chap0401??
    • {??
    • ??
    • ????public?static?void?Main()??
    • ????{??
    • ??
    • ????????Console.WriteLine("Chapter?4?example?1:?Headers?en?Footers");??
    • ??
    • ????????//?step?1:?creation?of?a?document-object ??
    • ????????Document?document?=?new?Document();??
    • ??
    • ????????try??
    • ????????{??
    • ????????????//?step?2:?we?create?a?writer?that?listens?to?the?document ??
    • ????????????PdfWriter.GetInstance(document,?new?FileStream("Chap0401.pdf",?FileMode.Create));??
    • ??
    • ????????????//?we?Add?a?Footer?that?will?show?up?on?PAGE?1 ??
    • ????????????HeaderFooter?footer?=?new?HeaderFooter(new?Phrase("This?is?page:?"),?true);??
    • ????????????footer.Border?=?Rectangle.NO_BORDER;??
    • ????????????document.Footer?=?footer;??
    • ??
    • ????????????//?step?3:?we?open?the?document ??
    • ????????????document.Open();??
    • ??
    • ????????????//?we?Add?a?Header?that?will?show?up?on?PAGE?2 ??
    • ????????????HeaderFooter?header?=?new?HeaderFooter(new?Phrase("This?is?a?header"),?false);??
    • ????????????document.Header?=?header;??
    • ??
    • ????????????//?step?4:?we?Add?content?to?the?document ??
    • ??
    • ????????????//?PAGE?1 ??
    • ????????????document.Add(new?Paragraph("Hello?World"));??
    • ????????????//?we?trigger?a?page?break ??
    • ????????????document.NewPage();??
    • ??
    • ????????????//?PAGE?2 ??
    • ????????????//?we?Add?some?more?content ??
    • ????????????document.Add(new?Paragraph("Hello?Earth"));??
    • ????????????//?we?remove?the?header?starting?from?PAGE?3 ??
    • ????????????document.ResetHeader();??
    • ????????????//?we?trigger?a?page?break ??
    • ????????????document.NewPage();??
    • ??
    • ????????????//?PAGE?3 ??
    • ????????????//?we?Add?some?more?content ??
    • ????????????document.Add(new?Paragraph("Hello?Sun"));??
    • ????????????document.Add(new?Paragraph("Remark:?the?header?has?vanished!"));??
    • ????????????//?we?reset?the?page?numbering ??
    • ????????????document.ResetPageCount();??
    • ????????????//?we?trigger?a?page?break ??
    • ????????????document.NewPage();??
    • ??
    • ????????????//?PAGE?4 ??
    • ????????????//?we?Add?some?more?content ??
    • ????????????document.Add(new?Paragraph("Hello?Moon"));??
    • ????????????document.Add(new?Paragraph("Remark:?the?pagenumber?has?been?reset!"));??
    • ??
    • ????????}??
    • ????????catch?(DocumentException?de)??
    • ????????{??
    • ????????????Console.Error.WriteLine(de.Message);??
    • ????????}??
    • ????????catch?(IOException?ioe)??
    • ????????{??
    • ????????????Console.Error.WriteLine(ioe.Message);??
    • ????????}??
    • ??
    • ????????//?step?5:?we?close?the?document ??
    • ????????document.Close();??
    • ??
    • ????????Console.Read();??
    • ????}??
    • }??

    using System; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; public class Chap0401 { public static void Main() { Console.WriteLine("Chapter 4 example 1: Headers en Footers"); // step 1: creation of a document-object Document document = new Document(); try { // step 2: we create a writer that listens to the document PdfWriter.GetInstance(document, new FileStream("Chap0401.pdf", FileMode.Create)); // we Add a Footer that will show up on PAGE 1 HeaderFooter footer = new HeaderFooter(new Phrase("This is page: "), true); footer.Border = Rectangle.NO_BORDER; document.Footer = footer; // step 3: we open the document document.Open(); // we Add a Header that will show up on PAGE 2 HeaderFooter header = new HeaderFooter(new Phrase("This is a header"), false); document.Header = header; // step 4: we Add content to the document // PAGE 1 document.Add(new Paragraph("Hello World")); // we trigger a page break document.NewPage(); // PAGE 2 // we Add some more content document.Add(new Paragraph("Hello Earth")); // we remove the header starting from PAGE 3 document.ResetHeader(); // we trigger a page break document.NewPage(); // PAGE 3 // we Add some more content document.Add(new Paragraph("Hello Sun")); document.Add(new Paragraph("Remark: the header has vanished!")); // we reset the page numbering document.ResetPageCount(); // we trigger a page break document.NewPage(); // PAGE 4 // we Add some more content document.Add(new Paragraph("Hello Moon")); document.Add(new Paragraph("Remark: the pagenumber has been reset!")); } catch (DocumentException de) { Console.Error.WriteLine(de.Message); } catch (IOException ioe) { Console.Error.WriteLine(ioe.Message); } // step 5: we close the document document.Close(); Console.Read(); } }

    ?

    ?

    我們也可以用一下的構造函數:

    [c-sharp] view plaincopyprint?
  • HeaderFooter?footer?=?new?HeaderFooter(new?Phrase("This?is?page?"),?new?Phrase("."));??
  • HeaderFooter footer = new HeaderFooter(new Phrase("This is page "), new Phrase("."));

    ?

    如果你設置HeadFooter對象沒有改變邊界,頁眉或者頁腳會在文本的上下有一條線。

    [c-sharp] view plaincopyprint?
  • HeaderFooter?header?=?new?HeaderFooter(new?Phrase("This?is?a?header?without?a?page?number"),?false);??
  • document.Header?=?header;??
  • HeaderFooter header = new HeaderFooter(new Phrase("This is a header without a page number"), false); document.Header = header;

    ?

    5.2 Chapters和Section

    ?

    十一章(Chapter 11 本文的12節)描述了如何創建大綱樹,如果你只是需要附有一些章節或者子段的簡單的樹,你可以利用Chapter和Section類來自動創建,核心代碼如下:

    [c-sharp] view plaincopyprint?
  • Paragraph?cTitle?=?new?Paragraph("This?is?chapter?1",?chapterFont);??
  • Chapter?chapter?=?new?Chapter(cTitle,?1);??
    • Paragraph?sTitle?=?new?Paragraph("This?is?section?1?in?chapter?1",?sectionFont);??
    • Section?section?=?chapter.addSection(sTitle,?1);??

    Paragraph cTitle = new Paragraph("This is chapter 1", chapterFont); Chapter chapter = new Chapter(cTitle, 1); Paragraph sTitle = new Paragraph("This is section 1 in chapter 1", sectionFont); Section section = chapter.addSection(sTitle, 1);

    ?

    下面的代碼,我們添加一系列的章節和子章節,運行程序后,你可以查看到PDF文件擁有完整的大綱樹,這個大綱樹被默認打開,如果你想使得有一部大綱關閉,你可以把BookmarkOpen屬性設置為false.

    [c-sharp] view plaincopyprint?
  • using?System;??
  • using?System.IO;??
    • ??
    • using?iTextSharp.text;??
    • using?iTextSharp.text.pdf;??
    • ??
    • public?class?Chap0402??
    • {??
    • ??
    • ????public?static?void?Main()??
    • ????{??
    • ??
    • ????????Console.WriteLine("Chapter?4?example?2:?Chapters?and?Sections");??
    • ??
    • ????????//?step?1:?creation?of?a?document-object ??
    • ????????Document?document?=?new?Document(PageSize.A4,?50,?50,?50,?50);??
    • ????????try??
    • ????????{??
    • ????????????//?step?2:?we?create?a?writer?that?listens?to?the?document ??
    • ????????????PdfWriter?writer?=?PdfWriter.GetInstance(document,?new?FileStream("Chap0402.pdf",?FileMode.Create));??
    • ????????????//?step?3:?we?open?the?document ??
    • ????????????document.Open();??
    • ????????????//?step?4:?we?Add?content?to?the?document ??
    • ????????????//?we?define?some?fonts ??
    • ????????????Font?chapterFont?=?FontFactory.GetFont(FontFactory.HELVETICA,?24,?Font.NORMAL,?new?Color(255,?0,?0));??
    • ????????????Font?sectionFont?=?FontFactory.GetFont(FontFactory.HELVETICA,?20,?Font.NORMAL,?new?Color(0,?0,?255));??
    • ????????????Font?subsectionFont?=?FontFactory.GetFont(FontFactory.HELVETICA,?18,?Font.BOLD,?new?Color(0,?64,?64));??
    • ????????????//?we?create?some?paragraphs ??
    • ????????????Paragraph?blahblah?=?new?Paragraph("blah?blah?blah?blah?blah?blah?blaah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah");??
    • ????????????Paragraph?blahblahblah?=?new?Paragraph("blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blaah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah?blah");??
    • ????????????//?this?loop?will?create?7?chapters ??
    • ????????????for?(int?i?=?1;?i?<?8;?i++)??
    • ????????????{??
    • ????????????????Paragraph?cTitle?=?new?Paragraph("This?is?chapter?"?+?i,?chapterFont);??
    • ????????????????Chapter?chapter?=?new?Chapter(cTitle,?i);??
    • ??
    • ????????????????if?(i?==?4)??
    • ????????????????{??
    • ????????????????????blahblahblah.Alignment?=?Element.ALIGN_JUSTIFIED;??
    • ????????????????????blahblah.Alignment?=?Element.ALIGN_JUSTIFIED;??
    • ????????????????????chapter.Add(blahblah);??
    • ????????????????}??
    • ????????????????if?(i?==?5)??
    • ????????????????{??
    • ????????????????????blahblahblah.Alignment?=?Element.ALIGN_CENTER;??
    • ????????????????????blahblah.Alignment?=?Element.ALIGN_RIGHT;??
    • ????????????????????chapter.Add(blahblah);??
    • ????????????????}??
    • ????????????????//?Add?a?table?in?the?6th?chapter ??
    • ????????????????if?(i?==?6)??
    • ????????????????{??
    • ????????????????????blahblah.Alignment?=?Element.ALIGN_JUSTIFIED;??
    • ????????????????}??
    • ????????????????//?in?every?chapter?3?sections?will?be?Added ??
    • ????????????????for?(int?j?=?1;?j?<?4;?j++)??
    • ????????????????{??
    • ????????????????????Paragraph?sTitle?=?new?Paragraph("This?is?section?"?+?j?+?"?in?chapter?"?+?i,?sectionFont);??
    • ????????????????????Section?section?=?chapter.AddSection(sTitle,?1);??
    • ????????????????????//?in?all?chapters?except?the?1st?one,?some?extra?text?is?Added?to?section?3 ??
    • ????????????????????if?(j?==?3?&&?i?>?1)??
    • ????????????????????{??
    • ????????????????????????section.Add(blahblah);??
    • ????????????????????}??
    • ????????????????????//?in?every?section?3?subsections?are?Added ??
    • ????????????????????for?(int?k?=?1;?k?<?4;?k++)??
    • ????????????????????{??
    • ????????????????????????Paragraph?subTitle?=?new?Paragraph("This?is?subsection?"?+?k?+?"?of?section?"?+?j,?subsectionFont);??
    • ????????????????????????Section?subsection?=?section.AddSection(subTitle,?3);??
    • ????????????????????????if?(k?==?1?&&?j?==?3)??
    • ????????????????????????{??
    • ????????????????????????????subsection.Add(blahblahblah);??
    • ????????????????????????}??
    • ????????????????????????subsection.Add(blahblah);??
    • ????????????????????}??
    • ????????????????????if?(j?==?2?&&?i?>?2)??
    • ????????????????????{??
    • ????????????????????????section.Add(blahblahblah);??
    • ????????????????????}??
    • ????????????????}??
    • ????????????????document.Add(chapter);??
    • ????????????}??
    • ????????}??
    • ????????catch?(Exception?de)??
    • ????????{??
    • ????????????Console.Error.WriteLine(de.StackTrace);??
    • ????????}??
    • ????????//?step?5:?we?close?the?document ??
    • ????????document.Close();??
    • ??
    • ????????Console.Read();??
    • ????}??
    • }??

    using System; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; public class Chap0402 { public static void Main() { Console.WriteLine("Chapter 4 example 2: Chapters and Sections"); // step 1: creation of a document-object Document document = new Document(PageSize.A4, 50, 50, 50, 50); try { // step 2: we create a writer that listens to the document PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("Chap0402.pdf", FileMode.Create)); // step 3: we open the document document.Open(); // step 4: we Add content to the document // we define some fonts Font chapterFont = FontFactory.GetFont(FontFactory.HELVETICA, 24, Font.NORMAL, new Color(255, 0, 0)); Font sectionFont = FontFactory.GetFont(FontFactory.HELVETICA, 20, Font.NORMAL, new Color(0, 0, 255)); Font subsectionFont = FontFactory.GetFont(FontFactory.HELVETICA, 18, Font.BOLD, new Color(0, 64, 64)); // we create some paragraphs Paragraph blahblah = new Paragraph("blah blah blah blah blah blah blaah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah"); Paragraph blahblahblah = new Paragraph("blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blaah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah"); // this loop will create 7 chapters for (int i = 1; i < 8; i++) { Paragraph cTitle = new Paragraph("This is chapter " + i, chapterFont); Chapter chapter = new Chapter(cTitle, i); if (i == 4) { blahblahblah.Alignment = Element.ALIGN_JUSTIFIED; blahblah.Alignment = Element.ALIGN_JUSTIFIED; chapter.Add(blahblah); } if (i == 5) { blahblahblah.Alignment = Element.ALIGN_CENTER; blahblah.Alignment = Element.ALIGN_RIGHT; chapter.Add(blahblah); } // Add a table in the 6th chapter if (i == 6) { blahblah.Alignment = Element.ALIGN_JUSTIFIED; } // in every chapter 3 sections will be Added for (int j = 1; j < 4; j++) { Paragraph sTitle = new Paragraph("This is section " + j + " in chapter " + i, sectionFont); Section section = chapter.AddSection(sTitle, 1); // in all chapters except the 1st one, some extra text is Added to section 3 if (j == 3 && i > 1) { section.Add(blahblah); } // in every section 3 subsections are Added for (int k = 1; k < 4; k++) { Paragraph subTitle = new Paragraph("This is subsection " + k + " of section " + j, subsectionFont); Section subsection = section.AddSection(subTitle, 3); if (k == 1 && j == 3) { subsection.Add(blahblahblah); } subsection.Add(blahblah); } if (j == 2 && i > 2) { section.Add(blahblahblah); } } document.Add(chapter); } } catch (Exception de) { Console.Error.WriteLine(de.StackTrace); } // step 5: we close the document document.Close(); Console.Read(); } }

    ?

    5.3 Graphic

    如果你想添加諸如線段、圓、幾何圖形等,你可以查看本文的第11章或者查看原文(Chapter 10),但如果你只是需要有限的功能,你可以直接使用Graphic對象。核心代碼如下:

    [c-sharp] view plaincopyprint?
  • Graphic?grx?=?new?Graphic();??
  • //?add?a?rectangle ??
    • grx.rectangle(100,?700,?100,?100);??
    • //?add?the?diagonal ??
    • grx.moveTo(100,?700);??
    • grx.lineTo(200,?800);??
    • //?stroke?the?lines ??
    • grx.stroke();??
    • document.Add(grx);??

    Graphic grx = new Graphic(); // add a rectangle grx.rectangle(100, 700, 100, 100); // add the diagonal grx.moveTo(100, 700); grx.lineTo(200, 800); // stroke the lines grx.stroke(); document.Add(grx);

    ?

    詳細代碼如下(在目前測試過程中,Ghaphic類不能使用,目前還不知道什么原因)

    [c-sharp] view plaincopyprint?
  • using?System;??
  • using?System.IO;??
    • ??
    • using?iTextSharp.text;??
    • using?iTextSharp.text.pdf;??
    • using?iTextSharp.text.factories;??
    • ??
    • public?class?Chap0404??
    • {??
    • ??
    • ????public?static?void?Main()??
    • ????{??
    • ??
    • ????????Console.WriteLine("Chapter?4?example?4:?Simple?Graphic");??
    • ??
    • ????????//?step?1:?creation?of?a?document-object ??
    • ????????Document?document?=?new?Document();??
    • ??
    • ????????try??
    • ????????{??
    • ??
    • ????????????//?step?2: ??
    • ????????????//?we?create?a?writer?that?listens?to?the?document ??
    • ????????????//?and?directs?a?PDF-stream?to?a?file ??
    • ??
    • ????????????PdfWriter.GetInstance(document,?new?FileStream("Chap0404.pdf",?FileMode.Create));??
    • ??
    • ????????????//?step?3:?we?open?the?document ??
    • ????????????document.Open();??
    • ??
    • ????????????//?step?4:?we?add?a?Graphic?to?the?document ??
    • ????????????Graphic?grx?=?new?Graphic();???????
    • ??????????????
    • ????????????//?add?a?rectangle ??
    • ????????????grx.rectangle(100,?700,?100,?100);??
    • ????????????//?add?the?diagonal ??
    • ????????????grx.moveTo(100,?700);??
    • ????????????grx.lineTo(200,?800);??
    • ????????????//?stroke?the?lines ??
    • ????????????grx.stroke();??
    • ????????????document.Add(grx);??
    • ??????????????
    • ??
    • ????????}??
    • ????????catch?(DocumentException?de)??
    • ????????{??
    • ????????????Console.Error.WriteLine(de.Message);??
    • ????????}??
    • ????????catch?(IOException?ioe)??
    • ????????{??
    • ????????????Console.Error.WriteLine(ioe.Message);??
    • ????????}??
    • ??
    • ????????//?step?5:?we?close?the?document ??
    • ????????document.Close();??
    • ??
    • ????????Console.Read();??
    • ????}??
    • }??

    using System; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; using iTextSharp.text.factories; public class Chap0404 { public static void Main() { Console.WriteLine("Chapter 4 example 4: Simple Graphic"); // step 1: creation of a document-object Document document = new Document(); try { // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter.GetInstance(document, new FileStream("Chap0404.pdf", FileMode.Create)); // step 3: we open the document document.Open(); // step 4: we add a Graphic to the document Graphic grx = new Graphic(); // add a rectangle grx.rectangle(100, 700, 100, 100); // add the diagonal grx.moveTo(100, 700); grx.lineTo(200, 800); // stroke the lines grx.stroke(); document.Add(grx); } catch (DocumentException de) { Console.Error.WriteLine(de.Message); } catch (IOException ioe) { Console.Error.WriteLine(ioe.Message); } // step 5: we close the document document.Close(); Console.Read(); } }

    ?

    ?

    六、表格Table(原文:http://itextsharp.sourceforge.net/tutorial/ch05.html)

    提示:如果你僅僅只生成PDF(并非XML,HTML,RTF)文件,你最好可以用PdfPTable類取代Table類

    6.1 一些簡單的表格

    Table(表格)就是一個包含Cells(單元格)的Rectangle(矩陣).并按照一些特定的矩陣進行排序。表格中的矩陣并一定要M*N,它還可以只包含比unit大的單元格或者hole,其核心代碼如下:

    [c-sharp] view plaincopyprint?
  • public?Table(int?columns,?int?rows)?throws?BadElementException;???
  • public Table(int columns, int rows) throws BadElementException;

    ?

    下面的代碼我們創建一個非常簡單的表格:

    [c-sharp] view plaincopyprint?
  • using?System;??
  • using?System.IO;??
    • ??
    • using?iTextSharp.text;??
    • using?iTextSharp.text.pdf;??
    • ??
    • public?class?Chap0501??
    • {??
    • ??
    • ????public?static?void?Main()??
    • ????{??
    • ????????Console.WriteLine("Chapter?5?example?1:?my?first?table");??
    • ????????//?step?1:?creation?of?a?document-object ??
    • ????????Document?document?=?new?Document();??
    • ????????try??
    • ????????{??
    • ????????????//?step?2: ??
    • ????????????//?we?create?a?writer?that?listens?to?the?document ??
    • ????????????//?and?directs?a?PDF-stream?to?a?file ??
    • ????????????PdfWriter.GetInstance(document,?new?FileStream("Chap0501.pdf",?FileMode.Create));??
    • ????????????//?step?3:?we?open?the?document ??
    • ????????????document.Open();??
    • ????????????//?step?4:?we?create?a?table?and?add?it?to?the?document ??
    • ????????????Table?aTable?=?new?Table(2,?2);????//?2?rows,?2?columns ??
    • ????????????aTable.AddCell("0.0");??
    • ????????????aTable.AddCell("0.1");??
    • ????????????aTable.AddCell("1.0");??
    • ????????????aTable.AddCell("1.1");??
    • ????????????aTable.AddCell("1.2");??
    • ????????????document.Add(aTable);??
    • ????????}??
    • ????????catch?(DocumentException?de)??
    • ????????{??
    • ????????????Console.Error.WriteLine(de.Message);??
    • ????????}??
    • ????????catch?(IOException?ioe)??
    • ????????{??
    • ????????????Console.Error.WriteLine(ioe.Message);??
    • ????????}??
    • ????????//?step?5:?we?close?the?document ??
    • ????????document.Close();??
    • ??
    • ????????Console.Read();??
    • ????}??
    • ??
    • }??

    using System; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; public class Chap0501 { public static void Main() { Console.WriteLine("Chapter 5 example 1: my first table"); // step 1: creation of a document-object Document document = new Document(); try { // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter.GetInstance(document, new FileStream("Chap0501.pdf", FileMode.Create)); // step 3: we open the document document.Open(); // step 4: we create a table and add it to the document Table aTable = new Table(2, 2); // 2 rows, 2 columns aTable.AddCell("0.0"); aTable.AddCell("0.1"); aTable.AddCell("1.0"); aTable.AddCell("1.1"); aTable.AddCell("1.2"); document.Add(aTable); } catch (DocumentException de) { Console.Error.WriteLine(de.Message); } catch (IOException ioe) { Console.Error.WriteLine(ioe.Message); } // step 5: we close the document document.Close(); Console.Read(); } }

    ?

    以上代碼創建了一個含有2行2列的表格,單元格自動添加,開始于第一行的第一列,然后第二列,當一個行滿了以后,下一個單元格就在下一行的第一列添加。如下圖所示:

    以下代碼為在表格指定的位置進行添加單元格,在測試本代碼,您必須添加引用System.Drawing.dll庫文件來訪問Point對象,我們在該代碼創建一個4X4的表格,然后在隨機的位置添加單元格。

    核心代碼如下:

    [c-sharp] view plaincopyprint?
  • Table?aTable?=?new?Table(4,4);??
  • aTable.AutoFillEmptyCells?=?true;??
    • aTable.addCell("2.2",?new?Point(2,2));??
    • aTable.addCell("3.3",?new?Point(3,3));??
    • aTable.addCell("2.1",?new?Point(2,1));??
    • aTable.addCell("1.3",?new?Point(1,3));??

    Table aTable = new Table(4,4); aTable.AutoFillEmptyCells = true; aTable.addCell("2.2", new Point(2,2)); aTable.addCell("3.3", new Point(3,3)); aTable.addCell("2.1", new Point(2,1)); aTable.addCell("1.3", new Point(1,3));

    ?

    詳細代碼如下:

    [c-sharp] view plaincopyprint?
  • using?System;??
  • using?System.IO;??
    • using?System.Drawing;??
    • ??
    • using?iTextSharp.text;??
    • using?iTextSharp.text.pdf;??
    • ??
    • public?class?Chap0502??
    • {??
    • ??
    • ????public?static?void?Main()??
    • ????{??
    • ????????Console.WriteLine("Chapter?5?example?2:?adding?cells?at?a?specific?position");??
    • ????????//?step?1:?creation?of?a?document-object ??
    • ????????Document?document?=?new?Document();??
    • ????????try??
    • ????????{??
    • ????????????//?step?2: ??
    • ????????????//?we?create?a?writer?that?listens?to?the?document ??
    • ????????????//?and?directs?a?PDF-stream?to?a?file ??
    • ????????????PdfWriter.GetInstance(document,?new?FileStream("Chap0502.pdf",?FileMode.Create));??
    • ????????????//?step?3:?we?open?the?document ??
    • ????????????document.Open();??
    • ????????????//?step?4:?we?create?a?table?and?add?it?to?the?document ??
    • ????????????Table?aTable;??
    • ??
    • ????????????aTable?=?new?Table(4,?4);????//?4?rows,?4?columns ??
    • ????????????aTable.AutoFillEmptyCells?=?true;??
    • ????????????aTable.AddCell("2.2",?new?Point(2,?2));??
    • ????????????aTable.AddCell("3.3",?new?Point(3,?3));??
    • ????????????aTable.AddCell("2.1",?new?Point(2,?1));??
    • ????????????aTable.AddCell("1.3",?new?Point(1,?3));??
    • ????????????document.Add(aTable);??
    • ????????????document.NewPage();??
    • ??
    • ????????????aTable?=?new?Table(4,?4);????//?4?rows,?4?columns ??
    • ????????????aTable.AddCell("2.2",?new?Point(2,?2));??
    • ????????????aTable.AddCell("3.3",?new?Point(3,?3));??
    • ????????????aTable.AddCell("2.1",?new?Point(2,?1));??
    • ????????????aTable.AddCell("1.3",?new?Point(1,?3));??
    • ????????????document.Add(aTable);??
    • ????????}??
    • ????????catch?(DocumentException?de)??
    • ????????{??
    • ????????????Console.Error.WriteLine(de.Message);??
    • ????????}??
    • ????????catch?(IOException?ioe)??
    • ????????{??
    • ????????????Console.Error.WriteLine(ioe.Message);??
    • ????????}??
    • ????????//?step?5:?we?close?the?document ??
    • ????????document.Close();??
    • ??
    • ????????Console.Read();??
    • ????}??
    • ??
    • }??

    using System; using System.IO; using System.Drawing; using iTextSharp.text; using iTextSharp.text.pdf; public class Chap0502 { public static void Main() { Console.WriteLine("Chapter 5 example 2: adding cells at a specific position"); // step 1: creation of a document-object Document document = new Document(); try { // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter.GetInstance(document, new FileStream("Chap0502.pdf", FileMode.Create)); // step 3: we open the document document.Open(); // step 4: we create a table and add it to the document Table aTable; aTable = new Table(4, 4); // 4 rows, 4 columns aTable.AutoFillEmptyCells = true; aTable.AddCell("2.2", new Point(2, 2)); aTable.AddCell("3.3", new Point(3, 3)); aTable.AddCell("2.1", new Point(2, 1)); aTable.AddCell("1.3", new Point(1, 3)); document.Add(aTable); document.NewPage(); aTable = new Table(4, 4); // 4 rows, 4 columns aTable.AddCell("2.2", new Point(2, 2)); aTable.AddCell("3.3", new Point(3, 3)); aTable.AddCell("2.1", new Point(2, 1)); aTable.AddCell("1.3", new Point(1, 3)); document.Add(aTable); } catch (DocumentException de) { Console.Error.WriteLine(de.Message); } catch (IOException ioe) { Console.Error.WriteLine(ioe.Message); } // step 5: we close the document document.Close(); Console.Read(); } }

    ?

    從以上代碼可以看出,我們必須設置屬性AutoFillEmptyCells屬性為true,如果你忘記設置該屬性(就像本代碼生成的第二個表格),這樣就不會有額外的單元格添加當然不包括任何單元格的行也會被忽略。在本例中,第一行沒有顯示,就是因為它是空的。

    通常情況下,我們會用數據庫查詢結果來填滿表格,在許多例子中,我們并不知道我們究竟需要多少行,這里有個構造函數可以解決這個問題,如下:

    [c-sharp] view plaincopyprint?
  • public?Table(int?columns);???
  • public Table(int columns);

    ?

    ?

    ?

    ?

    ?

    如果有需要,iText會自動添加行,在下面的例子,我們初始化了一個4X4的表格,當我們在6行和7行添加單元格的時候,iText自動將行數升至為7.具體代碼如下所示:

    [c-sharp] view plaincopyprint?
  • using?System;??
  • using?System.IO;??
    • using?System.Drawing;??
    • ??
    • using?iTextSharp.text;??
    • using?iTextSharp.text.pdf;??
    • ??
    • public?class?Chap0503??
    • {??
    • ??
    • ????public?static?void?Main()??
    • ????{??
    • ????????Console.WriteLine("Chapter?5?example?3:?rows?added?automatically");??
    • ????????//?step?1:?creation?of?a?document-object ??
    • ????????Document?document?=?new?Document();??
    • ????????try??
    • ????????{??
    • ????????????//?step?2: ??
    • ????????????//?we?create?a?writer?that?listens?to?the?document ??
    • ????????????//?and?directs?a?PDF-stream?to?a?file ??
    • ????????????PdfWriter.GetInstance(document,?new?FileStream("Chap0503.pdf",?FileMode.Create));??
    • ????????????//?step?3:?we?open?the?document ??
    • ????????????document.Open();??
    • ????????????//?step?4:?we?create?a?table?and?add?it?to?the?document ??
    • ????????????Table?aTable?=?new?Table(4,?4);????//?4?rows,?4?columns ??
    • ????????????aTable.AutoFillEmptyCells?=?true;??
    • ????????????aTable.AddCell("2.2",?new?Point(2,?2));??
    • ????????????aTable.AddCell("3.3",?new?Point(3,?3));??
    • ????????????aTable.AddCell("2.1",?new?Point(2,?1));??
    • ????????????aTable.AddCell("1.3",?new?Point(1,?3));??
    • ????????????aTable.AddCell("5.2",?new?Point(5,?2));??
    • ????????????aTable.AddCell("6.1",?new?Point(6,?1));??
    • ????????????aTable.AddCell("5.0",?new?Point(5,?0));??
    • ????????????document.Add(aTable);??
    • ????????}??
    • ????????catch?(DocumentException?de)??
    • ????????{??
    • ????????????Console.Error.WriteLine(de.Message);??
    • ????????}??
    • ????????catch?(IOException?ioe)??
    • ????????{??
    • ????????????Console.Error.WriteLine(ioe.Message);??
    • ????????}??
    • ????????//?step?5:?we?close?the?document ??
    • ????????document.Close();??
    • ????????Console.Read();??
    • ????}??
    • }??

    using System; using System.IO; using System.Drawing; using iTextSharp.text; using iTextSharp.text.pdf; public class Chap0503 { public static void Main() { Console.WriteLine("Chapter 5 example 3: rows added automatically"); // step 1: creation of a document-object Document document = new Document(); try { // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter.GetInstance(document, new FileStream("Chap0503.pdf", FileMode.Create)); // step 3: we open the document document.Open(); // step 4: we create a table and add it to the document Table aTable = new Table(4, 4); // 4 rows, 4 columns aTable.AutoFillEmptyCells = true; aTable.AddCell("2.2", new Point(2, 2)); aTable.AddCell("3.3", new Point(3, 3)); aTable.AddCell("2.1", new Point(2, 1)); aTable.AddCell("1.3", new Point(1, 3)); aTable.AddCell("5.2", new Point(5, 2)); aTable.AddCell("6.1", new Point(6, 1)); aTable.AddCell("5.0", new Point(5, 0)); document.Add(aTable); } catch (DocumentException de) { Console.Error.WriteLine(de.Message); } catch (IOException ioe) { Console.Error.WriteLine(ioe.Message); } // step 5: we close the document document.Close(); Console.Read(); } }

    ?

    同樣,添加列數也是可能的,但是有一定的難度,它不會進行自動的添加,你需要使用addColumns方法以及為列的寬度進行設置,在下面的代碼可以看出。

    [c-sharp] view plaincopyprint?
  • using?System;??
  • using?System.IO;??
    • using?System.Drawing;??
    • ??
    • using?iTextSharp.text;??
    • using?iTextSharp.text.pdf;??
    • ??
    • public?class?Chap0504??
    • {??
    • ??
    • ????public?static?void?Main()??
    • ????{??
    • ????????Console.WriteLine("Chapter?5?example?4:?adding?columns");??
    • ????????//?step?1:?creation?of?a?document-object ??
    • ????????Document?document?=?new?Document();??
    • ????????try??
    • ????????{??
    • ????????????//?step?2: ??
    • ????????????//?we?create?a?writer?that?listens?to?the?document ??
    • ????????????//?and?directs?a?PDF-stream?to?a?file ??
    • ????????????PdfWriter.GetInstance(document,?new?FileStream("Chap0504.pdf",?FileMode.Create));??
    • ????????????//?step?3:?we?open?the?document ??
    • ????????????document.Open();??
    • ????????????//?step?4:?we?create?a?table?and?add?it?to?the?document ??
    • ????????????Table?aTable?=?new?Table(2,?2);????//?2?rows,?2?columns ??
    • ????????????aTable.AutoFillEmptyCells?=?true;??
    • ????????????aTable.AddCell("0.0");??
    • ????????????aTable.AddCell("0.1");??
    • ????????????aTable.AddCell("1.0");??
    • ????????????aTable.AddCell("1.1");??
    • ????????????aTable.AddColumns(2);??
    • ????????????float[]?f?=?{?1f,?1f,?1f,?1f?};??
    • ????????????aTable.Widths?=?f;??
    • ????????????aTable.AddCell("2.2",?new?Point(2,?2));??
    • ????????????aTable.AddCell("3.3",?new?Point(3,?3));??
    • ????????????aTable.AddCell("2.1",?new?Point(2,?1));??
    • ????????????aTable.AddCell("1.3",?new?Point(1,?3));??
    • ????????????aTable.AddCell("5.2",?new?Point(5,?2));??
    • ????????????aTable.AddCell("6.1",?new?Point(6,?1));??
    • ????????????aTable.AddCell("5.0",?new?Point(5,?0));??
    • ????????????document.Add(aTable);??
    • ??
    • ????????}??
    • ????????catch?(DocumentException?de)??
    • ????????{??
    • ????????????Console.Error.WriteLine(de.Message);??
    • ????????}??
    • ????????catch?(IOException?ioe)??
    • ????????{??
    • ????????????Console.Error.WriteLine(ioe.Message);??
    • ????????}??
    • ????????//?step?5:?we?close?the?document ??
    • ????????document.Close();??
    • ??
    • ????????Console.Read();??
    • ????}??
    • }??

    using System; using System.IO; using System.Drawing; using iTextSharp.text; using iTextSharp.text.pdf; public class Chap0504 { public static void Main() { Console.WriteLine("Chapter 5 example 4: adding columns"); // step 1: creation of a document-object Document document = new Document(); try { // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter.GetInstance(document, new FileStream("Chap0504.pdf", FileMode.Create)); // step 3: we open the document document.Open(); // step 4: we create a table and add it to the document Table aTable = new Table(2, 2); // 2 rows, 2 columns aTable.AutoFillEmptyCells = true; aTable.AddCell("0.0"); aTable.AddCell("0.1"); aTable.AddCell("1.0"); aTable.AddCell("1.1"); aTable.AddColumns(2); float[] f = { 1f, 1f, 1f, 1f }; aTable.Widths = f; aTable.AddCell("2.2", new Point(2, 2)); aTable.AddCell("3.3", new Point(3, 3)); aTable.AddCell("2.1", new Point(2, 1)); aTable.AddCell("1.3", new Point(1, 3)); aTable.AddCell("5.2", new Point(5, 2)); aTable.AddCell("6.1", new Point(6, 1)); aTable.AddCell("5.0", new Point(5, 0)); document.Add(aTable); } catch (DocumentException de) { Console.Error.WriteLine(de.Message); } catch (IOException ioe) { Console.Error.WriteLine(ioe.Message); } // step 5: we close the document document.Close(); Console.Read(); } }

    ?

    6.2 ?一些表格參數

    以上創建的一些表格看起來效果都不怎么好,我們可以通過設置一些表格參數來改變表格的外觀。Table類和Cell類都是繼承于Rectangle類,所以我們可以利用一些rectangle的典型的方法,如下面代碼:

    [c-sharp] view plaincopyprint?
  • using?System;??
  • using?System.IO;??
    • ??
    • using?iTextSharp.text;??
    • using?iTextSharp.text.pdf;??
    • ??
    • public?class?Chap0505??
    • {??
    • ????public?static?void?Main()??
    • ????{??
    • ????????Console.WriteLine("Chapter?5?example?5:?colspan,?rowspan,?padding,?spacing,?colors");??
    • ????????//?step?1:?creation?of?a?document-object ??
    • ????????Document?document?=?new?Document();??
    • ????????try??
    • ????????{??
    • ????????????//?step?2: ??
    • ????????????//?we?create?a?writer?that?listens?to?the?document ??
    • ????????????//?and?directs?a?PDF-stream?to?a?file ??
    • ????????????PdfWriter.GetInstance(document,?new?FileStream("Chap0505.pdf",?FileMode.Create));??
    • ????????????//?step?3:?we?open?the?document ??
    • ????????????document.Open();??
    • ????????????//?step?4:?we?create?a?table?and?add?it?to?the?document ??
    • ????????????Table?table?=?new?Table(3);??
    • ????????????table.BorderWidth?=?1;??
    • ????????????table.BorderColor?=?new?Color(0,?0,?255);??
    • ????????????table.Padding?=?5;??
    • ????????????table.Spacing?=?5;??
    • ????????????Cell?cell?=?new?Cell("header");??
    • ????????????cell.Header?=?true;??
    • ????????????cell.Colspan?=?3;??
    • ????????????table.AddCell(cell);??
    • ????????????cell?=?new?Cell("example?cell?with?colspan?1?and?rowspan?2");??
    • ????????????cell.Rowspan?=?2;??
    • ????????????cell.BorderColor?=?new?Color(255,?0,?0);??
    • ????????????table.AddCell(cell);??
    • ????????????table.AddCell("1.1");??
    • ????????????table.AddCell("2.1");??
    • ????????????table.AddCell("1.2");??
    • ????????????table.AddCell("2.2");??
    • ????????????table.AddCell("cell?test1");??
    • ????????????cell?=?new?Cell("big?cell");??
    • ????????????cell.Rowspan?=?2;??
    • ????????????cell.Colspan?=?2;??
    • ????????????cell.BackgroundColor?=?new?Color(0xC0,?0xC0,?0xC0);??
    • ????????????table.AddCell(cell);??
    • ????????????table.AddCell("cell?test2");??
    • ????????????document.Add(table);??
    • ????????}??
    • ????????catch?(DocumentException?de)??
    • ????????{??
    • ????????????Console.Error.WriteLine(de.Message);??
    • ????????}??
    • ????????catch?(IOException?ioe)??
    • ????????{??
    • ????????????Console.Error.WriteLine(ioe.Message);??
    • ????????}??
    • ????????//?step?5:?we?close?the?document ??
    • ????????document.Close();??
    • ??
    • ????????Console.Read();??
    • ????}??
    • }??

    轉載于:https://www.cnblogs.com/zhycyq/p/3312620.html

    總結

    以上是生活随笔為你收集整理的.NET的那些事儿(9)——C# 2.0 中用iTextSharp制作PDF(基础篇) .的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。