您的位置:首页 > 其它

itext生成重复水印(watermark)

2015-07-30 10:13 302 查看
    在这里只讲在生成pdf的文件过程中添加水印,至于向已存在的pdf文件中添加水印,那并不是本文所探讨的内容。

    在网上搜了很多文字都不知道该怎么做。因为网上大部分都是讲的向已经存在的pdf文件中添加水印,而不是在写文件的过程中直接添加水印。

    不过还是有找到下面的文章,itext in action学习笔记,使我很快找到了办法。那就是通过添加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英文版,结果还是没正明白。

    于是还是只有在网上搜,结果收到下面的一个问答,里面的提问及回答给了我很大的启示

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

    问题自然就解决了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: