本教程展示如何使用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();
}
}