阅读提示
1. 本文仅做应用文, 不会太深入
2. 推荐使用itextPdf去实现功能
3. pdfbox我实在找不到办法去添加中文水印 , 谁要是会, 教我一下
itextPdf添加文字水印
导入依赖
```
```
因为业务要求比较麻烦, 要将文件经历置灰 , 水印 , 盖章等步骤,所以在上传保存文件之前,
需要pdf文件一直处于字节数组的状态
代码展示:
public static boolean addWatermarktext(byte[] infile,String outfile,String text ) {
try {
PdfReader reader =new PdfReader(infile);
//修改后的PDF将会存入bao
ByteArrayOutputStream bao =new ByteArrayOutputStream();
PdfStamper stamper =new PdfStamper(reader,bao);
// PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outfile));
// 字体设置支持中文
BaseFont base =BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.EMBEDDED);
int total =reader.getNumberOfPages() +1;
PdfContentByte under;
Rectangle pageRect =null;
for(int i =1 ; i< total; i++){
pageRect =stamper.getReader().getPageSizeWithRotation(i);
//计算水印的位置
float x = pageRect.getWidth()/3 -50;
float y = pageRect.getHeight()/3 -20;
// 获得PDF最顶层
under =stamper.getOverContent(i);
under.saveState();
// 设置透明度为0.3
PdfGState gs =new PdfGState();
gs.setFillOpacity(0.3f);
under.setGState(gs);
//开始加入水印
under.beginText();
under.setFontAndSize(base,45);
under.setColorFill(BaseColor.RED);
// 水印文字成45度角倾斜
under.showTextAligned(Element.ALIGN_LEFT, text,x,y,45);
// 添加水印文字结束
under.endText();
under.setLineWidth(1f);
under.stroke();
}
stamper.close();
byte[]byteArray =bao.toByteArray();
byte2File(byteArray,"d:/logs","a.pdf");
return true;
}catch (Exception e) {
e.printStackTrace();
return false;
}
}
```
新生成的PDF:
pdfbox添加文字水印
引入依赖
代码展示:
private static byte[]watermarkPDF (byte[] fileStored){
byte[] byteArray =null;
try{
ByteArrayOutputStream bos =new ByteArrayOutputStream();
PDDocument doc =PDDocument.load(fileStored);
doc.setAllSecurityToBeRemoved(true);
for(PDPage page:doc.getPages()){
PDPageContentStream cs =new PDPageContentStream(doc,page,PDPageContentStream.AppendMode.APPEND,true,true);
String ts ="confidential document";
PDFont font =PDType1Font.HELVETICA_OBLIQUE;
float fontSize =50.0f;
PDExtendedGraphicsState r0 =new PDExtendedGraphicsState();
// 透明度
r0.setNonStrokingAlphaConstant(0.2f);
r0.setAlphaSourceFlag(true);
cs.setGraphicsStateParameters(r0);
cs.setNonStrokingColor(200,0,0);//Red
cs.beginText();
cs.setFont(font,fontSize);
// 获取旋转实例
cs.setTextMatrix(Matrix.getRotateInstance(45,150f,150f));
cs.showText(ts);
cs.endText();
cs.close();
}
doc.save(bos);
byteArray =bos.toByteArray();
}catch (Exception e) {
e.printStackTrace();
}
return byteArray;
}
生成的PDF: