本文将详细讲解如何使用spire.pdf for java 为pdf文档添加文本水印。
import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.geom.*;
public class textwatermark {
public static void main(string[] args) {
//创建pdfdocument对象
pdfdocument pdf = new pdfdocument();
//加载示例文档
pdf.loadfromfile("c:\\users\\administrator\\desktop\\sample.pdf");
//获取第一页
pdfpagebase page = pdf.getpages().get(0);
//调用insertwatermark方法插入文本水印
insertwatermark(page, "e-iceblue");
//保存文档
pdf.savetofile("out/textwatermark.pdf");
}
static void insertwatermark(pdfpagebase page, string watermark) {
dimension2d dimension2d = new dimension();
dimension2d.setsize(page.getcanvas().getclientsize().getwidth() / 2, page.getcanvas().getclientsize().getheight() / 3);
pdftilingbrush brush = new pdftilingbrush(dimension2d);
brush.getgraphics().settransparency(0.3f);
brush.getgraphics().save();
brush.getgraphics().translatetransform((float) brush.getsize().getwidth() / 2, (float) brush.getsize().getheight() / 2);
brush.getgraphics().rotatetransform(-45);
brush.getgraphics().drawstring(watermark, new pdffont(pdffontfamily.helvetica, 24), pdfbrushes.getviolet(), 0, 0, new pdfstringformat(pdftextalignment.center));
brush.getgraphics().restore();
brush.getgraphics().settransparency(1);
rectangle2d lorect = new rectangle2d.float();
lorect.setframe(new point2d.float(0, 0), page.getcanvas().getclientsize());
page.getcanvas().drawrectangle(brush, lorect);
}
}