使用Free Spire.PDF for Java 产品,为PDF添加印章
① 下载JAR包或使用Maven仓库
② Java代码示例
//创建PdfDocument对象,加载PDF文档
PdfDocument doc = new PdfDocument();
doc.loadFromStream(new ByteArrayInputStream(buffer.toByteArray()));
//获取文档最后一页
PdfPageBase page = doc.getPages().get(doc.getPages().getCount()-1);
//加载印章图片
PdfImage image = PdfImage.fromStream(new URL(Const.oSSFilePath+productAgreement.getContractSeal()).openStream());
//获取印章图片的宽度和高度
int width = image.getWidth();
int height = image.getHeight();
//创建PdfTemplate对象
PdfTemplate template = new PdfTemplate(width, height);
//将图片绘制到模板
template.getGraphics().drawImage(image, 0, 0, width, height);
//创建PdfRubebrStampAnnotation对象,指定大小和位置
Rectangle2D rect = new Rectangle2D.Float((float) (page.getActualSize().getWidth() - productAgreement.getAbscissa()), (float) (page.getActualSize().getHeight() - productAgreement.getOrdinate()),productAgreement.getSealWidth(),productAgreement.getSealHeight() );
PdfRubberStampAnnotation stamp = new PdfRubberStampAnnotation(rect);
//创建PdfAppearance对象
PdfAppearance pdfAppearance = new PdfAppearance(stamp);
//将模板应用为PdfAppearance的一般状态
pdfAppearance.setNormal(template);
//将PdfAppearance 应用为图章的样式
stamp.setAppearance(pdfAppearance);
//添加图章到PDF
page.getAnnotationsWidget().add(stamp);
String filePath = "pdf/预览协议.pdf";
//保存文档
doc.saveToFile(filePath,FileFormat.PDF);
//上传阿里云
AliOSSClientController aliOssClientCont = new AliOSSClientController();
OSSClient ossClient = aliOssClientCont.getOSSClient();
ossClient.putObject(Const.bucketName, filePath, new FileInputStream(filePath));
ossClient.shutdown();
注:自定义数据
印章图片地址:productAgreement.getContractSeal()
印章宽度:productAgreement.getSealWidth()
印章长度:productAgreement.getSealWidth()
印章位置横坐标:productAgreement.getSealWidth()
印章位置纵坐标:productAgreement.getSealWidth()