下载老版的spire.pdf.jar,就会在一页有水印,添加一页pdf,然后删掉最后一页就可以了;
jar资源地址:spire.pdf-3.7.4.jar
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.IOException;import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.junit.Test;import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
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 com.spire.pdf.widget.PdfPageCollection;public class SomeTest {public static void main(String[] args) {//创建PdfDocument对象,加载PDF测试文档PdfDocument doc = new PdfDocument();doc.loadFromFile("xxx.pdf");System.out.println(doc.getPages().getCount());//添加空白文档doc.getPages().add();PdfPageCollection pages = doc.getPages();System.out.println(pages.getCount());for (int i = 0; i < pages.getCount(); i++) {PdfPageBase page = doc.getPages().get(i);PdfRubberStampAnnotation stamp = getStamp(page);//添加图章到PDFpage.getAnnotationsWidget().add(stamp);}System.out.println(doc.getPages().getCount());//保存文档doc.saveToFile("ImageStamp.pdf", FileFormat.PDF);//删除空白文档removeLast("ImageStamp.pdf");}private static void removeLast(String filePath) {try {// 加载PDF文档PDDocument document = PDDocument.load(new File(filePath));int pageNumberToRemove = document.getPages().getCount() - 1;// 获取要删除的页PDPage pageToRemove = document.getPage(pageNumberToRemove);// 删除页document.removePage(pageToRemove);// 保存修改后的PDFdocument.save(new File(filePath));// 关闭文档document.close();System.out.println("成功删除第 " + pageNumberToRemove + " 页!");} catch (IOException e) {e.printStackTrace();}}private static PdfRubberStampAnnotation getStamp(PdfPageBase page) {//加载印章图片PdfImage image = PdfImage.fromFile("章.png");//获取印章图片的宽度和高度int width = image.getWidth();int height = image.getHeight();//创建PdfTemplate对象PdfTemplate template = new PdfTemplate(width, height);//将图片绘制到模板 要在pdf上调整好大小template.getGraphics().drawImage(image, 50, 0, 100, 100);//创建PdfRubebrStampAnnotation对象,指定大小和位置Rectangle2D rect = new Rectangle2D.Float((float) (page.getActualSize().getWidth() - width - 0),(float) (page.getActualSize().getHeight() - height + 50), width, height);PdfRubberStampAnnotation stamp = new PdfRubberStampAnnotation(rect);//创建PdfAppearance对象PdfAppearance pdfAppearance = new PdfAppearance(stamp);//将模板应用为PdfAppearance的一般状态pdfAppearance.setNormal(template);//将PdfAppearance 应用为图章的样式stamp.setAppearance(pdfAppearance);return stamp;}
}