本文介绍使用spire.pdf for java加载图片来设置成pdf平铺图片背景的效果,也可以作为平铺图片水印来使用;一般设置时可设置倾斜效果,这里设置图片背景(水印)也可以设置倾斜效果,具体可参考代码示例。
import com.spire.pdf.*;
import com.spire.pdf.graphics.pdfimage;
import com.spire.pdf.graphics.pdftilingbrush;
import java.awt.*;
import java.awt.geom.dimension2d;
import java.awt.geom.rectangle2d;
public class addbackground {
public static void main(string[] args) {
//创建pdfdocument对象,并加载pdf测试文档
pdfdocument pdf = new pdfdocument();
pdf.loadfromfile("test.pdf");
//遍历文档每一页,加载图片,并设置成平铺背景(水印)
for (int i = 0; i < pdf.getpages().getcount();i )
{
pdfpagebase page = pdf.getpages().get(i);
dimension2d dimension2d = new dimension();
dimension2d.setsize(page.getcanvas().getsize().getwidth()/4, page.getcanvas().getsize().getheight()/3);
pdftilingbrush brush = new pdftilingbrush(dimension2d);
brush.getgraphics().settransparency(0.2f);
brush.getgraphics().translatetransform(brush.getsize().getwidth()/10,brush.getsize().getheight()/10);
brush.getgraphics().rotatetransform(30);
pdfimage image = pdfimage.fromimage("logo.png");
brush.getgraphics().drawimage(image,brush.getsize().getwidth()-image.getwidth()/2,(brush.getsize().getheight())/2);
rectangle2d rectangle2d = new rectangle2d.float();
rectangle2d.setframe(new point(0,0),page.getcanvas().getclientsize());
page.getcanvas().drawrectangle(brush,rectangle2d);
}
//保存文档
pdf.savetofile("settiledbackground.pdf");
pdf.dispose();
}
}
平铺图片背景(水印)效果: