.NET的那些事儿(9)——C# 2.0 中用iTextSharp制作PDF(基础篇) .
該文主要介紹如何借助iTextSharp在C# 2.0中制作PDF文件,本文的架構(gòu)大致按照iTextSharp的操作文檔進(jìn)行翻譯,如果需要查看原文,請(qǐng)點(diǎn)擊一下鏈接:http://itextsharp.sourceforge.net/tutorial/
一、?iTextSharp的介紹和下載
(1)用戶可以瀏覽官網(wǎng)進(jìn)行查看: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
下載后為一個(gè)解壓縮文件,用戶直接解壓后得到一個(gè)dll動(dòng)態(tài)鏈接庫,在創(chuàng)建的項(xiàng)目中直接引入即可使用(本文的所有代碼均在VS 2005環(huán)境下測試通過)
二、創(chuàng)建一個(gè)PDF文檔(原文:http://itextsharp.sourceforge.net/tutorial/ch01.html)
2.1 示例代碼分析
創(chuàng)建一個(gè)PDF文檔大致包括五個(gè)步驟,代碼如下:
[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: 創(chuàng)建Document對(duì)象 Document document = new Document(); try { //step 2:創(chuàng)建一個(gè)writer用于監(jiān)聽Document以及通過PDF-stream指向一個(gè)文件 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: 關(guān)閉document document.Close(); Console.Read(); } } }
?
該段代碼的效果是可以在當(dāng)前工作目錄下,生成一個(gè)名字叫做Chap0101.pdf的PDF文檔
2.2 第一步:創(chuàng)建Document對(duì)象
(1) Document對(duì)象
iTextSharp.text.Document有三個(gè)構(gòu)造函數(shù),分別為:
[c-sharp] view plaincopyprint?public Document(); public Document(Rectangle pageSize); public Document(Rectangle pageSize, int marginLeft, int marginRight, int marginTop, int marginBottom);
?
第一個(gè)構(gòu)造函數(shù)調(diào)用第二個(gè)構(gòu)造函數(shù),參數(shù)為PageSize.A4
第二個(gè)構(gòu)造函數(shù)調(diào)用第三個(gè)構(gòu)造函數(shù),其中每個(gè)邊距默認(rèn)值為36
(2) Page Size
你可以創(chuàng)建自己的用于特定顏色的Rectangle對(duì)象,并將其作為pageSize。我們對(duì)前面的代碼進(jìn)行修改,即創(chuàng)建一個(gè)長的、窄的、背景顏色為淡黃色的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(); } } }
?
大多pageSizes都是采用了PORTRAIT格式,如果你想在LANDSCAPE應(yīng)用它們,你必須使用rotate(),代碼如下:
[c-sharp] view plaincopyprint?Document document = new Document(PageSize.A4.rotate());
?
(3) Margins
在創(chuàng)建document的過程中,你也可以定義左、右、上、下邊距,代碼如下所示:
[c-sharp] view plaincopyprint?Document document = new Document(PageSize.A5, 36, 72, 108, 180);
?
注意:如果你修改pageSize,會(huì)在下一個(gè)頁面創(chuàng)建時(shí)產(chǎn)生影響;如果你修改margins,則會(huì)在當(dāng)前頁面立即產(chǎn)生影響。
2.3 創(chuàng)建Write對(duì)象
一旦成功創(chuàng)建了document,我們必須創(chuàng)建一個(gè)或者多個(gè)實(shí)例用于監(jiān)聽document,所有的writers繼承于iTextSharp.text.DocWriter類。即你可以iTextSharp.text.pdf.PdfWriter使用來生成PDF文檔,而如果需要生成Tex文檔你必須使用iTextSharp.text.TeX.TeXWriter。
你可以使用以下的方式創(chuàng)建實(shí)例:
[c-sharp] view plaincopyprint?PdfWriter writer = PdfWriter.getInstance(document, new FileStream("Chap01xx.pdf"));
?
在使用過程中,你幾乎不會(huì)使用到writer對(duì)象(除了你想創(chuàng)建高級(jí)的PDF文件或者你想使用一些特定的函數(shù),比如ViewerPreferences或者Encryption),所以獲取這類實(shí)例就足夠了。
該函數(shù)的第一個(gè)參數(shù)即第一步所創(chuàng)建的document對(duì)象;
第二個(gè)參數(shù)為不同類型的Stream對(duì)象,目前我們都只使用System.IO.FileStream,后來我們會(huì)使用到System.IO.MemoryStream.?
2.4 元數(shù)據(jù)以及打開document
在你添加實(shí)際數(shù)據(jù)(即內(nèi)容)是,你可能想加入某些關(guān)系到document的元數(shù)據(jù),其方法如下:
[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)
?
你可以選擇自己的Title,Subject,Keywords,Author以及Creator,但是添加制作者的函數(shù)必須一直使用,以及添加創(chuàng)建時(shí)間的方法添加的當(dāng)前系統(tǒng)的時(shí)間(事實(shí)上,這兩個(gè)方法是被自動(dòng)調(diào)用的),你可以用客戶的姓名作為Header,但是這對(duì)于PdfWrite沒有任何影響。
2.5 添加內(nèi)容
1、在前面的三個(gè)步驟中,你遇到了諸如:Phrase,Paragraph…的對(duì)象,在以后的章節(jié)會(huì)詳細(xì)的給予介紹。有些時(shí)候,你可能希望writer可以忽略document中的行為,相關(guān)的代碼可以查看
2、如果你想創(chuàng)建兩個(gè)writer:writerA和writerB(這個(gè)代碼在第二步會(huì)丟出異常)
[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));
?
實(shí)際上,我們需要對(duì)其進(jìn)行簡單的修改,修改后的代碼如下:
[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();
?
2.6 關(guān)閉document
關(guān)閉document相當(dāng)重要,因?yàn)樗鼤?huì)影響和關(guān)閉writer寫的輸出流,close方法為finalize方法,但是你不能依靠它,你必須手工對(duì)其進(jìn)行關(guān)閉。
三、Chunks, Phrases 和Paragraphs(原文http://itextsharp.sourceforge.net/tutorial/ch02.html)
 3.1 Chunk
Chunk是能夠添加到document文本中最小的重要部分。Chunk能夠?yàn)槠渌脑刂T如Phrase以及Paragrph等構(gòu)建塊,一個(gè)Chunk就是一個(gè)附有指定字體的字符串,在添加chunk的文本的對(duì)象中,所有其他的版面設(shè)計(jì)參數(shù)都應(yīng)該定義。
下面的代碼表示我們創(chuàng)建內(nèi)容為"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)));
?
?
?
?
3.2 Phrases
?
Phrases是一系列擁有特定的作為額外參數(shù)的leading(=兩行之間的空間)的Chunk
Phrases擁有一個(gè)主字體,但是其他的chunks可以擁有不同于這個(gè)主字體的其余字體,你可以從多種構(gòu)造函數(shù)中創(chuàng)建Phrases對(duì)象。代碼如下:
[c-sharp] view plaincopyprint?- ??
- 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,用戶也可以定義特定的縮排。每個(gè)加到document的Phragraph都會(huì)自動(dòng)生成新的一行。Phragraph的構(gòu)造函數(shù)包括如下幾種:
[c-sharp] view plaincopyprint?- 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對(duì)象還可以利用add()添加paragraph對(duì)象。代碼如下:
[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."));
?
注意:每一個(gè)paragraph只能且需有一個(gè)leading,如果你想添加其他字體的phrase或者chunk,原先的leading依舊有效,你可以利用方法setLeading修改leading,但是這樣會(huì)造成所有paragraph的內(nèi)容都會(huì)擁有新的leading.測試代碼如下:
[c-sharp] view plaincopyprint?- ??
- 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(); } }
?
以下的代碼我們應(yīng)用方法setKeepTogether(true)來保證paragraph在一個(gè)page上,這個(gè)并不經(jīng)常發(fā)生。
[c-sharp] view plaincopyprint?- ??
- 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中的超文本鏈接,只要你點(diǎn)擊指定的文字,你就可以跳轉(zhuǎn)到網(wǎng)絡(luò)中的其他頁面,這種功能在PDF中同樣存在,在后面的章節(jié)會(huì)詳細(xì)的介紹PDF中的鏈接Chapter 11,。但是這是iText的另外一種高級(jí)編程,我們這里只是介紹簡單的iText.
如果你想添加外部的link到document中(比如用URL鏈接到網(wǎng)頁中的另外一個(gè)document),你可以簡單的使用Anchor對(duì)象,該對(duì)象繼承于Phrase對(duì)象,它們具有相同的使用方法,但是它還有兩個(gè)額外的方法:setName和setReference,具體的使用代碼如下:
[c-sharp] view plaincopyprint?- 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";
?
如果你想添加內(nèi)部的鏈接,你需要為鏈接選擇獨(dú)特的名字,這就像在HTML中為錨所使用的名字,當(dāng)你為這個(gè)目標(biāo)設(shè)定索引時(shí),你需要在前面添加一個(gè)#符號(hào),具體代碼如下:
[c-sharp] view plaincopyprint?- 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)你都可以使用這兩個(gè)類。
?
(1) ordered列表
[c-sharp] view plaincopyprint?- 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"));
?
?
結(jié)果為:
?
(2) 無序列表
[c-sharp] view plaincopyprint?- 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");
?
結(jié)果為:
你可以用setListSymbol方法改變列表標(biāo)識(shí)符,代碼如下所示:
[c-sharp] view plaincopyprint?- //?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.
而列表符的縮排可以在構(gòu)造函數(shù)中給予設(shè)定,參考代碼如下:
[c-sharp] view plaincopyprint?- ??
- 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添加一些小塊的文本,但是這些文本并不屬于內(nèi)容的一部分,Annotation有一個(gè)標(biāo)題和一些內(nèi)容,具體代碼如下:
[c-sharp] view plaincopyprint?Annotation a = new Annotation( "authors", "Maybe it's because I wanted to be an author myself that I wrote iText."); ??
?
(2) External links(外部鏈接):你可以指定一個(gè)可被點(diǎn)擊的矩形或者字符串(稱為URL)或者URL對(duì)象,具體代碼如下:
[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");
?
(3) External PDF file(外部PDF文件):你可以設(shè)定一個(gè)可點(diǎn)擊的矩形和字符串(文件名稱)和目的文件或者頁碼:
[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);
?
(4) Named action(指定的行為):你必須制定一個(gè)可點(diǎn)擊的矩形和一個(gè)指定的行為:
[c-sharp] view plaincopyprint?Annotation annot = new Annotation(100f, 700f, 200f, 800f, PdfAction.FIRSTPAGE);
?
(5) Application(應(yīng)用):你必須制定一個(gè)可點(diǎn)擊的矩形和一個(gè)應(yīng)用程序
[c-sharp] view plaincopyprint?Annotation annot = new Annotation(300f, 700f, 400f, 800f, "C://winnt/notepad.exe", null, null, null);
?
?
5、HeaderFooters,Chapters,Sections和Graphic對(duì)象(原文:http://itextsharp.sourceforge.net/tutorial/ch04.html)
5.1 HeaderFooter
HeaderFooter對(duì)象是一個(gè)能夠?yàn)閐ocument的每個(gè)頁面添加footer和header的對(duì)象,這些頁眉和頁腳都包含著標(biāo)準(zhǔn)的短語和當(dāng)前的頁碼(如果有需要)。如果你需要更加復(fù)雜的頁眉和頁腳(有表格或者有page X of Y),您需要閱讀12章節(jié)Chapter 12:
下面的核心代碼表示我們第一個(gè)添加一個(gè)包含頁碼但是么有任何邊界的頁眉。
[c-sharp] view plaincopyprint?HeaderFooter footer = new HeaderFooter(new Phrase("This is page: "), true); footer.Border = Rectangle.NO_BORDER; document.Footer = footer;
?
具體代碼如下:
?
[c-sharp] view plaincopyprint?- ??
- 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(); } }
?
?
我們也可以用一下的構(gòu)造函數(shù):
[c-sharp] view plaincopyprint?HeaderFooter footer = new HeaderFooter(new Phrase("This is page "), new Phrase("."));
?
如果你設(shè)置HeadFooter對(duì)象沒有改變邊界,頁眉或者頁腳會(huì)在文本的上下有一條線。
[c-sharp] view plaincopyprint?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節(jié))描述了如何創(chuàng)建大綱樹,如果你只是需要附有一些章節(jié)或者子段的簡單的樹,你可以利用Chapter和Section類來自動(dòng)創(chuàng)建,核心代碼如下:
[c-sharp] view plaincopyprint?- 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);
?
下面的代碼,我們添加一系列的章節(jié)和子章節(jié),運(yùn)行程序后,你可以查看到PDF文件擁有完整的大綱樹,這個(gè)大綱樹被默認(rèn)打開,如果你想使得有一部大綱關(guān)閉,你可以把BookmarkOpen屬性設(shè)置為false.
[c-sharp] view plaincopyprint?- ??
- 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對(duì)象。核心代碼如下:
[c-sharp] view plaincopyprint?- 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);
?
詳細(xì)代碼如下(在目前測試過程中,Ghaphic類不能使用,目前還不知道什么原因)
[c-sharp] view plaincopyprint?- ??
- 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(表格)就是一個(gè)包含Cells(單元格)的Rectangle(矩陣).并按照一些特定的矩陣進(jìn)行排序。表格中的矩陣并一定要M*N,它還可以只包含比unit大的單元格或者h(yuǎn)ole,其核心代碼如下:
[c-sharp] view plaincopyprint?public Table(int columns, int rows) throws BadElementException;
?
下面的代碼我們創(chuàng)建一個(gè)非常簡單的表格:
[c-sharp] view plaincopyprint?- ??
- 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(); } }
?
以上代碼創(chuàng)建了一個(gè)含有2行2列的表格,單元格自動(dòng)添加,開始于第一行的第一列,然后第二列,當(dāng)一個(gè)行滿了以后,下一個(gè)單元格就在下一行的第一列添加。如下圖所示:
以下代碼為在表格指定的位置進(jìn)行添加單元格,在測試本代碼,您必須添加引用System.Drawing.dll庫文件來訪問Point對(duì)象,我們?cè)谠摯a創(chuàng)建一個(gè)4X4的表格,然后在隨機(jī)的位置添加單元格。
核心代碼如下:
[c-sharp] view plaincopyprint?- 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));
?
詳細(xì)代碼如下:
[c-sharp] view plaincopyprint?- 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(); } }
?
從以上代碼可以看出,我們必須設(shè)置屬性AutoFillEmptyCells屬性為true,如果你忘記設(shè)置該屬性(就像本代碼生成的第二個(gè)表格),這樣就不會(huì)有額外的單元格添加當(dāng)然不包括任何單元格的行也會(huì)被忽略。在本例中,第一行沒有顯示,就是因?yàn)樗强盏摹?/span>
通常情況下,我們會(huì)用數(shù)據(jù)庫查詢結(jié)果來填滿表格,在許多例子中,我們并不知道我們究竟需要多少行,這里有個(gè)構(gòu)造函數(shù)可以解決這個(gè)問題,如下:
[c-sharp] view plaincopyprint?public Table(int columns);
?
?
?
?
?
如果有需要,iText會(huì)自動(dòng)添加行,在下面的例子,我們初始化了一個(gè)4X4的表格,當(dāng)我們?cè)?行和7行添加單元格的時(shí)候,iText自動(dòng)將行數(shù)升至為7.具體代碼如下所示:
[c-sharp] view plaincopyprint?- 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(); } }
?
同樣,添加列數(shù)也是可能的,但是有一定的難度,它不會(huì)進(jìn)行自動(dòng)的添加,你需要使用addColumns方法以及為列的寬度進(jìn)行設(shè)置,在下面的代碼可以看出。
[c-sharp] view plaincopyprint?- 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 ?一些表格參數(shù)
以上創(chuàng)建的一些表格看起來效果都不怎么好,我們可以通過設(shè)置一些表格參數(shù)來改變表格的外觀。Table類和Cell類都是繼承于Rectangle類,所以我們可以利用一些rectangle的典型的方法,如下面代碼:
[c-sharp] view plaincopyprint?- ??
- 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();??
- ????}??
- }??
轉(zhuǎn)載于:https://www.cnblogs.com/zhycyq/p/3312620.html
總結(jié)
以上是生活随笔為你收集整理的.NET的那些事儿(9)——C# 2.0 中用iTextSharp制作PDF(基础篇) .的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: RedHat 7.8下Redis安装和配
- 下一篇: linux桥接网卡
