在Asp.Net中操作PDF – iTextSharp -利用塊,短語,段落添加文本
轉自:http://www.cnblogs.com/CareySon/archive/2011/11/03/2234625.html
本篇文章是講述使用iTextSharp這個開源組件的系列文章的第三篇,iTextSharp可以通過Asp.Net創建PDFs,就像HTML和ASP.Net為文本提供了多種容器一樣,iTextSharp提供了Chunk,Phrase和Paragraph這三個類作為容器
Chunks
塊(Chunks)是容納文本的最小容器,就像ASP.Net中的<asp:Label>一樣。就像使用Label一樣,對于塊的使用需要小心.下面代碼展示如何為塊設置文本,然后將其寫入PDF 3次.
string path = Server.MapPath("PDFs");Rectangle r = new Rectangle(400, 300);
Document doc = new Document(r);
PdfWriter.GetInstance(doc, new FileStream(path + "/Blocks.pdf", FileMode.Create));
doc.Open();
Chunk c1 = new Chunk("A chunk represents an isolated string. ");
for (int i = 1; i < 4; i++)
{
doc.Add(c1);
}</pre>
[接下來的一段你要格外注意,我們后面還要用到]
結果如下,可以看出文本已經被加入文檔,但顯示出來卻是一團亂麻.Chunk并不知道文本長度何時超過文檔寬度并自動換行。你可以使用”\n”或者Environment.NewLine,甚至是Chunk.NEWLINE作為給Chunk對象賦值的一部分.
Chunk有一系列方法允許你為文本設置樣式,比如setUnderLine(), setBackGround(), 和 setTextRise()以及一些構造函數來設置字體類型以及風格.
Chunk chunk = new Chunk("Setting the Font", FontFactory.GetFont("dax-black"));chunk.SetUnderline(0.5f, -1.5f);</pre>
PHRASE
Phrase是比Chunk大一級的容器,Phrase可以理解為一組Chunk,并且會在長度超過文檔寬度后自動換行,每一行之間的行距(測量方法其實是每行底部之間的距離)是字體大小的1.5倍,因為在iTextSharp行距之間的舉例是12pt,所以下面代碼之間的行距為16pt.你可以在Phrase初始化的時候設置字體和行距.當然也可以通過其多種構造函數重載來在初始化時為Phrase添加內容.
下面代碼展示了前面3個chunk加入Phrase后展示的結果:
Phrase phrase = new Phrase();for (int i = 1; i < 4; i++)
{
phrase.Add(c1);
}</pre>
Paragraphs
目前為止,我們已經看到了如何在PDF中添加最基本的文本塊.而事實上你應該用的最多的類是Paragraphs.Paragraph其實是一組有序Phrase和Chunk的集合。Paragraph派生于Phrase,所以和Phrase一樣,Paragraph也會在長度超過文檔長度時自動換行.不僅如此,Paragraph和Paragraph之間也會自動空一行(就像文字處理軟件那樣),在本文前面Chunk部分對部分文字設置格式是我們日常經常需要的,所以下面代碼中,我會將格式化的文本通過Chunk和Phrase來添加到Paragraphs中:
string path = Server.MapPath("PDFs");Rectangle r = new Rectangle(400, 300);
Document doc = new Document(r);
try
{
PdfWriter.GetInstance(doc, new FileStream(path + "/Blocks2.pdf", FileMode.Create)); doc.Open(); string text = @"The result can be seen below, which shows the text having been written to the document but it looks a mess. Chunks have no concept of how to force a new line when the length exceeds the available width in the document. Really, all they should be used for is to change or set the style of a word or phrase inline. "; text = text.Replace(Environment.NewLine, String.Empty).Replace(" ", String.Empty); Font brown = new Font(Font.COURIER, 9f, Font.NORMAL, new Color(163, 21, 21)); Font lightblue = new Font(Font.COURIER, 9f, Font.NORMAL, new Color(43, 145, 175)); Font courier = new Font(Font.COURIER, 9f); Font georgia = FontFactory.GetFont("georgia", 10f); georgia.Color = Color.GRAY; Chunk beginning = new Chunk(text, georgia); Phrase p1 = new Phrase(beginning); Chunk c1 = new Chunk("You can of course force a newline using \"", georgia); Chunk c2 = new Chunk(@"\n", brown); Chunk c3 = new Chunk("\" or ", georgia); Chunk c4 = new Chunk("Environment", lightblue); Chunk c5 = new Chunk(".NewLine", courier); Chunk c6 = new Chunk(", or even ", georgia); Chunk c7 = new Chunk("Chunk", lightblue); Chunk c8 = new Chunk(".NEWLINE", courier); Chunk c9 = new Chunk(" as part of the string you give a chunk.", georgia); Phrase p2 = new Phrase(); p2.Add(c1); p2.Add(c2); p2.Add(c3); p2.Add(c4); p2.Add(c5); p2.Add(c6); p2.Add(c7); p2.Add(c8); p2.Add(c9); Paragraph p = new Paragraph(); p.Add(p1); p.Add(p2); doc.Add(p);
}
catch (DocumentException dex)
{
throw (dex);
}
catch (IOException ioex)
{
throw (ioex);
}
finally
{
doc.Close();
}</pre>
首先,來看結果,然后我再解釋代碼:
在代碼中添加異常處理并不是一件復雜的事,當然,每次越到關于IO的操作時,最好都要使用try…catch。對于iTextSharp的Document對象來說,還有DocumentException這個異常需要處理.我還在iTextSharp發現了其他幾個猥瑣的異常,當我寫測試代碼去生成PDF文件時,我不小心對Font對象的構造函數傳了兩個參數,我先傳入了Font.NORMAL,后傳入了文字大小,然后悲劇發生了,字體大小被設置成了0.在代碼執行到doc.Close()時拋出異常,我不得不強關了VS來釋放在內存中的PDF.
所以,異常處理非常重要,至少在document從內存釋放之前,你也需要注意字體類型傳入時,都要在后面加個f后綴,來表明編譯器它是FLOAT類型,這樣能防止你遇到和我同樣的錯誤。
第一塊文字,也就是@+引號,或者說是純文本,不允許中間有空格和換行符,否則空格和換行符就會原樣在PDF中顯示出來。除此之外,每一個設置了風格樣式的字體都需要包含在一個Chunk中,然后再將Chunk添加到Phrase來確保文字會自動換行,最后,所有Phrase和Chunk都會被添加到Paragraph對象中。還可以通過Paragraph.setAlignment()設置Paragraph的對齊方式,這個方法接受一個String類型的參數,可以是"Left", "Center", "Justify",和 "Right".下面是設置p.setAlignment("Justify");居中的顯示效果:
Paragraph還有許多其他的方法來設置縮進:
Paragraph.FirstLineIndent //allows you to apply a float value to indent the first line Paragraph.IndentationLeft //allows you to add space to the left hand side Paragraph.IndentationRight //allows you to add space to the right hand side Paragraph.setSpacingBefore //adds a specified amount of space above the paragraph Paragraph.setSpacingAfter //adds the specified amount of space after the paragraph