图片盖章
// 将原来的证书图片画到pdf文件上
File originalPdf = new File( "图片画到pdf上.pdf");
com.itextpdf.text.Document tDoc = new com.itextpdf.text.Document(PageSize.A4, 50, 50, 50, 50);
FileOutputStream osWithOriginal = new FileOutputStream(originalPdf);
PdfWriter tWriterWithOriginal = PdfWriter.getInstance(tDoc, osWithOriginal);
tDoc.open();
com.itextpdf.text.Image tImgCover = com.itextpdf.text.Image.getInstance(RequestHelp.getFileFromOss(图片服务器之图片地址));
tImgCover.setAbsolutePosition(0, 0);
tImgCover.scaleAbsolute(595, 842);
tDoc.add(tImgCover);
osWithOriginal.flush();
tWriterWithOriginal.flush();
tDoc.close();
// 给原证书pdf文件加盖一个“已过期”印章的图层,并生成新的过期证书pdf文件
File newPdf = new File("图片盖章.pdf");
PdfReader pdfReader = new PdfReader(originalPdf.getCanonicalPath());
FileOutputStream osWithBackground = new FileOutputStream(newPdf);
PdfStamper pdfStamper = new PdfStamper(pdfReader, osWithBackground);
ClassLoader classLoaderToUse = ClassUtils.getDefaultClassLoader();
// war包/WEB-INFO/classes下
Enumeration<URL> backgroundPngUrls = classLoaderToUse.getResources("xxx/印章.png");
URL backgroundPngUrl;
if (backgroundPngUrls.hasMoreElements()) {
backgroundPngUrl = backgroundPngUrls.nextElement();
} else {
throw new 业务Exception(业务code, "获取背景图片失败!");
}
com.itextpdf.text.Image tExpiredImgCover = com.itextpdf.text.Image.getInstance(backgroundPngUrl);
tExpiredImgCover.setAbsolutePosition(360, 562);
tExpiredImgCover.scaleAbsolute(100, 100);
PdfContentByte content = pdfStamper.getOverContent(1);
content.addImage(tExpiredImgCover);
content.stroke();
osWithBackground.flush();
pdfStamper.close();
pdfReader.close();
// 过期证书pdf文件 -> png
File imageFile = new File("盖好章的图片.png");
Document document = new Document();
document.setFile(newPdf.getCanonicalPath());
BufferedImage image = (BufferedImage) document.getPageImage(0, GraphicsRenderingHints.SCREEN, 1, 0f, 2.5f);
ImageIO.write(image, "png", imageFile);
image.flush();
document.dispose();
// finally删除中间文件和关闭流
总结:
1,pdf两个图层融合的时候会出现边框痕迹,如下:
可以如下这样处理:
如上图,以小的页面为主,大的页面没有在小的页面上留下任何痕迹;