JAVA操作PDF实现简单盖章功能(未签字)

默认再第一页签章:https://www.cnblogs.com/wolf-shuai/p/16977802.html

摘要:

jar包准备:

bcpkix-jdk15on-1.70.jar

bcprov-jdk15on-1.70.jar

iTextAsian.jar

itextpdf-5.5.13.3.jar

签章图片:

 

 

上面链接只能实现第一页的签章

下面是体现到pdf文章末尾页签章

package cn.tomtocc.demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

public class pageDemoUtils {

    public static void main(String[] args)throws Exception {
    Document document=null;
        PdfStamper stamper=null;
        PdfReader reader=null;
        try {

            // 模板文件路径
            String templatePath = "F:\\signinfo\\gongwen2.pdf";
            // 生成的文件路径
            String targetPath = "F:\\signinfo\\gongwen4.pdf";
            // 书签名
            String fieldName = "texts";
            // 图片路径
            String imagePath = "F:\\signinfo\\2.png";




            // 读取模板文件
            InputStream input = new FileInputStream(new File(templatePath));
            reader = new PdfReader(input);
            //获取页数
            int pagecount= reader.getNumberOfPages();

            stamper = new PdfStamper(reader, new FileOutputStream(
                    targetPath));

            document = new Document(reader.getPageSize(1));

            // 获取页面宽度
            float width = document.getPageSize().getWidth();
            // 获取页面高度
            float height = document.getPageSize().getHeight();
            System.out.println("width = "+width+", height = "+height);

            // 读图片
            Image image = Image.getInstance(imagePath);
            // 根据域的大小缩放图片
            image.scaleToFit(150, 150);

            image.setAbsolutePosition(width-150-50, 50);

            // 获取操作的页面  根据pagecount给pdf最后一页添加签章
            PdfContentByte under = stamper.getOverContent(pagecount);
            // 添加图片
            under.addImage(image);
            /*for (int i=1;i<=pagecount;i++) {
                // 获取操作的页面
                PdfContentByte under = stamper.getOverContent(i);
                // 添加图片
                under.addImage(image);
            }*/

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(document!=null){
                document.close();
            }
            if(stamper!=null) {
                stamper.close();
            }
                if(reader!=null) {
                    reader.close();
                }
        }
    }

}

 

posted @ 2022-12-13 11:13  Ferocious  阅读(1675)  评论(0编辑  收藏  举报