Java itext为pdf 文件添加水印核心功能代码片段

/**
	 * 
	 * @param content
	 * @param pageRect
	 * @param waterMarkContent 水印文字
	 */
	private static void addWaterMark(PdfContentByte content, Rectangle pageRect, String waterMarkContent){
		try {
			// 方式一:系统自带字体文件文件
//			String path= "C:\\Windows\\Fonts\\SIMHEI.TTF";
//			BaseFont bf = BaseFont.createFont(path, BaseFont.IDENTITY_H,BaseFont.EMBEDDED);
			//BaseFont bf = BaseFont.createFont();
	       
	        // 方式二:指定字体文件拷贝至源码文件中src/main/java,通过读取流方式事项字体文件加载
	        InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("com/digipower/erms/font/SIMFANG.TTF");
	        byte[] bytes = new byte[stream.available()];
	        stream.read(bytes);
	        BaseFont bf = BaseFont.createFont("SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED, BaseFont.NOT_CACHED,
	        		bytes, bytes);

	        Font f = new Font("仿宋", Font.PLAIN, SimpleTypeConverterUtil.convertIfNecessary(ApplicationPropertiesHolder.getProperty("watermark.size", "50"), int.class));
	        FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(f);  
	        int textH = fm.getHeight();
	        int textW =fm.stringWidth(waterMarkContent);
			content.beginText();
            // 设置字体填充色值
			content.setColorFill(new Color(201,189,189));
             // 设置字体大小
            content.setFontAndSize(bf, SimpleTypeConverterUtil.convertIfNecessary(ApplicationPropertiesHolder.getProperty("watermark.size", "23"), float.class));
             // 设置字体透明度
            PdfGState gs = new PdfGState();
            Float opacity = Float.valueOf(ApplicationPropertiesHolder.getProperty("watermark.opacity", "0.8"));
            gs.setFillOpacity(opacity);// 设置透明度为0.8
            content.setGState(gs);
            //高度,宽度的增长步长, 目前分别是 : textH*5, textW*4。 根据后续业务调整,跟字体,size相关.
            for (int height = 100 + textH; height < pageRect.getHeight();  
                    height = height + textH * 5) {
                for (int width = 200 + textW; width < pageRect.getWidth() + textW;   
                        width = width + textW * 2) {
                    // 设置水印内容和水印倾斜角度
                	content.showTextAligned(Element.ALIGN_LEFT, waterMarkContent, width - textW, height - textH, 30);
                }  
            }
            content.endText();
			
		} catch (Exception e) {
			logger.error("添加水印出错. waterMarkContent :" + waterMarkContent, e);
		} 
	}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值