Java 8 itextpdf 實現 給 pdf 添加水印

前言

給pdf添加水印功能是日常開發中經常會遇到的問題,下面我們就來看看怎麼通過Java實現給pdf文件添加水印

環境

新創建個Spring Boot的項目,然後添加itextpdf的依賴,具體的pom.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo-pdf</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo-pdf</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.4.3</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

代碼

/**
 * Copyright 2020. thunisoft.com Studio All Right Reserved
 * <p>
 * Create on 2020-05-19 17:05
 * Created by zhaoxinguo
 * Version 2.0.0
 */
package com.example.demopdf.test;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import java.io.FileOutputStream;

/**
 * @description: TODO
 * @author zhaoxinguo
 * @date 2020/5/19 17:05
 */
public class PdfTest {

    public static void main(String[] args) {
        waterMark("E:\\BaiduNetdiskDownload\\Spring Microservices in Action.pdf", "E:\\BaiduNetdiskDownload\\Spring Microservices in Action 副本.pdf", "市委組織部");
    }

    /**
     * @param inputFile 你的PDF文件地址
     * @param outputFile 添加水印後生成PDF存放的地址
     * @param waterMarkName 你的水印
     * @return
     */
    public static boolean waterMark(String inputFile,
                                    String outputFile, String waterMarkName) {
        try {
            PdfReader reader = new PdfReader(inputFile);
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
            //這裏的字體設置比較關鍵,這個設置是支持中文的寫法
            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);// 使用系統字體
            int total = reader.getNumberOfPages() + 1;

            PdfContentByte under;
            Rectangle pageRect = null;
            for (int i = 1; i < total; i++) {
                pageRect = stamper.getReader().getPageSizeWithRotation(i);
                // 計算水印X,Y座標
                float x = pageRect.getWidth()/10;
                float y = pageRect.getHeight()/10-10;
                // 獲得PDF最頂層
                under = stamper.getOverContent(i);
                under.saveState();
                // set Transparency
                PdfGState gs = new PdfGState();
                // 設置透明度爲0.2
                gs.setFillOpacity(1.f);
                under.setGState(gs);
                under.restoreState();
                under.beginText();
                under.setFontAndSize(base, 60);
                under.setColorFill(BaseColor.ORANGE);

                // 水印文字成45度角傾斜
                under.showTextAligned(Element.ALIGN_CENTER, waterMarkName, x, y, 55);
                // 添加水印文字
                under.endText();
                under.setLineWidth(1f);
                under.stroke();
            }
            stamper.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}

運行結果

Java 8 itextpdf 實現 給 pdf 添加水印 01.png

結束語

以上就是Spring Boot 集成 itextpdf 實現給PDF添加水印的全部內容,如有問題歡迎加入QQ交流羣:羣號:715224124,謝謝!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章