如何使用Java为PDF中的图像添加水印。(How to add water marks to the images in a PDF using Java.)

优质
小牛编辑
130浏览
2023-12-01

问题描述 (Problem Description)

如何使用Java为PDF中的图像添加水印。

解决方案 (Solution)

以下是使用Java在PDF中为图像添加水印的程序。

import com.itextpdf.io.image.ImageDataFactory; 
import com.itextpdf.kernel.color.DeviceGray; 
import com.itextpdf.kernel.geom.Rectangle; 
import com.itextpdf.kernel.pdf.PdfDocument; 
import com.itextpdf.kernel.pdf.PdfWriter; 
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject; 
import com.itextpdf.layout.Canvas; 
import com.itextpdf.layout.Document; 
import com.itextpdf.layout.element.Image; 
import com.itextpdf.layout.property.TextAlignment;  
public class AddingToImagesInPDF { 
   public static void main(String args[]) throws Exception { 
      String file = "C:/EXAMPLES/itextExamples/addingImageToPDF.pdf"; 
      //Creating a PdfDocument object 
      PdfDocument pdfDoc = new PdfDocument(new PdfWriter(file));     
      //Creating a Document object 
      Document doc = new Document(pdfDoc);        
      //Creating an Image         
      Image image = new Image(ImageDataFactory.create(
         "C:/EXAMPLES/itextExamples/logo.jpg")); 
      image.scaleToFit(400, 700); 
      //Creating template             
      PdfFormXObject template = new PdfFormXObject(new Rectangle(
         image.getImageScaledWidth(), image.getImageScaledHeight())); 
      Canvas canvas = new Canvas(template, pdfDoc).add(image); 
      String watermark = "Welcome to xnip"; 
      canvas.setFontColor(DeviceGray.LIGHT_GRAY)      
         .showTextAligned(watermark, 100, 360, TextAlignment.CENTER);  
      //Adding template to document
      Image image1 = new Image(template);          
      doc.add(image1); 
      //Closing the document 
      doc.close();  
      System.out.println("Watermark added successfully..");  
   }  
}

输入 (Input)

OpenCV复制输入

输出 (Output)

水印