java给pdf添加水印

public static void main(String[] args) {
        com.ciic.core.util.OfficeUtil.setLicence();
        addWatermark("C:\\Users\\Dash\\Desktop\\劳动合同(标准版).pdf","已作废");
    }
    // 添加水印
    //filepath:文件路径
    //data:水印文字内容
    public static void addWatermark(String filepath,String data) {
        Document pdfDocument = new Document(filepath);

        TextStamp textStamp1 = new TextStamp(data);
        textStamp1.setBackground(false);
        textStamp1.setXIndent(200);//设置位置
        textStamp1.setYIndent(300);
        textStamp1.setRotateAngle(50);//设置旋转角度
        textStamp1.getTextState().setFont(FontRepository.findFont("Arial"));
        textStamp1.getTextState().setFontSize(80.0F);//设置字体大小
        textStamp1.getTextState().setFontStyle(FontStyles.Italic);
        textStamp1.getTextState().setForegroundColor(Color.getLightGray());//设置字体颜色

        PageCollection pages = pdfDocument.getPages();
        int size = pages.size();
        for (int i = 1; i <= size; i++) {
            pages.get_Item(i).addStamp(textStamp1);
        }
        pdfDocument.save("C:\\Users\\Dash\\Desktop\\水印合同.pdf");
    }

    @Test
    public void waterMarkTest(){
        com.ciic.core.util.OfficeUtil.setLicence();
        Document pdfDocument = new Document("C:\\Users\\Dash\\Desktop\\劳动合同(标准版).pdf");
        ImageStamp imageStamp = new ImageStamp("D:\\other\\image\\black.png");
        //设置水印背景的宽高,还有透明度
        imageStamp.setHeight(280);
        imageStamp.setWidth(280);
        imageStamp.setOpacity(0.2);
        imageStamp.setRotateAngle(50);
        for(Page page : pdfDocument.getPages())
        {
            //让每一页的边距为0,也可以自定义设置
            page.getPageInfo().setMargin(new MarginInfo(0,0,0,0));
//            for (double y = 0; y < page.getPageInfo().getHeight(); y = y + imageStamp.getHeight())
//            {
//                for (double x = 0; x < page.getPageInfo().getWidth(); x = x + imageStamp.getWidth())
//                {
                    //设置图片位置的x,y轴,通过双重循环来达到铺满背景的目的
                    imageStamp.setXIndent(180);
                    imageStamp.setYIndent(300);
                    //添加水印
                    page.addStamp(imageStamp);
                    // imageStamp.put(page);
//                }
//            }
        }
        //输出到磁盘
        pdfDocument.save("C:\\Users\\Dash\\Desktop\\图片水印合同.pdf");
    }

猜你喜欢

转载自blog.csdn.net/Romantic_321/article/details/121911604