当一页完成时,4 层的重叠遵照如下顺序:
1、 通过 DirectContentUnder得到的 PdfContentByte
2、 包含图象或高级对象的内部 PdfContentByte
3、 通过文本或高级对象的内部 PdfContentByte
4、 通过DirectContent得到的 PdfContentByte
绘图,前面已经介绍
cb.LineWidth = 10f;
cb.moveTo(100, 700);
cb.lineTo(200, 800);
cb.stroke();
随意位置输入文字
PdfContentByte contentbyte =
writer.DirectContentUnder;
BaseFont bfwryh = BaseFont.CreateFont(@"H:\备份\resources1\微软雅黑.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
//设置字体
contentbyte.SetFontAndSize(bfwryh, 12);
iTextSharp.text.Font font = new iTextSharp.text.Font(bfwryh,18);
contentbyte.BeginText();
contentbyte.ShowTextAligned(PdfContentByte.ALIGN_CENTER,
"This text is centered", 250, 700, 0);//设置文件
contentbyte.EndText();
contentbyte.BeginText();
contentbyte.MoveText(11,22);//移动文本的位置
contentbyte.NewlineShowText("22222222222");
contentbyte.EndText();
contentbyte.BeginText();
contentbyte.SetTextMatrix(100, 400);
contentbyte.ShowText("这是中文字体测试-------------");
contentbyte.EndText();
模板(Form xObjects
当我们在第四章讨论页眉和页脚时,我们定义了一小块添加到每一页的信息,实际上,该小块信息写到了文件的每一个新页上。这并不是最经济的解决方案,更好的办法是将该信息作为一个 Form Xobject 仅在文档中添加一次,在其可见位置重复出现。我达到该目的,我们将使用模板
PdfTemplate template = cb.CreateTemplate(500, 200);//该模板的宽度为 500,高度为
200。
//通过该模板我们可以做象 PdfContentByte 同样的事情
template.MoveTo(0, 200);
template.LineTo(500, 0);
template.Stroke();
template.BeginText();
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA,
BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
template.SetFontAndSize(bf, 12);
template.SetTextMatrix(100, 100);
template.ShowText("Text at the position 100,100
(relative to the template!)");
template.EndText();
//添加一个模板到文档
//通过象下面一样在绝对位置添加一个模板:
cb.AddTemplate(template, 0, 400);
//你还可以做一些有趣的事情,如缩放或旋转他们:
//将模板旋转 90 度
cb.AddTemplate(template, 0, 1, -1, 0, 500, 200);
// 缩放模板为 50%
cb.AddTemplate(template, .5f, 0, 0, .5f, 100, 400);
//缩放模板为150%
cb.AddTemplate(template, 1.5, 0, 0, 1.5, -200, 400);
第几页共几页
在一些情况下,你希望插入一些你在写本页时外壳无法知道的信息到文本中去,如:在一篇文档的第一页,你并不知道该文档共有几页。只能在完成了整个文档时才知道总的页数。当使用模板时,该问题就不存在了。在示例代码 0103中,我们在添加模板到 ContentByte 前添加了一些信息到模板中,这是没有必要的。我们可以在任何时候添加信息到模板,因为 iText 添加 Form Xobject 是在PDF 结束的地方(当通过 close 方法关闭该文档时调用)。示例代码 1004 显示了首先创建 4 页然后添加总到页数,该例非常简单和有用。
//在doc.Close()前模板可以做任何事
template.ShowTextAligned(PdfContentByte.ALIGN_LEFT,
"共40页",100
,20f,0);
template.EndText();