案例 文字水印与图片水印

代码:

package com.jc.util;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.swing.JLabel;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.DocumentException;
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;

import com.spire.pdf.*;
import com.spire.pdf.graphics.PdfCanvas;
import com.spire.pdf.graphics.PdfImage;
import com.spire.pdf.graphics.PdfTilingBrush;

import java.awt.*;
import java.awt.geom.Dimension2D;
import java.awt.geom.Rectangle2D;

/**
 * 水印工具类
 * @author wang-xiaoming
 */
public class WaterMarkUtil {
    // 文字水印透明度
    private static float DEFAULT_WORD_ALPHA = 0.5f;
    // 文字水印之间的间隔
    private static final int DEFAULT_WORD_XMOVE = 80;
    // 文字水印之间的间隔
    private static final int DEFAULT_WORD_YMOVE = 80;
    // 默认文字信息
    private static final String DEFAULT_WORD = "防伪水印";
    // 默认文字字体
    private static final String DEFAULT_FONT = "仿宋";
    // 默认文字大小
    private static final int DEFAULT_SIZE = 20;
    // 默认文字颜色,色彩代码:https://html-color-codes.info/chinese/
    private static final String DEFAULT_COLOR = "#333333";
    
    /**
     * 信息文字
     */
    private static final String WORD = "word";
    /**
     * 信息文字字体
     */
    private static final String FONT = "font";
    /**
     * 信息文字大小
     */
    private static final String SIZE = "size";
    /**
     * 信息文字颜色
     */
    private static final String COLOR = "color";
    /**
     * 信息文字格式
     */
    private static final String FORMAT = "format";
    /**
     * 信息文字自定义倾斜度
     */
    private static final String DEGREE = "degree";
 
    /**
     * 获取文本长度。汉字为1:1,英文和数字为2:1
     */
    private static int getTextLength (String text) {
        int length = text.length ();
        for (int i = 0; i < text.length (); i++) {
            String s = String.valueOf (text.charAt (i));
            if (s.getBytes ().length > 1) {
                length++;
            }
        }
        length = length % 2 == 0 ? length / 2 : length / 2 + 1;
        return length;
    }
    
    /**
     * RGB 转 Color
     * @param colorCode,十六进制颜色码,#0000FF
     * @return
     */
    private static Color parseToColor(String colorCode) {
        String srcColorCode = colorCode;
        Color convertedColor = Color.white;
        try {
            colorCode = colorCode.replace("#", "");
            convertedColor = new Color(Integer.parseInt(colorCode, 16));
        } catch(NumberFormatException e) {
            System.out.println("RGB 转 Color异常,e=" + e.getMessage());
        }
        System.out.println("RGB 转 Color," + srcColorCode + "  -->  " + convertedColor);
        return convertedColor;
    }
    
    /**
     * RGB 转 BaseColor
     * @param colorCode,十六进制颜色码,#0000FF
     * @return
     */
    private static BaseColor parseToBaseColor(String colorCode) {
        BaseColor convertedColor = BaseColor.WHITE;
        try {
            colorCode = colorCode.replace("#", "");
            int red = Integer.parseInt(colorCode.substring(0, 2), 16);
            int green = Integer.parseInt(colorCode.substring(2, 4), 16);
            int blue = Integer.parseInt(colorCode.substring(4, 6), 16);
            convertedColor = new BaseColor(red, green, blue);
        } catch(NumberFormatException e) {
            System.out.println("RGB 转 BaseColor异常,e=" + e.getMessage());
        }
        return convertedColor;
    }
 
