iText的showTextAligned方法

java使用itext的showTextAligned方法给pdf添加文字水印(watermark)

 

2013-07-22 17:39:59   来源:   评论:0 点击:3582

 

java的开源pdf库-Itext可以给pdf添加水印,主要是使用showTextAligned这个方法.ShowTextAligned方法可以设置输出水印的文本和水印文本的旋转角度,ShowTextAligned方法具体的参数说明如下:

public void ShowTextAligned(int alignment, String text, float x,float y, float rotation)

参数 参数说明:
alignment 左、右、居中(ALIGN_CENTER, ALIGN_RIGHT or ALIGN_LEFT)
text 要输出的文本
x 文本输入的X坐标
y 文本输入的Y坐标
rotation 文本的旋转角度

将itext-5.4.2.zip压缩包解压缩后得到7个文件:itextpdf-5.4.2.jar(核心组件)、itextpdf-5.4.2-javadoc.jar(API文档)、itextpdf-5.4.2-sources.jar(源代码)、itext-xtra-5.4.2.jar、itext-xtra-5.4.2-javadoc.jar、itext-xtra-5.4.2-sources.jar ,如果是输出中文pdf,需要用到itext-asian.jar这个jar包,这个jar包在extrajars-2.3.zip中,下载地址:请点这里

private static void addWatermark(PdfStamper pdfStamper
, String waterMarkName) {
PdfContentByte content = null;
BaseFont base = null;
Rectangle pageRect = null;
PdfGState gs = new PdfGState();
try { // 设置字体
base = BaseFont.createFont("STSongStd-Light",
"UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (base == null || pdfStamper == null) { return; }
// 设置透明度为0.4
gs.setFillOpacity(0.4f);
gs.setStrokeOpacity(0.4f);
int toPage = pdfStamper.getReader().getNumberOfPages();
for (int i = 1; i <= toPage; i++) {
pageRect = pdfStamper.getReader(). getPageSizeWithRotation(i);
// 计算水印X,Y坐标
float x = pageRect.getWidth() / 2;
float y = pageRect.getHeight() / 2;
//获得PDF最顶层
content = pdfStamper.getOverContent(i);
content.saveState();
// set Transparency
content.setGState(gs);
content.beginText();
content.setColorFill(BaseColor.GRAY);
content.setFontAndSize(base, 60);
// 水印文字成45度角倾斜
content.showTextAligned(Element.ALIGN_CENTER ,
waterMarkName, x, y, 45); content.endText(); }
} catch (Exception ex) {
ex.printStackTrace();
}
finally {
content = null;
base = null;
pageRect = null;
}
}

java使用itext的showTextAligned方法给pdf添加文字水印的完整代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sjmz30071360

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值