先引入pom引入jar包
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.0.6</version>
</dependency>
第一步切割图片
/**
* 切割图片
* @param Path 图片路径
* @param n 切割份数
*/
public static Image[] slicingImages(String Path,int n) throws IOException, BadElementException {
Image[] nImage = new Image[n];
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedImage img = ImageIO.read(new File(Path));
int h = img.getHeight();
int w = img.getWidth();
int sw = w/n;
for(int i=0;i<n;i++){
BufferedImage subImg;
if(i==n-1){//最后剩余部分
subImg = img.getSubimage(i * sw, 0, w-i*sw, h);
}else {//前n-1块均匀切
subImg = img.getSubimage(i * sw, 0, sw, h);
}
ImageIO.write(subImg,Path.substring(Path.lastIndexOf('.')+1),out);
nImage[i] = Image.getInstance(out.toByteArray());
out.flush();
out.reset();
}
return nImage;
}
第二步盖!!!
/**
* 盖骑缝章
*
* @param infilePath 原PDF路径
* @param outFilePath 输出PDF路径
*/
public static void stamperCheckMarkPDF(String infilePath,String outFilePath,String picPath) throws IOException, DocumentException {
PdfReader reader = new PdfReader(infilePath);//选择需要印章的pdf
PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(outFilePath));//加完印章后的pdf
Rectangle pageSize = reader.getPageSize(1);//获得第一页
float height = pageSize.getHeight();
float width = pageSize.getWidth();
int nums = reader.getNumberOfPages();
Image[] nImage = slicingImages(picPath,nums);//生成骑缝章切割图片
for(int n=1;n<=nums;n++){
PdfContentByte over = stamp.getOverContent(n);//设置在第几页打印印章
Image img = nImage[n-1];//选择图片
img.setAbsolutePosition(width-img.getWidth(),height/2-img.getHeight()/2);//控制图片位置
over.addImage(img);
}
stamp.close();
}
最后一步调用
public static void main(String[] args) throws IOException, DocumentException {
String infilePath = "C:\\Users\\Best\\Desktop\\test.pdf";
String outfilePaht = "C:\\Users\\Best\\Desktop\\test112.pdf";
String picPath = "C:\\Users\\Best\\Desktop\\签章1.png";
stamperCheckMarkPDF(infilePath,outfilePaht,picPath);
}
因为签章是公司的就不给大家展示了,直接CV大法试试效果
近期部分同学一直说他们的环境使用上述环境PDF会有问题,今天我又拉下来测试了一下,没发现什么问题。就是要注意一下方法导包时候都选itextpdf包下的方法