本教程展示如何使用spire.pdf for java在pdf中添加图片图章。
import com.spire.pdf.annotations.pdfrubberstampannotation;
import com.spire.pdf.annotations.appearance.pdfappearance;
import com.spire.pdf.graphics.pdfimage;
import com.spire.pdf.graphics.pdftemplate;
import java.awt.geom.rectangle2d;
public class imagestamp {
public static void main(string[] args) {
//创建pdfdocument对象
pdfdocument doc = new pdfdocument();
//加载pdf文档
doc.loadfromfile("c:\\users\\administrator\\desktop\\test.pdf");
//获取第一页
pdfpagebase page = doc.getpages().get(0);
//加载图片到pdfimage对象
pdfimage image = pdfimage.fromfile("c:\\users\\administrator\\desktop\\quality-control-stamp.png");
//获取图片高宽
int width = image.getwidth();
int height = image.getheight();
//创建pdftemplate对象,大小跟图片一致
pdftemplate template = new pdftemplate(width, height);
//在模板上绘制图片
template.getgraphics().drawimage(image, 0, 0, width, height);
//创建pdfrubebrstampannotation对象,指定大小和位置
rectangle2d rect = new rectangle2d.float((float) (page.getactualsize().getwidth() - width - 50), (float) (page.getactualsize().getheight() - height - 80), width, height);
pdfrubberstampannotation stamp = new pdfrubberstampannotation(rect);
//创建pdfappearance对象
pdfappearance pdfappearance = new pdfappearance(stamp);
//将模板应用为pdfappearance的一般状态
pdfappearance.setnormal(template);
//将pdfappearance 应用为图章的样式
stamp.setappearance(pdfappearance);
//添加图章到pdf
page.getannotationswidget().add(stamp);
//保存文档
doc.savetofile("imagestamp.pdf");
doc.close();
}
}