Java 8 itextpdf 实现 给 pdf 添加水印

迷彩 28天前 ⋅ 99 阅读

前言

给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,谢谢!


全部评论: 0

    我有话说: