前言
该工具用于调整pdf中文本内容,具体位置需要根据自己根据坐标进行调整。通过填充空白框,再添加新内容实现文本内容替换。
依赖
<?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.tools</groupId>
<artifactId>pdf-tools</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>pdf-tools</name>
<description>pdf-tools</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- PDF工具类 -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.27</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox-tools</artifactId>
<version>2.0.27</version>
</dependency>
<!-- -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
配置
server:
port: 8083
spring:
datasource:
url: jdbc:mysql://localhost/test01?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false&allowMultiQueries=true
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.zaxxer.hikari.HikariDataSource
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# global-config:
# db-config:
# table-underline: false
pdf:
file:
path:
old-path: D:/testFile/pdf/notification/p1
new-path: D:/testFile/pdf/notification/p2
配置类
package com.tools.pdftools.config;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 添加你的拦截器,如果有的话
// ...
return interceptor;
}
@Bean
public ConfigurationCustomizer configurationCustomizer() {
return configuration -> {
configuration.setMapUnderscoreToCamelCase(false); // 关闭驼峰命名映射
};
}
}
业务代码
package com.tools.pdftools;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.tools.pdftools.model.Student;
import com.tools.pdftools.properties.FilePathProperties;
import com.tools.pdftools.service.StudentService;
import com.tools.pdftools.util.PDFUtils;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.awt.*;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
@SpringBootTest
@Slf4j
class PdfToolsApplicationTests {
@Autowired
private FilePathProperties filePathProperties;
@Autowired
private StudentService studentService;
@Test
void contextLoads() throws Exception {
addPdf();
}
private void addPdf() throws IOException, ParseException {
QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("state", 1);
List<Student> students = studentService.getBaseMapper().selectList(queryWrapper);
if (CollectionUtils.isEmpty(students)) {
return;
}
String originalPath = filePathProperties.getOldPath();
String newPath = filePathProperties.getNewPath();
Color color = Color.WHITE;
for (Student student : students) {
String originalPathAct = originalPath + student.getRemark();
String newPathAct = newPath + student.getRemark();
Date createTime = student.getCreateTime();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd HH:mm");
Date createTimeStr = format.parse("20240711 06:00");
Boolean flag = createTime.before(createTimeStr);
// PDFUtils.adjustPDF(originalPathAct, newPathAct,student.getName(),student.getGender()==1?"男":"女",student.getBirthday());
PDFUtils.addPDF(originalPathAct, newPathAct, color, flag, student);
log.info("==========={}已完成添加年月日==========", student.getName());
}
}
}
package com.tools.pdftools.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "pdf.file.path")
@Data
public class FilePathProperties {
private String oldPath;
private String newPath;
}
package com.tools.pdftools.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.tools.pdftools.model.Student;
public interface StudentService extends IService<Student> {
}
package com.tools.pdftools.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tools.pdftools.mapper.StudentMapper;
import com.tools.pdftools.model.Student;
import com.tools.pdftools.service.StudentService;
import org.springframework.stereotype.Service;
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
}
package com.tools.pdftools.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.tools.pdftools.model.Student;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface StudentMapper extends BaseMapper<Student> {
}
package com.tools.pdftools.util;
import com.tools.pdftools.model.Student;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@Slf4j
public class PDFUtils {
public static void addPDF(String originalPath, String newPath, Color color, Boolean flag, Student student, Rectangle... rectangles) throws IOException {
try (PDDocument document = PDDocument.load(new File(originalPath))) {
PDPage page = document.getPage(0); // 获取第一页
// 创建一个新的内容流,以追加模式添加到页面上
try (PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true)) {
// 设置绘图颜色为白色(这里使用CMYK颜色空间中的白色,对于RGB颜色空间,使用1, 1, 1)
// 注意:PDFBox默认使用CMYK颜色空间,但也可以切换到RGB
// 对于RGB,可以使用contentStream.setNonStrokingColor(Color.WHITE.getRGB()); 但需要额外导入java.awt.Color
// 这里为了简单起见,我们继续使用CMYK并假设PDFBox已正确设置为默认颜色空间
// 在实际中,你可能需要检查PDF的颜色空间并相应地设置颜色
// float[] cmykWhite = {0f, 0f, 0f, 1f}; // CMYK中的白色
contentStream.setNonStrokingColor(color);
if (rectangles == null || rectangles.length == 0) {
rectangles = new Rectangle[3];
rectangles[0] = new Rectangle(120, 780, 35, 15);
rectangles[1] = new Rectangle(205, 780, 30, 15);
rectangles[2] = new Rectangle(290, 780, 60, 15);
// rectangles[0] = new Rectangle(120, 765, 50, 15);
// rectangles[1] = new Rectangle(205, 765, 35, 15);
// rectangles[2] = new Rectangle(290, 765, 60, 15);
}
if (rectangles.length >= 3) {
if (originalPath.contains("=====================")) {
rectangles[0] = new Rectangle(120, 780, 35, 15);
rectangles[1] = new Rectangle(205, 780, 30, 15);
rectangles[2] = new Rectangle(290, 780, 60, 15);
}
if ((originalPath.contains("condition") && !flag)) {
rectangles[0] = new Rectangle(120, 780, 35, 15);
rectangles[1] = new Rectangle(220, 780, 30, 15);
rectangles[2] = new Rectangle(305, 780, 60, 15);
}
if (
originalPath.contains("condition")
|| originalPath.contains("condition")
|| originalPath.contains("condition")
) {
rectangles[0] = new Rectangle(120, 765, 35, 15);
rectangles[1] = new Rectangle(205, 765, 35, 15);
rectangles[2] = new Rectangle(290, 765, 60, 15);
}
if (originalPath.contains("condition") && flag) {
rectangles[0] = new Rectangle(120, 730, 35, 15);
rectangles[1] = new Rectangle(180, 730, 35, 15);
rectangles[2] = new Rectangle(260, 730, 60, 15);
}
if ((originalPath.contains("condition") && flag)
|| (originalPath.contains("condition") && flag)
|| (originalPath.contains("condition") && flag)
) {
rectangles[0] = new Rectangle(120, 742, 35, 15);
rectangles[1] = new Rectangle(180, 742, 35, 15);
rectangles[2] = new Rectangle(260, 742, 60, 15);
}
if (originalPath.contains("condition")) {
rectangles[0] = new Rectangle(118, 738, 35, 15);
rectangles[1] = new Rectangle(180, 738, 35, 15);
rectangles[2] = new Rectangle(260, 738, 60, 15);
}
if (originalPath.contains("condition")
|| originalPath.contains("condition")
|| (originalPath.contains("condition") && !flag)
) {
rectangles[0] = new Rectangle(120, 780, 35, 15);
rectangles[1] = new Rectangle(205, 780, 30, 15);
rectangles[2] = new Rectangle(290, 780, 60, 15);
}
}
// 绘制一个矩形覆盖指定区域
// 这里的参数是:x, y, width, height, 其中x, y是矩形左下角的坐标
// contentStream.addRect(480, 230, 20, 10); // 假设我们要覆盖的区域
for (Rectangle rectangle : rectangles) {
double x = rectangle.getX();
double y = rectangle.getY();
double width = rectangle.getWidth();
double height = rectangle.getHeight();
// 假设我们要覆盖的区域
contentStream.addRect((float) x, (float) y, (float) width, (float) height);// 假设我们要覆盖的区域
}
contentStream.fill(); // 填充矩形
// 假设您的字体文件位于类路径下
// FileInputStream fileInputStream = new FileInputStream("D:/source/font/simsunb.ttf");
// InputStream fontStream = PDFUtils.class.getClassLoader().getSystemResourceAsStream("font/simsunb.ttf");
// 加载字体
//
Integer fontsize = 10;
Integer adjustHeight = 3;
File fontFile = new File("C:\\Windows\\fonts\\SIMFANG.TTF");
PDType0Font font = PDType0Font.load(document, fontFile);
//
contentStream.setNonStrokingColor(Color.BLACK);
contentStream.beginText();
contentStream.setFont(font, fontsize);
// 设置文本位置(左下角为原点,向右为x正方向,向上为y正方向)
contentStream.newLineAtOffset((float) rectangles[0].getX(), (float) (rectangles[0].getY() + adjustHeight));
contentStream.showText(student.getName()); // 显示文本
contentStream.endText();
contentStream.setNonStrokingColor(Color.BLACK);
contentStream.beginText();
contentStream.setFont(font, fontsize);
contentStream.newLineAtOffset((float) rectangles[1].getX(), (float) rectangles[1].getY() + adjustHeight);
contentStream.showText(student.getGender() == 1 ? "男" : "女"); // 显示文本
contentStream.endText();
contentStream.setNonStrokingColor(Color.BLACK);
contentStream.beginText();
contentStream.setFont(font, fontsize);
contentStream.newLineAtOffset((float) rectangles[2].getX(), (float) (rectangles[2].getY() + adjustHeight));
contentStream.showText(student.getBirthday()); // 显示文本
contentStream.endText();
// 注意:坐标和尺寸需要根据你的PDF页面大小和布局进行调整
}
Path path = Paths.get(newPath);
Path directoryPath = path.getParent();
if (!Files.exists(directoryPath)) {
Files.createDirectories(directoryPath);
}
// 保存修改后的PDF
document.save(newPath);
} catch (IOException e) {
e.printStackTrace();
}
}
}