java为PDF添加水印,图片水印和文字水印

一时失言乱红尘 2023-10-04 12:01 77阅读 0赞

java为PDF添加水印,文字水印和图片水印

一个需求,下载pdf、word、excel文件时要带有水印,要求铺满。先分开,先介绍为PDF文件添加文字水印和图片水印。
所需jar包:itext-2.0.1.jar。(itextpdf-5.5.8.jar,这个类似)
jar包可在这里下载:https://mvnrepository.com/

创建水印图片的类

  1. import java.awt.Color;
  2. import java.awt.Font;
  3. import java.awt.Graphics2D;
  4. import java.awt.RenderingHints;
  5. import java.awt.Transparency;
  6. import java.awt.image.BufferedImage;
  7. import java.io.File;
  8. import javax.imageio.ImageIO;
  9. public class ImageUtil {
  10. /**
  11. * 生成背景透明的文字水印图片,文字位于中央,且倾斜
  12. * @param content 水印文字
  13. * @return
  14. */
  15. public static BufferedImage createWaterMark(String content) {
  16. //生成图片宽度
  17. int width = 250;
  18. //生成图片高度
  19. int heigth = 160;
  20. //获取bufferedImage对象
  21. BufferedImage image = new BufferedImage(width, heigth, BufferedImage.TYPE_INT_RGB);
  22. //得到画笔对象
  23. Graphics2D g2d = image.createGraphics();
  24. //使得背景透明
  25. image = g2d.getDeviceConfiguration().createCompatibleImage(width, heigth, Transparency.TRANSLUCENT);
  26. g2d.dispose();
  27. g2d = image.createGraphics();
  28. //设置对线段的锯齿状边缘处理
  29. g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
  30. //设置水印旋转,倾斜度
  31. g2d.rotate(-0.5, (double) image.getWidth()/2, (double) image.getHeight()/2);
  32. //设置颜色,这是黑色,第4个参数是透明度
  33. g2d.setColor(new Color(0, 0, 0, 20));
  34. //设置字体
  35. Font font = new Font("宋体", Font.ROMAN_BASELINE, 22);
  36. g2d.setFont(font);
  37. float fontSize = font.getSize();
  38. //计算绘图偏移x、y,使得使得水印文字在图片中居中
  39. float x = 0.5f * fontSize;
  40. float y = 0.5f * heigth + x;
  41. //取绘制的字串宽度、高度中间点进行偏移,使得文字在图片坐标中居中
  42. g2d.drawString(content, x, y);
  43. //释放资源
  44. g2d.dispose();
  45. return image;
  46. }
  47. public static void main(String[] args) throws Exception {
  48. BufferedImage bi = createWaterMark("水印图片 2021-12-32");
  49. ImageIO.write(bi, "png", new File("E:\\waterMark.png")); //写入文件
  50. }
  51. }

效果图

在这里插入图片描述

PDF添加图片水印的类

  1. import java.io.FileOutputStream;
  2. import com.lowagie.text.Image;
  3. import com.lowagie.text.pdf.PdfContentByte;
  4. import com.lowagie.text.pdf.PdfGState;
  5. import com.lowagie.text.pdf.PdfReader;
  6. import com.lowagie.text.pdf.PdfStamper;
  7. public class PDFUtil {
  8. /**
  9. * pdf文件添加图片水印
  10. * itext-2.0.1.jar
  11. * @param srcPath 输入的文件路径
  12. * @param destPath 输出的文件路径
  13. * @param imagePath 水印图片的路径
  14. * @throws Exception
  15. */
  16. public static void addPDFImageWaterMark(String srcPath, String destPath, String imagePath)
  17. throws Exception {
  18. PdfReader reader = new PdfReader(srcPath);
  19. PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destPath));
  20. //加载图片
  21. Image image = Image.getInstance(imagePath);
  22. PdfGState gs = new PdfGState();
  23. //gs.setFillOpacity(0.2f);//图片水印透明度
  24. //gs.setStrokeOpacity(0.4f);//设置笔触字体不透明度
  25. PdfContentByte content = null;
  26. int total = reader.getNumberOfPages();//pdf文件页数
  27. for (int i=0; i<total; i++) {
  28. float x = reader.getPageSize(i+1).width();//页宽度
  29. float y = reader.getPageSize(i+1).height();//页高度
  30. content = stamper.getOverContent(i+1);
  31. content.setGState(gs);
  32. content.beginText();//开始写入
  33. //每页7行,一行3个
  34. for (int j=0; j<3; j++) {
  35. for (int k=0; k<7; k++) {
  36. //setAbsolutePosition 方法的参数(输出水印X轴位置,Y轴位置)
  37. image.setAbsolutePosition(x/3*j-30, y/7*k-20);
  38. content.addImage(image);
  39. }
  40. }
  41. content.endText();//结束写入
  42. }
  43. //关闭流
  44. stamper.close();
  45. reader.close();
  46. }
  47. public static void main(String[] args) throws Exception {
  48. addPDFImageWaterMark("E:\\测试.pdf", "E:\\测试水印img.pdf", "E:\\waterMark.png");
  49. }
  50. }

