JAVA给PDF添加水印

Shaka 3月前 ⋅ 65 阅读

 

网上看到的本应该是从源文件添加水印到目标文件.但是我不想要目标文件改了一点.

//添加水印
waterMark(importantPath,"Yaxincheng");
private void waterMark(String inputFile,String waterMarkName) {
int interval = -5;
File file = new File(inputFile);
String outputFile = inputFile.replace(file.getName(),"temp"+file.getName());
try {
PdfReader reader = new PdfReader(inputFile);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(
outputFile));

BaseFont base = BaseFont.createFont("C:/WINDOWS/Fonts/Arial.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

Rectangle pageRect;
PdfGState gs = new PdfGState();
gs.setFillOpacity(0.05f);
gs.setStrokeOpacity(0.4f);
int total = reader.getNumberOfPages() + 1;

JLabel label = new JLabel();
FontMetrics metrics;
int textH = 0;
int textW = 0;
label.setText(waterMarkName);
metrics = label.getFontMetrics(label.getFont());
textH = metrics.getHeight();
textW = metrics.stringWidth(label.getText());

PdfContentByte under;
for (int i = 1; i < total; i++) {
pageRect = reader.getPageSizeWithRotation(i);
under = stamper.getOverContent(i);
under.saveState();
under.setGState(gs);
under.beginText();
under.setFontAndSize(base, 80);

// 水印文字成30度角倾斜
//你可以随心所欲的改你自己想要的角度
for (int height = interval + textH; height < pageRect.getHeight();
height = height + textH*20) {
for (int width = interval + textW; width < pageRect.getWidth() + textW;
width = width + textW*6) {
under.showTextAligned(Element.ALIGN_LEFT
, waterMarkName, width - textW*2,
height - textH*2, 50);
}
}
// 添加水印文字
under.endText();
}
//说三遍
//一定不要忘记关闭流
//一定不要忘记关闭流
//一定不要忘记关闭流
stamper.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
new File(inputFile).delete();;
new File(outputFile).renameTo(new File(inputFile));
}

注意:本文归作者所有,未经作者允许,不得转载

全部评论: 0

    我有话说: