itext生成重复水印(watermark)

在这里只讲在生成pdf的文件过程中添加水印,至于向已存在的pdf文件中添加水印,那并不是本文所探讨的内容。
在网上搜了很多文字都不知道该怎么做。因为网上大部分都是讲的向已经存在的pdf文件中添加水印,而不是在写文件的过程中直接添加水印。
不过还是有找到下面的文章,[url=http://www.cnblogs.com/julyluo/archive/2012/07/20/2601641.html]itext in action学习笔记[/url],使我很快找到了办法。那就是通过添加pageEvent事件解决。
代码如下:

writer.setPageEvent(new Watermark("HELLO WORLD"));//水印内容

//在继承自PdfPageEventHelper类中的OnEndPage方法中添加水印
public void OnEndPage(PdfWriter writer, Document document) {
ColumnText.ShowTextAligned(writer.DirectContent,
Element.ALIGN_RIGHT,
header[0],
100.0f,
200.0f,
0);
}


不过水印只是出来了一条,并没有我想想的多条。
后来只有硬着头皮看itext5的文档《itext in action》 second Edition英文版,结果还是没正明白。
于是还是只有在网上搜,结果收到下面的[url=http://itext-general.2136553.n4.nabble.com/watermarks-td2140784.html]一个问答[/url],里面的提问及回答给了我很大的启示

That method is obsolete.
Use page events to add watermarks (as many as you want).
br,
Bruno

看来还是得在pageEvent中做文章。有过了许久,突然灵光一线。出现一条就用一次,出现多条,用个循环打印不就是了吗?于是赶紧先看看ColumnText的ShowTextAligned()方法的api文档。

showTextAligned
public static void showTextAligned(PdfContentByte canvas,
int alignment,
Phrase phrase,
float x,
float y,
float rotation)Shows a line of text. Only the first line is written.

Parameters:
canvas - where the text is to be written to
alignment - the alignment
phrase - the Phrase with the text
x - the x reference position
y - the y reference position
rotation - the rotation to be applied in degrees counterclockwise

果然发现有横纵坐标的参数。于是乎将自定义的Watermark类改为如下:

public class Watermark extends PdfPageEventHelper {
Font FONT = new Font(FontFamily.HELVETICA, 30, Font.BOLD, new GrayColor(0.95f));
private String waterCont;//水印内容
public Watermark() {

}
public Watermark(String waterCont) {
this.waterCont = waterCont;
}

@Override
public void onEndPage(PdfWriter writer, Document document) {
for(int i=0 ; i<5; i++) {
for(int j=0; j<5; j++) {
ColumnText.showTextAligned(writer.getDirectContentUnder(),
Element.ALIGN_CENTER,
new Phrase(this.waterCont == null ? "HELLO WORLD" : this.waterCont, FONT),
(50.5f+i*350),
(40.0f+j*150),
writer.getPageNumber() % 2 == 1 ? 45 : -45);
}
}
}
}

问题自然就解决了。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值