java 档案整理 文字水印
import com.itextpdf.text.*; import com.itextpdf.text.pdf.*; import com.itextpdf.text.pdf.codec.TiffImage; import java.io.*;
public class Change2PDF {
/** * pdf文件添加水印 * * @param file pdf文件 * @param waterText 添加文字水印 * @return * @throws IOException * @throws DocumentException */ public static String addtextWatermark(File file, String waterText) throws IOException, DocumentException { //获取pdfWatermark的存放路径 String fileSavePath=file.getPath().substring(0, file.getPath().lastIndexOf(".")); fileSavePath=fileSavePath+"Watermark"+".pdf";//水印保存位置 //待加水印的文件 PdfReader reader = new PdfReader(file.getPath()); // 加完水印的文件 PdfStamper stamper = new PdfStamper(reader,new FileOutputStream(fileSavePath)); int total = reader.getNumberOfPages() + 1; //获取文档 Document document = new Document(reader.getPageSize(1)); // 获取页面宽度 float widths = document.getPageSize().getWidth(); // 获取页面高度 float heights = document.getPageSize().getHeight(); // document.close(); PdfContentByte content; // 设置字体 BaseFont baseFont = BaseFont.createFont("C:\\Windows\\Fonts\\simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); // 循环对每页插入水印 for (int i = 1; i < total; i++) { content = stamper.getOverContent(i); // 开始 content.beginText(); // 设置颜色 content.setColorFill(BaseColor.GRAY); // 设置字体及字号 content.setFontAndSize(baseFont, 55); //透明度 PdfGState gs = new PdfGState(); gs.setFillOpacity(0.5f);// 设置透明度为0.8 content.setGState(gs); // 开始写入水印 设置起始位置 旋转 content.showTextAligned(Element.ALIGN_CENTER, waterText, widths / 2, heights / 2, 50); content.endText(); } stamper.setFormFlattening(false);// 如果为false那么生成的PDF文件还能编辑,一定要设为true stamper.close();//一定要在循环外关闭,不然只有第一页有水印 reader.close();//关闭读取否则文件删除不了 return fileSavePath; } public static void main(String[] args) throws Exception { String pdfPath = "E:\\Desktop\\GQ_GuoQi\\Change2PDF.pdf"; File file = new File(pdfPath); String path= addtextWatermark(file,"交通厅档案注意保密"); System.out.println("打水印完成后地址:"+path); }
}
效果