spire.pdf盖章(无水印免费无限制)

下载老版的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);
      //添加图章到PDF
      page.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);

      // 保存修改后的PDF
      document.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;
  }
}

你可能感兴趣的:(pdf,java,pdf盖章,spire.pdf)