@Override
public ByteArrayInputStream addLogo(ByteArrayOutputStream out) {
ByteArrayInputStream bais = new ByteArrayInputStream(out.toByteArray());
PdfReader reader = null;
try {
reader = new PdfReader(bais);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteArrayOutputStream os = new ByteArrayOutputStream();
PdfStamper stamper = null;
try {
stamper = new PdfStamper(reader, os);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteArrayInputStream result = null;
try {
//获取印章图片
Image image = Image.getInstance(this.getClass().getClassLoader().getResource(fileName));
//获取盖章位置
float startX = 0;
float startY = 0;
int pageNum = 1;
//转换坐标
Rectangle pageRect = reader.getPageSize(pageNum);
float pageHeight = pageRect.getHeight();
image.scalePercent(30);
Rectangle rect = placeImageUpsideDown(startX, startY, image, pageHeight);
PdfContentByte contentByte = stamper.getOverContent(pageNum);
image.setAlignment(1);
image.setAbsolutePosition(80, 770);
contentByte.addImage(image);
if (stamper != null) {
stamper.close();
}
result = new ByteArrayInputStream(os.toByteArray());
// FileUtils.writeByteArrayToFile(new File("D:/tt.pdf"), os.toByteArray());
} catch (BadElementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
org.apache.commons.io.IOUtils.closeQuietly(os);
if (reader != null) {
reader.close();
}
stamper = null;
reader = null;
}
return result;
}
public Rectangle placeImageUpsideDown(float startX, float startY, Image image, float pageHeight) {
float llx = startX;
float lly = pageHeight - startY - image.getScaledHeight();
float urx = llx + image.getScaledWidth();
float ury = lly + image.getScaledHeight();
return new Rectangle(llx, lly, urx, ury);
}
pdf添加logo
最新推荐文章于 2022-07-15 17:39:03 发布