import com.lowagie.text.pdf.*;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class test4 {
public static void main(String[] args) throws DocumentException, IOException {
// 待加水印的文件
PdfReader reader = new PdfReader( "D:/xxxx/xxx.pdf");
//如果拼接地址:出现地址转码的问题:可用File.separator方法
// 加完水印的文件
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream( "D:/xx/"+new SimpleDateFormat("yyyyMMddHHmmsshh").format(new Date())+".pdf"));
int total = reader.getNumberOfPages() + 1;
// 设置字体
BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
String type ="A";
PdfGState gs = new PdfGState();
gs.setFillOpacity(0.9f);
gs.setStrokeOpacity(0.9f);
PdfContentByte under;
for (int i = 1; i < total; i++) {
String sss1 = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+i; //水印一
String sss2 = "水印二";
under = stamper.getOverContent(i);
under.saveState();
under.setGState(gs);
under = stamper.getOverContent(i);// 在内容上方加水印
// under = stamper.getUnderContent(i);//在内容下方加水印
// 设置字体和字体大小
under.beginText();
under.setColorFill(Color.BLACK);
under.setFontAndSize(base, 10);
under.setTextMatrix(80, 200);
float width = reader.getPageSize(i).getWidth();
float height = reader.getPageSize(i).getHeight();
under.showTextAligned(Element.ALIGN_CENTER , sss1, 420,810, 0);
under.showTextAligned(Element.ALIGN_CENTER , sss2, 500,810, 0);
if(type.equals("A")&&i>=2){
under.showTextAligned(Element.ALIGN_CENTER , sss1, 600,560, 0);
under.showTextAligned(Element.ALIGN_CENTER , sss2, 680,560, 0);
}
under.setTextRise(45f);
under.endText();
}
//一定不要忘记关闭流
stamper.close();
reader.close();
}
}