pdf 添加电子签名

 用到的依赖:

        
        
            com.itextpdf
            itextpdf
            5.5.13
        
        
            com.itextpdf
            itext-asian
            5.2.0
        
        
            org.bouncycastle
            bcpkix-jdk15on
            1.64
        
        
        
            org.apache.pdfbox
            pdfbox
            2.0.20
        
        

 直接上代码:

package com.secxiot.common.utils;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * 用户签名书
 */
public class SignWriteToPDF {
    /**
     * signImagePath 签名图片
     * inputPDFPath 原文件路径
     * outPDFPath 输出文件路径
     */
    public static void setWaterPrint(String outPDFPath, String inputPDFPath, String signImagePath) throws DocumentException, IOException {
        BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        InputStream input = new FileInputStream(new File(inputPDFPath));
        PdfReader reader = new PdfReader(input);

        OutputStream output = new FileOutputStream(new File(outPDFPath));
        PdfStamper stamper = new PdfStamper(reader, output);
        PdfContentByte page = stamper.getOverContent(1);

        //将文字贴入pdf
       /* page.beginText();
        page.setFontAndSize(baseFont,12);
        BaseColor coler = new BaseColor(0, 0, 0);
        page.setColorFill(coler);
        page.setTextMatrix(100,500); //设置文字在页面中的坐标
        page.showText("66666666666666666");
        page.endText();*/

        //将图片贴入pdf
        Image image = Image.getInstance(signImagePath);
        image.setAbsolutePosition(480, 130); //设置图片在页面中的坐标
        //image.scalePercent(20);//依照比例缩放
        image.setRotationDegrees(90);//旋转 角度

        image.scaleAbsolute(image.getWidth()/10, image.getWidth()/10);
        page.addImage(image);

        stamper.close();
        reader.close();
        input.close();
    }

    public static void main(String[] args) throws DocumentException, IOException {
        setWaterPrint("H:\\photo\\spatient_sign_48.pdf", "H:\\photo\\spatient_sign.pdf", "H:\\photo\\711664989302785.png");
    }

    /**
     *
     * @param pdfPath pdf 路径
     * @param imgPath 图片路径
     * @param imgType 图片类型
     */
    public static void pdfTOimg(String pdfPath, String imgPath, String imgType) {
        File file = new File(pdfPath);
        try {
            PDDocument doc = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            for(int i=0;i

 

你可能感兴趣的:(java)