在最近一次自己搗鼓中,發現給PDF添加文字水印並不方便,有的說要下載Adobe的軟件,有的在線pdf添加水印的網站,試過之後發現只能添加一個水印文字,並不能像我希望的那樣能夠全屏鋪滿,然後在搜索結果中發現了能夠用itextpdf這個庫用代碼的方式給PDF添加水印,但是當中過程也是曲折,特此記錄一下,並說明當中的坑。
這裏直接貼上java代碼:
public class PDFWaterMark {
private static int interval = -5;
/**
* 添加文字水印
* @param inputFile 文件源地址
* @param outputFile 文件輸出地址
* @param waterMarkName 水印文字
*/
public static void waterMark(String inputFile,
String outputFile, String waterMarkName) {
try {
PdfReader reader = new PdfReader(inputFile);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(
outputFile));
//這裏獲取一個默認的BaseFont
BaseFont base = BaseFont.createFont();
Rectangle pageRect;
PdfGState gs = new PdfGState();
//設置文字透明度
gs.setFillOpacity(0.2f);
gs.setStrokeOpacity(0.2f);
//獲取pdf總頁數
int total = reader.getNumberOfPages() + 1;
JLabel label = new JLabel();
FontMetrics metrics;
int textH;
int textW;
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.setColorFill(BaseColor.LIGHT_GRAY);
//設置水印文字和大小
under.setFontAndSize(base, 30);
//這個position主要是爲了在換行加水印時能往右偏移起始座標
int position = 0;
for (int height = interval + textH; height < pageRect.getHeight(); height = height + textH * 8) {
for (int width = interval + textW + position * 50; width < pageRect.getWidth() + textW; width = width + textW * 3) {
//添加水印文字,水印文字成30度角傾斜
under.showTextAligned(Element.ALIGN_LEFT, waterMarkName, width - textW , height - textH, 30);
}
position++;
}
// 添加水印文字
under.endText();
}
//一定不要忘記關閉流
stamper.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String fileIn = "你電腦中的文件源路徑/XXX.pdf";
String fileOut = "你想保存的文件源路徑/outfile.pdf";
waterMark(fileIn, fileOut, "testword");
}
}
代碼中已經添加了較爲詳細的註釋,首先要說明的是這個代碼現在目前只能添加英文水印,並不能添加中文水印,因爲在實現過程中發現按照網上的寫法,BaseFont會報錯
"STSong-Light' with 'UniGB-UCS2-H' is not recognized"
因爲我沒用到itextasian.jar,所以我沒有按照他們的解決方式去解決,大家如有需要,可以自己嘗試,目前代碼可以正常運行,親測有效。