itext生成重复水印(watermark)

编程技术  /  houtizong 发布于 3年前   280
    在这里只讲在生成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文档。
showTextAlignedpublic 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 toalignment - the alignmentphrase - the Phrase with the textx - the x reference positiony - the y reference positionrotation - 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;}@Overridepublic 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);}}}}
 
    问题自然就解决了。

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!

留言需要登陆哦

技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成

网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];

      订阅博客周刊 去订阅

文章归档

文章标签

友情链接

Auther ·HouTiZong
侯体宗的博客
© 2020 zongscan.com
版权所有ICP证 : 粤ICP备20027696号
PHP交流群 也可以扫右边的二维码
侯体宗的博客