在Asp.Net中操作PDF – iTextSharp -利用块,短语,段落添加文本

MadSwinburn 8年前

转自: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);     }

[接下来的一段你要格外注意,我们后面还要用到]

   结果如下,可以看出文本已经被加入文档,但显示出来却是一团乱麻.Chunk并不知道文本长度何时超过文档宽度并自动换行。你可以使用”\n”或者Environment.NewLine,甚至是Chunk.NEWLINE作为给Chunk对象赋值的一部分.

    1

    Chunk有一系列方法允许你为文本设置样式,比如setUnderLine(), setBackGround(), 和 setTextRise()以及一些构造函数来设置字体类型以及风格.

Chunk chunk = new Chunk("Setting the Font", FontFactory.GetFont("dax-black"));     chunk.SetUnderline(0.5f, -1.5f);

    2

    

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

    3

 

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

首先,来看结果,然后我再解释代码:

 

     4

 

   在代码中添加异常处理并不是一件复杂的事,当然,每次越到关于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");居中的显示效果:

     5

    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