效果图

在这里插入图片描述

PDF添加文字水印的类

与图片水印的类似,稍微改动

  1. import java.io.FileOutputStream;
  2. import com.lowagie.text.Element;
  3. import com.lowagie.text.Image;
  4. import com.lowagie.text.pdf.BaseFont;
  5. import com.lowagie.text.pdf.PdfContentByte;
  6. import com.lowagie.text.pdf.PdfGState;
  7. import com.lowagie.text.pdf.PdfReader;
  8. import com.lowagie.text.pdf.PdfStamper;
  9. public class PDFUtil {
  10. /**
  11. * pdf文件添加文字水印
  12. * @param srcPath 输入的文件路径
  13. * @param destPath 输出的文件路径
  14. * @param word 水印文字
  15. * @throws Exception
  16. */
  17. public static void addPDFWaterMark(String srcPath, String destPath, String word)
  18. throws Exception {
  19. PdfReader reader = new PdfReader(srcPath);
  20. PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destPath));
  21. //使用系统字体
  22. String prefixFont = null;
  23. String os = System.getProperties().getProperty("os.name");
  24. if (os.startsWith("win") || os.startsWith("Win")) {
  25. prefixFont = "C:\\Windows\\Fonts\\SIMSUN.TTC,1";
  26. } else {
  27. prefixFont = "/usr/share/fonts/chinese/TrueType/uming.ttf";
  28. }
  29. //创建字体,第一个参数是字体路径
  30. BaseFont base = BaseFont.createFont(prefixFont, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
  31. //BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
  32. PdfGState gs = new PdfGState();
  33. gs.setFillOpacity(0.2f);//图片水印透明度
  34. //gs.setStrokeOpacity(0.4f);//设置笔触字体不透明度
  35. PdfContentByte content = null;
  36. int total = reader.getNumberOfPages();//pdf文件页数
  37. for (int i=0; i<total; i++) {
  38. float x = reader.getPageSize(i+1).width();//页宽度
  39. float y = reader.getPageSize(i+1).height();//页高度
  40. content = stamper.getOverContent(i+1);
  41. content.setGState(gs);
  42. content.beginText();//开始写入
  43. content.setFontAndSize(base, 20);//字体大小
  44. //每页7行,一行3个
  45. for (int j=0; j<3; j++) {
  46. for (int k=0; k<7; k++) {
  47. //showTextAligned 方法的参数(文字对齐方式,位置内容,输出水印X轴位置,Y轴位置,旋转角度)
  48. content.showTextAligned(Element.ALIGN_CENTER, word, x/3*j+90, y/7*k, 25);
  49. }
  50. }
  51. content.endText();//结束写入
  52. }
  53. //关闭流
  54. stamper.close();
  55. reader.close();
  56. }
  57. public static void main(String[] args) throws Exception {
  58. addPDFWaterMark("E:\\测试.pdf", "E:\\测试水印.pdf", "水印测试 2021-12-32");
  59. }
  60. }

效果图

在这里插入图片描述
若用的是itextpdf-5.5.8.jar,则需改动以下两处
float x = reader.getPageSize(i+1).getWidth(); //页宽度
float y = reader.getPageSize(i+1).getHeight(); //页高度

发表评论

表情:
评论列表 (有 0 条评论,77人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java图片添加文字水印

    闲着没事,研究了下图片水印的事儿,图片水印虽然恶心,而且大大的影响了图片的美观,试想一下,一张美女的性感写真照,下方来了个大大的水印“XXXX所有”,看着那猥琐的文字水印,是不