    /**
     * 图片添加文字水印
     * @param paramMap
     * @param srcImgPath 原图片路径
     * @param targetPath 目标图片路径
     */
    public static void addWaterMarkToImage (Map<String, String> paramMap, String srcImgPath, String targetPath) {
        String word = StringUtil.isNullOrEmpty(paramMap.get(WORD))? DEFAULT_WORD:paramMap.get(WORD);// 文字信息
        String fontType = StringUtil.isNullOrEmpty(paramMap.get(FONT))? DEFAULT_FONT:paramMap.get(FONT);// 文字字体
        int fontSize = StringUtil.toInt(paramMap.get(SIZE), DEFAULT_SIZE);// 文字大小
        String wordColor = StringUtil.isNullOrEmpty(paramMap.get(COLOR))? DEFAULT_COLOR:paramMap.get(COLOR);// 文字颜色
        Color color = parseToColor(wordColor);
        int plate = StringUtil.toInt(paramMap.get(FORMAT), 1);// 文字板式 1-倾斜(-45°);2-水平(0°)
        Integer degree = plate == 1? -45:0;
        if(paramMap.get(DEGREE) != null){
            degree = Integer.valueOf(paramMap.get(DEGREE));
        }
        
        InputStream is = null;
        OutputStream os = null;
        try {
            // 源图片
            Image srcImg = ImageIO.read (new File (srcImgPath));
            int width = srcImg.getWidth (null);// 原图宽度
            int height = srcImg.getHeight (null);// 原图高度
            BufferedImage buffImg = new BufferedImage (srcImg.getWidth (null), srcImg.getHeight (null),
                                                       BufferedImage.TYPE_INT_RGB);
            // 得到画笔对象
            Graphics2D g = buffImg.createGraphics ();
            // 设置对线段的锯齿状边缘处理
            g.setRenderingHint (RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage (srcImg.getScaledInstance (srcImg.getWidth (null), srcImg.getHeight (null), Image.SCALE_SMOOTH),
                         0, 0, null);
            // 设置水印旋转
            if (null != degree) {
                g.rotate (Math.toRadians (degree), (double) buffImg.getWidth () / 2, (double) buffImg.getHeight () / 2);
            }
            // 设置水印文字颜色
            g.setColor (color);
            
            // 设置水印文字Font
            Font font = new Font (fontType, Font.BOLD, fontSize);
            g.setFont (font);
            // 设置水印文字透明度
            g.setComposite (AlphaComposite.getInstance (AlphaComposite.SRC_ATOP, DEFAULT_WORD_ALPHA));
 
            int x = -width / 2;
            int y = -height / 2;
            int markWidth = fontSize * getTextLength (word);// 字体长度
            int markHeight = fontSize;// 字体高度
 
            // 循环添加水印
            while (x < width * 1.5) {
                y = -height / 2;
                while (y < height * 1.5) {
                    g.drawString (word, x, y);
 
                    y += markHeight + DEFAULT_WORD_YMOVE;
                }
                x += markWidth + DEFAULT_WORD_XMOVE;
            }
            // 释放资源
            g.dispose ();
            // 生成图片
            os = new FileOutputStream (targetPath);
            ImageIO.write (buffImg, "JPG", os);
        } catch (Exception e) {
            System.out.println("图片添加文字水印异常!e=" + e.getMessage());
        } finally {
            try {
                if (null != is)
                    is.close ();
            } catch (Exception e) {
                System.out.println("图片添加文字水印异常,关闭is流异常!e=" + e.getMessage());
            }
            try {
                if (null != os)
                    os.close ();
            } catch (Exception e) {
                System.out.println("图片添加文字水印异常,关闭os流异常!e=" + e.getMessage());
            }
        }
    }
    
    /**
     * 文件添加文字水印
     * @param paramMap
     * @param srcPdfPath 原文件路径
     * @param targetPath 目标文件路径
     */
    public static void addWaterMarkToPDF(Map<String, String> paramMap, String srcPdfPath, String targetPath){
        String word = StringUtil.isNullOrEmpty(paramMap.get(WORD))? DEFAULT_WORD:paramMap.get(WORD);// 文字信息
        String fontType = StringUtil.isNullOrEmpty(paramMap.get(FONT))? DEFAULT_FONT:paramMap.get(FONT);// 文字字体
        int fontSize = StringUtil.toInt(paramMap.get(SIZE), DEFAULT_SIZE);// 文字大小
        String wordColor = StringUtil.isNullOrEmpty(paramMap.get(COLOR))? DEFAULT_COLOR:paramMap.get(COLOR);// 文字颜色
        BaseColor baseColor = parseToBaseColor(wordColor);
        int plate = StringUtil.toInt(paramMap.get(FORMAT), 1);// 文字板式 1-倾斜(45°);2-水平(0°)
        Integer degree = plate == 1? 45:0;
        if(paramMap.get(DEGREE) != null){
            degree = Integer.valueOf(paramMap.get(DEGREE));
        }
        
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        PdfReader reader = null;
        PdfStamper stamper = null;
        try {
            fos = new FileOutputStream(new File(targetPath));
            bos = new BufferedOutputStream(fos);
            reader = new PdfReader(srcPdfPath);
            stamper = new PdfStamper(reader, bos);
            
            // 获取总页数 +1, 下面从1开始遍历
            int total = reader.getNumberOfPages() + 1;
            // 使用classpath下面的字体库,例如,"/SIMFANG.TTF"
            String fontPath = "";
            // 取字体所在真实路径或相对根目录所在路径
            String fontsPath = File.separator;
            if ("仿宋".equals(fontType)) {
                fontPath = fontsPath + "SIMFANG.TTF";
            } else if ("宋体".equals(fontType)) {
                fontPath = fontsPath + "SIMSUN.TTC,0";// 解决SIMSUN.TTC报错,解决方法http://www.genshuixue.com/i-cxy/p/15543081
            } else if ("黑体".equals(fontType)) {
                fontPath = fontsPath + "SIMHEI.TTF";
            } else if ("微软雅黑".equals(fontType)) {
                fontPath = fontsPath + "MSYH.TTF";
            } else {
                fontPath = fontsPath + "SIMFANG.TTF";
            }
            BaseFont base = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            
            // 间隔
            int interval = -5;
            // 获取水印文字的高度和宽度
            int textH = 0, textW = 0;
            JLabel label = new JLabel();
            label.setText(word);
            FontMetrics metrics = label.getFontMetrics(label.getFont());
            textH = metrics.getHeight();
            textW = metrics.stringWidth(label.getText());
            System.out.println("textH: " + textH);
            System.out.println("textW: " + textW);
            
            // 设置水印透明度
            PdfGState gs = new PdfGState();
            gs.setFillOpacity(DEFAULT_WORD_ALPHA);
            gs.setStrokeOpacity(DEFAULT_WORD_ALPHA);
            
            Rectangle pageSizeWithRotation = null;
            PdfContentByte content = null;
            for (int i = 1; i < total; i++) {
                // 在内容上方加水印
                content = stamper.getOverContent(i);
                // 在内容下方加水印
//                content = stamper.getUnderContent(i);
                content.saveState();
                content.setGState(gs);
                
                // 设置字体和字体大小
                content.beginText();
                // 设置字体颜色
                content.setColorFill(baseColor);
                content.setFontAndSize(base, fontSize);
                
                // 获取每一页的高度、宽度
                pageSizeWithRotation = reader.getPageSizeWithRotation(i);
                float pageHeight = pageSizeWithRotation.getHeight();
                float pageWidth = pageSizeWithRotation.getWidth();
                if(i < 2){
                    System.out.println("-----------第" + i + "张----------");
                    System.out.println("pageHeight:" + pageHeight);
                    System.out.println("pageWidth:" + pageWidth);
                }
                
                // 根据纸张大小多次添加, 水印文字成30度角倾斜
                StringBuilder builder;
                for (int height = interval + textH; height < pageHeight*2; height = height + textH * 3) {
                    builder = new StringBuilder("(x, y) = ");
                    for (int width = interval + textW; width < (pageWidth + textW)*2; width = width + textW * 2) {
                        content.showTextAligned(Element.ALIGN_CENTER, word, width - textW, height - textH, degree);
                        builder.append("(").append(width - textW).append(", ").append(height - textH).append(")\t");
                    }
                    if(i < 2){
                        System.out.println(builder.toString());
                    }
                }
                content.endText();
            }
            
        } catch (FileNotFoundException e) {
            System.out.println("文件添加文字水印异常,FileNotFoundException!e=" + e.getMessage());
        } catch (IOException e) {
            System.out.println("文件添加文字水印异常,IOException!e=" + e.getMessage());
        } catch (DocumentException e) {
            System.out.println("文件添加文字水印异常,DocumentException!e=" + e.getMessage());
        } finally {
            // 关流
            try {
                if(null != stamper){
                    stamper.close();
                }
            } catch (Exception e) {
                System.out.println("文件添加文字水印异常,关闭stamper流异常!e=" + e.getMessage());
            }
            try {
                if(null != reader){
                    reader.close();
                }
            } catch (Exception e) {
                System.out.println("文件添加文字水印异常,关闭reader流异常!e=" + e.getMessage());
            }
            try {
                if(null != fos){
                    fos.close();
                }
            } catch (Exception e) {
                System.out.println("文件添加文字水印异常,关闭fos流异常!e=" + e.getMessage());
            }
            try {
                if(null != bos){
                    bos.close();
                }
            } catch (Exception e) {
                System.out.println("文件添加文字水印异常,关闭bos流异常!e=" + e.getMessage());
            }
        }
    }
    
    /**
     * 内部枚举类,用于指定水印铺设的样式,0-常规,1-平铺,2-拉伸;默认1
     */
    private static final int DEFAULT_IMAGE_MODE = 1;
    /**
     * 图片水印之间的水平间距,默认50
     */
    private static final int DEFAULT_IMAGE_XMOVE = 50;
    /**
     * 图片水印之间的垂直间距,默认50
     */
    private static final int DEFAULT_IMAGE_YMOVE = 50;
    /**
     * 图片水印透明度,默认0.5f
     */
    private static final float DEFAULT_IMAGE_ALPHA = 0.5f;
    /**
     * 图片水印旋转角度,应在正负45度之间,默认-45
     */
    private static final double DEFAULT_IMAGE_THETA = -45;
    /**
     * 图片水印高缩放比例,默认1.0,等比例高
     */
    private static final double DEFAULT_LOGO_HEIGHT_SCALE = 1.0;
    /**
     * 图片水印宽缩放比例,默认1.0,等比例宽
     */
    private static final double DEFAULT_LOGO_WIDTH_SCALE = 1.0;
    
    private static final String IMAGE_MODE = "imageMode";
    private static final String IMAGE_XMOVE = "imageXMove";
    private static final String IMAGE_YMOVE = "imageYMove";
    private static final String IMAGE_ALPHA = "imageAlpha";
    private static final String IMAGE_THETA = "imageTheta";
    private static final String LOGO_HEIGHT_SCALE = "logoHeightScale";
    private static final String LOGO_WIDTH_SCALE = "logoWidthScale";
    
    /**
     * 图片添加图片水印
     * @param paramMap
     * @param srcImgPath 原图片路径
     * @param targetPath 目标图片路径
     * @param logoPath logo图片路径
     */
    public static void addLogoToImage(Map<String, String> paramMap, String srcImgPath, String targetPath, String logoPath){
        // 获取参数
        int imageMode = StringUtil.toInt(paramMap.get(IMAGE_MODE), DEFAULT_IMAGE_MODE);
        int imageXMove = StringUtil.toInt(paramMap.get(IMAGE_XMOVE), DEFAULT_IMAGE_XMOVE);
        int imageYMove = StringUtil.toInt(paramMap.get(IMAGE_YMOVE), DEFAULT_IMAGE_YMOVE);
        float imageAlpha = StringUtil.toFloat(paramMap.get(IMAGE_ALPHA), DEFAULT_IMAGE_ALPHA);
        double imageTheta = StringUtil.toDouble(paramMap.get(IMAGE_THETA), DEFAULT_IMAGE_THETA);
        double logoHeightScale = StringUtil.toDouble(paramMap.get(LOGO_HEIGHT_SCALE), DEFAULT_LOGO_HEIGHT_SCALE);
        System.out.println("logoHeightScale=" + logoHeightScale);
        double logoWidthScale = StringUtil.toDouble(paramMap.get(LOGO_WIDTH_SCALE), DEFAULT_LOGO_WIDTH_SCALE);
        System.out.println("logoWidthScale=" + logoWidthScale);
        
        try {
            BufferedImage originImg= ImageIO.read(new File(srcImgPath));
            BufferedImage logoImage = ImageIO.read(new File(logoPath));
            Graphics2D graphics = (Graphics2D) originImg.getGraphics();
            graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, imageAlpha));
 
            int canvasHeight = originImg.getHeight();
            int canvasWidth = originImg.getWidth();
            System.out.println("原图片高canvasHeight=" + canvasHeight);
            System.out.println("原图片宽canvasWidth=" + canvasWidth);
            
            int srcLogoHeight = logoImage.getHeight();
            int srcLogoWidth = logoImage.getWidth();
            System.out.println("logo图片原高srcLogoHeight=" + srcLogoHeight);
            System.out.println("logo图片原宽srcLogoWidth=" + srcLogoWidth);
            
            int logoHeight = (int) (srcLogoHeight*logoHeightScale);
            int logoWidth = (int) (srcLogoWidth*logoWidthScale);
            System.out.println("logo图片高logoHeight=" + logoHeight);
            System.out.println("logo图片宽logoWidth=" + logoWidth);
            
            // 图片水印格式
            if(imageMode == 0){
                graphics.rotate(imageTheta, canvasWidth/2, canvasHeight/2);
                
                // x = (原图片宽 - logo图片宽)/2
                // y = (原图片高 - logo图片高)/2
                int x = (canvasWidth - logoWidth)/2;
                int y = (canvasHeight - logoHeight)/2;
                System.out.println("(x, y) = (" + x + ", " + y + ")");
                graphics.drawImage(logoImage,x,y,srcLogoWidth,srcLogoHeight,null);
            }else if(imageMode == 1){
                graphics.rotate(imageTheta);
                
                // 300*300 --> 30*30
                logoHeight = (int) (srcLogoHeight*0.1);
                logoWidth = (int) (srcLogoWidth*0.1);
                // 可固定大小
//                logoHeight = 100;
//                logoWidth = 100;
                
                int interval = logoWidth+logoHeight;
                StringBuilder builder;
                for(int i = -canvasHeight; i < canvasWidth + canvasHeight; i = i + interval + imageXMove){
                    builder = new StringBuilder("(x, y) = ");
                    for(int j = -canvasWidth; j < canvasHeight + canvasWidth; j = j + interval + imageYMove){
                        builder.append("(").append(i).append(", ").append(j).append(")\t");
                        graphics.drawImage(logoImage,i,j,logoWidth,logoHeight,null);
                    }
                    if(i < 3){
                        System.out.println(builder.toString());
                    }
                }
            } else {
                graphics.rotate(imageTheta, canvasWidth/2, canvasHeight/2);
                
                // x = (原图片宽 - logo图片宽)/2
                // y = (原图片高 - logo图片高)/2
                int x = (canvasWidth - logoWidth)/2;
                int y = (canvasHeight - logoHeight)/2;
                
                System.out.println("(x, y) = (" + x + ", " + y + ")");
                graphics.drawImage(logoImage,x,y,logoWidth,logoHeight,null);
            }
            
            
            graphics.dispose();
            ImageIO.write(originImg,"png",new File(targetPath));
        } catch (IOException e) {
            System.out.println("文件添加图片水印异常!e=" + e.getMessage());
        }
    }
    
    /**
     * 文件添加图片水印
     * @param paramMap
     * @param srcPdfPath 原文件路径
     * @param targetPath 目标文件路径
     * @param logoPath logo水印图片路径
     */
    public static void addImageToPDF(Map<String, String> paramMap, String srcPdfPath, String targetPath, String logoPath){
        // 获取参数
        int imageMode = StringUtil.toInt(paramMap.get(IMAGE_MODE), DEFAULT_IMAGE_MODE);
        int imageXMove = StringUtil.toInt(paramMap.get(IMAGE_XMOVE), DEFAULT_IMAGE_XMOVE);
        int imageYMove = StringUtil.toInt(paramMap.get(IMAGE_YMOVE), DEFAULT_IMAGE_YMOVE);
        float imageAlpha = StringUtil.toFloat(paramMap.get(IMAGE_ALPHA), DEFAULT_IMAGE_ALPHA);
        double imageTheta = StringUtil.toDouble(paramMap.get(IMAGE_THETA), DEFAULT_IMAGE_THETA);
        float angle = (float) imageTheta;
        System.out.println("angle=" + angle);
        double logoHeightScale = StringUtil.toDouble(paramMap.get(LOGO_HEIGHT_SCALE), DEFAULT_LOGO_HEIGHT_SCALE);
        System.out.println("logoHeightScale=" + logoHeightScale);
        double logoWidthScale = StringUtil.toDouble(paramMap.get(LOGO_WIDTH_SCALE), DEFAULT_LOGO_WIDTH_SCALE);
        System.out.println("logoWidthScale=" + logoWidthScale);
        
        // 创建PdfDocument对象,并加载PDF测试文档
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile(srcPdfPath);
        // 解决了:生成的pdf第一页左上角出现 Evaluation Warning : The document was created with Spire.PDF for Java.
        PdfPageBase addOne = pdf.getPages().add();
        pdf.getPages().remove(addOne);

        // 遍历文档每一页,加载图片,并设置成平铺背景(水印)
        for (int k = 0; k < pdf.getPages().getCount(); k++) {
            // 获取当前页
            PdfPageBase page = pdf.getPages().get(k);

            Dimension2D dimension2D = new Dimension();
            double width = page.getCanvas().getSize().getWidth();
            double height = page.getCanvas().getSize().getHeight();
            // 设置每分隔间距可展示的水印个数
            dimension2D.setSize(width, height);

            PdfTilingBrush brush = new PdfTilingBrush(dimension2D);
            PdfCanvas graphics = brush.getGraphics();
            // 当前页的宽和高
            double brushWidth = brush.getSize().getWidth();
            double brushHeight = brush.getSize().getHeight();
            
            // 设置透明度
            graphics.setTransparency(imageAlpha);
            
            // 设置平移间隔,平移x,平移y;由于下面的for循环已经固定了间距,所以这里不再限制
//            graphics.translateTransform(brushWidth/10, brushHeight/10);
//            graphics.translateTransform(imageXMove, imageYMove);
            
            // 设置旋转角度
//            graphics.rotateTransform(angle);

            PdfImage image = PdfImage.fromImage(logoPath);
            // logo原图片宽和高
            int srcLogoWidth = image.getWidth();
            int srcLogoHeight = image.getHeight();
            // logo原图片宽和高取整
            int logoHeight = (int) (srcLogoHeight*logoHeightScale);
            int logoWidth = (int) (srcLogoWidth*logoWidthScale);
            // 当前页的宽和高取整
            int canvasHeight = (int) brushHeight;
            int canvasWidth = (int) brushWidth;
            if(k < 3){
                System.out.println("------第" + (k + 1) + "次------");
                System.out.println("brushWidth=" + brushWidth);
                System.out.println("brushHeight=" + brushHeight);
                System.out.println("srcLogoWidth=" + srcLogoWidth);
                System.out.println("srcLogoHeight=" + srcLogoHeight);
            }
            
            if(imageMode == 0){
                graphics.rotateTransform(0);
                // x = (原图片宽 - logo图片宽)/2
                // y = (原图片高 - logo图片高)/2
                int x = (canvasWidth - logoWidth)/2;
                int y = (canvasHeight - logoHeight)/2;
                
                graphics.drawImage(image,x,y,srcLogoWidth,srcLogoHeight);
            }else if(imageMode == 1){
                graphics.rotateTransform(angle);
                
                logoHeight = (int) (srcLogoHeight*0.1);
                logoWidth = (int) (srcLogoWidth*0.1);
                int interval = logoWidth+logoHeight;
                StringBuilder builder;
                for(int i = -canvasHeight; i < canvasWidth + canvasHeight; i = i + interval + imageXMove){
                    builder = new StringBuilder("(x, y) = ");
                    for(int j = -canvasWidth; j < canvasHeight + canvasWidth; j = j + interval + imageYMove){
                        builder.append("(").append(i).append(", ").append(j).append(")\t");
                        graphics.drawImage(image, i, j, logoWidth, logoHeight);
                    }
                    if(k < 3){
                        System.out.println(builder.toString());
                    }
                }
                if(k < 3){
                    System.out.println();
                }
            }else{
                graphics.rotateTransform(0);
                
                // 设置旋转中心为页面中心
                int x = (canvasWidth - logoWidth)/2;
                int y = (canvasHeight - logoHeight)/2;
                graphics.drawImage(image,x,y,logoWidth,logoWidth);
                
//                page.setBackgroundImage(logoPath);
//                Rectangle2D.Float rect = new Rectangle2D.Float();
//                rect.setRect(x, y, logoWidth, logoWidth);
//                page.setBackgroundRegion(rect);
            }
            
            Rectangle2D rectangle2D = new Rectangle2D.Float();
            rectangle2D.setFrame(new Point(0,0),page.getCanvas().getClientSize());
            page.getCanvas().drawRectangle(brush,rectangle2D);
        }

        // 保存文档
        pdf.saveToFile(targetPath);
        pdf.dispose();
    }
 
    public static void main (String[] args) {
        Map<String, String> paramMap = new HashMap<>(16);
        
        /**
         * 测试一:图片添加文字水印
         */
        // 原图片路径
        System.out.println ("图片添加文字水印开始...");
        String srcImgPath = "D:/watermark/test/图片水印/my.png";
        // 目标图片路径
        String targerPath1 = "D:/watermark/test/图片水印/my_文字水印_水平.png";
        String targerPath2 = "D:/watermark/test/图片水印/my_文字水印_倾斜.png";
        String targerPath3 = "D:/watermark/test/图片水印/my_文字水印_自定义角度.png";
        // 给图片添加正水印文字
        paramMap.put(FORMAT, "2");
        WaterMarkUtil.addWaterMarkToImage(paramMap, srcImgPath, targerPath1);
        
        // 给图片添加斜水印文字
        paramMap.put(FORMAT, "1");
        WaterMarkUtil.addWaterMarkToImage(paramMap, srcImgPath, targerPath2);
        
        // 给图片添加任意斜度水印文字
        paramMap.put(DEGREE, "-75");
        WaterMarkUtil.addWaterMarkToImage(paramMap, srcImgPath, targerPath3);
        System.out.println ("图片添加文字水印结束...");
        
        /**
         * 测试二:文件添加文字水印
         */
        paramMap = new HashMap<>(16);
        System.out.println ("文件添加文字水印开始...");
        // 原图片路径
        String srcPdfPath = "D:/watermark/test/图片水印/my.pdf";
        // 目标图片路径
        String targerPath4 = "D:/watermark/test/图片水印/my_pdf文字水印.pdf";
        paramMap.put(FORMAT, "1");
        paramMap.put(WORD, "花开有时");
        WaterMarkUtil.addWaterMarkToPDF(paramMap, srcPdfPath, targerPath4);
        System.out.println ("文件添加文字水印结束...");
        
        /**
         * 测试三:文件添加图片水印
         */
        System.out.println ("文件添加图片水印开始...");
        srcPdfPath = "D:/watermark/test/图片水印/my.pdf";
        String targetPath = "D:/watermark/test/图片水印/my_pdf_图片水印_常规.pdf";
        String logoPath = "D:/watermark/test/图片水印/003.png";
        // 常规
        paramMap.put(IMAGE_MODE, "0");
        WaterMarkUtil.addImageToPDF(paramMap, srcPdfPath, targetPath, logoPath);
        
        // 平铺
        targetPath = "D:/watermark/test/图片水印/my_pdf_图片水印_平铺.pdf";
        paramMap.put(IMAGE_MODE, "1");
        WaterMarkUtil.addImageToPDF(paramMap, srcPdfPath, targetPath, logoPath);
        
        // 拉伸
        targetPath = "D:/watermark/test/图片水印/my_pdf_图片水印_拉伸.pdf";
        paramMap.put(IMAGE_MODE, "2");
        paramMap.put(LOGO_HEIGHT_SCALE, "0.8");
        paramMap.put(LOGO_WIDTH_SCALE, "0.5");
        paramMap.put(IMAGE_ALPHA, "0.8f");
        WaterMarkUtil.addImageToPDF(paramMap, srcPdfPath, targetPath, logoPath);
        System.out.println ("文件添加图片水印结束...");
        
        /**
         * 测试四:图片添加图片水印
         */
        System.out.println ("图片添加图片水印开始...");
        srcImgPath = "D:/watermark/test/图片水印/my.png";
        targetPath = "D:/watermark/test/图片水印/my_png_图片水印_常规.png";
        logoPath = "D:/watermark/test/图片水印/003.png";
        // 常规
        paramMap.put(IMAGE_MODE, "0");
        addLogoToImage(paramMap, srcImgPath, targetPath, logoPath);
        
        // 平铺
        targetPath = "D:/watermark/test/图片水印/my_png_图片水印_平铺.png";
        paramMap.put(IMAGE_MODE, "1");
        addLogoToImage(paramMap, srcImgPath, targetPath, logoPath);
        
        // 拉伸
        targetPath = "D:/watermark/test/图片水印/my_png_图片水印_拉伸.png";
        paramMap.put(IMAGE_MODE, "2");
        paramMap.put(LOGO_HEIGHT_SCALE, "0.8");
        paramMap.put(LOGO_WIDTH_SCALE, "0.5");
        addLogoToImage(paramMap, srcImgPath, targetPath, logoPath);
        System.out.println ("图片添加图片水印结束...");
    }
    
}

测试一:

测试二:

测试三:

常规

拉伸 

 平铺

测试四:

测试文件路径:

项目结构:

 相关附件请参考评论。

posted @ 2020-07-01 18:23  王晓鸣  阅读(371)  评论(1编辑  收藏  举报