Java adds custom text watermarks to images, PDFs and other documents, easy to use for personal testing

        With the advent of the era of big data, data security has gradually been put on the agenda. What I will share with you today is adding custom watermarks to pictures in Java, adding custom watermarks to documents such as PDF and Word.

I'm not talking nonsense here, just upload the code, paste it into your project and use it, if there is a lack of dependency references, you need to download it yourself.

The official website of the jar package (it may not be opened without overturning the wall): https://mvnrepository.com/

Lazy people can directly copy the following Maven dependencies:

		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itextpdf</artifactId>
			<version>5.5.13</version>
		</dependency>

Add text watermark to PDF, Word and other documents:

​    //为了使文字向左移动5像素
	private static int interval = -5;
	/**
	 * PDF加文字水印
	 * @param inputFile        PDF文件输入路径
	 * @param outputFile       PDF文件输出路径
	 * @param waterMarkName    自定义水印
	 */
	private static void waterMarkPdf(String inputFile,String outputFile, String waterMarkName) {
		log.info("开始对PDF进行添加文字水印。");
		//根据水印文字长度,更改水印文字大小
		int size = 0;
		if (waterMarkName.length() <= 13) {
			size = 50;
		}else if(waterMarkName.length() > 13 && waterMarkName.length() <= 33) {
			size = 35;
		}else {
			size = 20;
		}
		try {	
			PdfReader reader = new PdfReader(inputFile);
			FileOutputStream outputStream = new FileOutputStream(outputFile);
			PdfStamper stamper = new PdfStamper(reader, outputStream);
			//设置文字样式
			BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
			
			Rectangle pageRect = null;
			
			PdfGState gs = new PdfGState();
			//设置透明度
			gs.setFillOpacity(0.03f);
			
			gs.setStrokeOpacity(0.4f);
			
			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 = null;
		
			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, size);
		
				//调整for循环的宽高可更改水印位置,高:textH 宽:textW
				for (int height = interval + textH; height < pageRect.getHeight(); height = height + textH*10) {
		
					for (int width = interval + textW; width < pageRect.getWidth() + textW; width = width + textW*5) {
				        //水印文字成21度角倾斜
						under.showTextAligned(Element.ALIGN_LEFT, waterMarkName, width - textW, height - textH, 21);			
					}	
				}
				// 添加水印文字
				under.endText();
			}
			//关闭流
			stamper.close();
			outputStream.close();
			reader.close();
			
			} catch (Exception e) {
				log.error("异常:", e);
			}
		log.info("pdf添加文字水印结束。");
	}

Add text watermark to image:

    /**
	 * 图片加文字水印
	 * @param text            水印内容
	 * @param transparency    清晰度
     * @param imageName       图片名(含后缀)
     * @param path            图片保存位置
	 */
	private static void clearImage(String text, Float transparency,String imageName, String path) {
		log.info("开始对图片添加文字水印。");
		try {
	        // 读取本地图片文件
	         File file = new File(path + imageName);

	        // 将文件对象转化为图片对象(限png、jpg、gif)
	         BufferedImage image = ImageIO.read(file);
	         //图片宽度不足,返回无水印图片
	         if (!(image.getWidth() > (text.length()*20) + 10)) {
	        	File f = new File(path + "waterMark" + imageName);
		        FileOutputStream outputFile = new FileOutputStream(f);
                //此处需设置图片类型
		 		ImageIO.write(image, "png", outputFile);
		 		outputFile.close();
			}else {
                //设置水印字体大小
		        int size = 5;
		        if (image.getWidth() >= text.length() * 30) {
		        	size = 30;
				}else if (image.getWidth() >= text.length() * 20) {
					size = 20;
				}else if (image.getWidth() >= text.length() * 10) {
					size = 10;
				}
	
		        Graphics2D pen = image.createGraphics();
	
		        pen.setColor(Color.BLACK);
		        // 设置画笔字体样式为微软雅黑 斜体:Font.ITALIC
		        pen.setFont(new Font("微软雅黑", Font.BOLD, size));
		        //文字倾斜
		        pen.shear(0.1, -0.4);
		        //消除文字锯齿
		        pen.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
		        //设置文字透明度
		        pen.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, transparency));
		        //获取文本长度,用来设置坐标
		        int len = text.length();
		        //获取水印坐标位置
		        int width = image.getWidth()/2;
		        int height = image.getHeight()/2;
		        if (image.getWidth() - (len*size) > 0) {
		        	//根据水印字体长度,控制水印位置
					width = image.getWidth()/2 - (len/2)*size;
				}
		        if (image.getHeight() - 100 > 0) {
		        	height = image.getHeight() - 100;
				}
		        //添加水印
		        pen.drawString(text, width, height);
		        //创建新图片文件
		        File file2 = new File(path + "waterMark" + imageName);
	        	//将处理好的图片数据写入到新图片文件中        
				FileOutputStream outputFile = new FileOutputStream(file2);
                //此处需设置图片类型
				ImageIO.write(image, "png", outputFile);
				outputFile.close();
			}
	        
		} catch (Exception e) {
			log.error("异常:", e);
			
		}
		log.info("png图片添加文字水印结束。");
    }

    

        The above is all the content of adding text watermark in Java. If you like it, you can like and bookmark it. Thank you O(∩_∩)O

Guess you like

Origin blog.csdn.net/guo0208/article/details/127515412