java -PDF添加文本水印与图片水印

时间:2024-03-18 09:16:53

java pdf添加水印文本及图片文本

PDF文件添加文本水印

    private static int interval = 30;  
    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.3f);
            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; 
            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, 30); //控制字体间宽度
                // 水印文字成30度角倾斜
                for (int height = interval + textH; height < pageRect.getHeight();  height = height + textH*8) {
                    for (int width = interval + textW; width < pageRect.getWidth() + textW;  width = width + textW*4) {
                        under.showTextAligned(Element.ALIGN_LEFT , waterMarkName, width - textW, 
                                height - textH, 30);  }  } 
                // 添加水印文字     
                under.endText(); 
                }   
            //关闭流  
            stamper.close();  
            reader.close(); 
            } catch (Exception e) {     
                e.printStackTrace();     
            }   
        }

 

 

PDF添加图片水印:

private static final float IAMGE_HEIGHT = 110f; // 水印图片的的高度
    private static final float IAMGE_WIDTH = 110f; // 水印图片的的宽度
    public static void addPdfMark(String pdfPath,String logoPath, String outPath) throws Exception {

        PdfReader reader = new PdfReader(pdfPath, "PDF".getBytes());
        // 如果是web项目,直接下载应该放到response的流里面
        // PdfStamper stamp = new PdfStamper(reader,response.getOutputStream());
        // 添加水印之后的pdf文件
        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(outPath));
        int pageSize = reader.getNumberOfPages();

        float pageHeight = reader.getPageSize(1).getHeight();
        float pageWidth = reader.getPageSize(1).getWidth();
        try {
            // 每两行显示两个 左边一个,右边一个
            int lineNum = (int) (pageHeight / IAMGE_HEIGHT); // 行数
            int middleY = (int) pageWidth / 2;
            for (int i = 1; i <= pageSize; i++) {
                for (int j = 0, k = 0; j < lineNum; j = j + 4, k++) {
                    Random random = new Random();
                    // 放入水印
                    Image img = Image.getInstance(logoPath);
                    img.scaleAbsolute(IAMGE_WIDTH, IAMGE_HEIGHT * 184 / 455);
                    // 将水印显示到最底层
                    img.setAlignment(Image.UNDERLYING);
                    int trueY;
                    while (true) {
                        trueY = random.nextInt(middleY);
                        if (trueY > IAMGE_WIDTH / 2 && trueY < (middleY - IAMGE_WIDTH)) {
                            break;
                        }
                    }
                    // 水印的位置
                    img.setAbsolutePosition(trueY, j * IAMGE_HEIGHT + (float) random.nextInt((int) IAMGE_HEIGHT) - (k % 2) * 10);
                    // 旋转 角度
                    img.setRotationDegrees(random.nextInt(360));
                    PdfContentByte under = stamp.getUnderContent(i);

                    PdfGState gs = new PdfGState();
                    // 设置透明度为0.5
                    gs.setFillOpacity(0.5f);
                    under.setGState(gs);
                    under.addImage(img);
                    while (true) {
                        trueY = random.nextInt(middleY) + middleY;
                        if (trueY > middleY + IAMGE_WIDTH / 2 && trueY < (2 * middleY - IAMGE_WIDTH)) {
                            break;
                        }
                    }
                    // 水印的位置
                    img.setAbsolutePosition(trueY, j * IAMGE_HEIGHT + (float) random.nextInt((int) IAMGE_HEIGHT) - (k % 2) * 10);
                    // 旋转角度
                    img.setRotationDegrees(random.nextInt(360));
                    under.addImage(img);
                }
            }
        } catch (Exception e) {
            throw e;
        } finally {
            stamp.close();
            reader.close();
        }

测试--------------------------------------------------------------------------------

public static void main(String[] args) throws Exception {
        waterMark("xxx.pdf", "yyy.pdf", "测试工程");
        //addPdfMark("xxx.pdf","image.png","yyy.xml");
        System.out.println("结束");
    }
    }      

 

参考了很多前辈的,希望能帮到各位!

模块所需jar包(itextpdf-5.5.13.1.jar)