Itext相關便可java
連接:https://pan.baidu.com/s/1DRAnRxT037hibWey5uJ_AA 提取碼:f3q1
spa
注:註釋掉的是滿屏文印版,沒註釋的是大文字中間文印版 ,想用什麼版本調換註釋就好了。code
package com.wdkj.util;
import java.awt.FontMetrics;
import java.io.FileOutputStream;
import javax.swing.JLabel;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
/** * PDF加水印 * @author sunkuang * */
public class TestwaterMark {
private static int interval = -5;
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 base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
BaseFont.EMBEDDED);
Rectangle pageRect = null;
PdfGState gs = new PdfGState();
// 設置透明度
gs.setFillOpacity(0.3f);
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;
//int numi = 0 ;
//int numj = 0 ;
//int numk = 0 ;
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, 50); //設置大小
// 設置水印顏色
under.setColorFill(BaseColor.BLACK);
// 水印文字成30度角傾斜
// 你能夠爲所欲爲的改你本身想要的角度
/*for (int height = interval + textH; height < pageRect .getHeight(); height = height + textH * 3) { numj ++ ; for (int width = interval + textW; width < pageRect .getWidth() + textW; width = width + textW * 2) { numk ++ ; under.showTextAligned(Element.ALIGN_LEFT, waterMarkName, width - textW, height - textH, 30); } } */
under.showTextAligned(Element.ALIGN_LEFT,
waterMarkName, reader.getPageSize(i).getWidth()/2-120, reader.getPageSize(i).getHeight()/2-80,
45);
// 添加水印文字
under.endText();
}
//System.out.println( numi);
//System.out.println( numj);
//System.out.println( numk);
// 說三遍
// 必定不要忘記關閉流
// 必定不要忘記關閉流
// 必定不要忘記關閉流
stamper.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}複製代碼