itext生成重复水印(watermark)
2015-07-30 10:13
357 查看
在这里只讲在生成pdf的文件过程中添加水印,至于向已存在的pdf文件中添加水印,那并不是本文所探讨的内容。
在网上搜了很多文字都不知道该怎么做。因为网上大部分都是讲的向已经存在的pdf文件中添加水印,而不是在写文件的过程中直接添加水印。
不过还是有找到下面的文章,itext in action学习笔记,使我很快找到了办法。那就是通过添加pageEvent事件解决。
代码如下:
不过水印只是出来了一条,并没有我想想的多条。
后来只有硬着头皮看itext5的文档《itext in action》 second Edition英文版,结果还是没正明白。
于是还是只有在网上搜,结果收到下面的一个问答,里面的提问及回答给了我很大的启示
看来还是得在pageEvent中做文章。有过了许久,突然灵光一线。出现一条就用一次,出现多条,用个循环打印不就是了吗?于是赶紧先看看ColumnText的ShowTextAligned()方法的api文档。
果然发现有横纵坐标的参数。于是乎将自定义的Watermark类改为如下:
问题自然就解决了。
在网上搜了很多文字都不知道该怎么做。因为网上大部分都是讲的向已经存在的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); } } } }
问题自然就解决了。
相关文章推荐
- javascript取当月最后一天
- Jeecms之编辑器表格对齐及图片插入
- Jeecms之new标签实现
- 实时提示输入字节数
- Oracle_SQL_序列与groupby同时用
- itext生成只读pdf文档
- iframe 中关闭父窗口的弹窗
- plsql连接异常问题
- java正则过滤html标签属性
- 策略模式小练习
- IE8按f12无反应
- HDOJ-1232 畅通工程
- Java串口助手(程序源码)
- Android Studio三种方式导入外部资源 以及 报错处理
- 生产环境常见的HTTP状态码列表
- GitHub使用for Eclipse
- Java串口助手(程序源码) 分类: Java 2015-07-30 10:13 16人阅读 评论(0) 收藏
- acedinitget
- Jeecms之固定取消不了
- 举例说明Java中代码块的执行顺序