A Tool Class in Java to Implement PDF Watermarking
preface
Procedure
1、 Import Dependencies
<!-- Operation on PDF file --> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.13.1</version> </dependency> <!-- PDF file font prevents Chinese garbled code --> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency>
2、 Tool code
import com.itextpdf.text.Element; import com.itextpdf.text.pdf.*; import org.apache.commons.io.IOUtils; import java.io.FileInputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Optional; /** * WatermarkUtils *PDF Add Watermark Tool Class * * @author Lcry */ public class WaterMarkUtils { Public static final String DEFAULT_WATERMARK_TEXT="Top Secret Information"; /** *Pdf Add Watermark * *@ param waterMarkText Watermark text * @param pdfFileBytes pdf *@ param outputFilePath output stream */ public static void addWaterMark(String waterMarkText, byte[] pdfFileBytes, OutputStream outputFilePath) { try { //Original PDF file PdfReader reader = new PdfReader(pdfFileBytes); //Exported PDF file content PdfStamper stamper = new PdfStamper(reader, outputFilePath); //Font comes from the itext asian jar package BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", true); PdfGState gs = new PdfGState(); //Set Transparency gs.setFillOpacity(0.2f); gs.setStrokeOpacity(0.3f); int totalPage = reader.getNumberOfPages() + 1; for (int i = 1; i < totalPage; i++) { //Content upper layer PdfContentByte content = stamper.getOverContent(i); content.beginText(); //Font Add Transparency content.setGState(gs); //Add font size, etc content.setFontAndSize(baseFont, 170); //Add Range content.showTextAligned(Element. ALIGN_BOTTOM, Optional.ofNullable(waterMarkText).orElse(""), 100, 100, 45); content.endText(); } //Close stamper.close(); reader.close(); } catch (Exception e) { e.printStackTrace(); } } }
3、 Test
public static void main(String[] args) throws Exception { FileInputStream fileInputStream = new FileInputStream("C:\\Users\\lcry\\Downloads\\2021sj.pdf"); AddWaterMark ("Confidential Information", IOUtils. toByteArray (fileInputStream), Files. newOutputStream (Paths. get ("C: Users lcry Downloads 2021sj mark. pdf")); }
Effect Preview
Reference article
Add text watermark to java pdf (very professional)