SpirePDF 10.6.2 很强大,API 也封装的很好,使用的时候及其舒适。但是需要购买许可,不然有很大限制,最大的问题在于会添加水印,这就导致基本上用不了。有钱真好,真是嘴馋。
好在 SpirePDF 也有版本较老的免费版本,有查到一个 5.1.0。接下来附上使用代码
1、在 pom.xml 文件中添加他们的源
<!-- 使用 huawei / aliyun 的 Maven 源,提升下载速度 -->
<repositories>
<repository>
<id>huaweicloud</id>
<name>huawei</name>
<url>https://mirrors.huaweicloud.com/repository/maven/</url>
</repository>
<repository>
<id>aliyunmaven</id>
<name>aliyun</name>
<url>https://maven.aliyun.com/repository/public</url>
</repository>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<releases>
<enabled>false</enabled>
</releases>
</repository>
</repositories>
2、在 pom.xml 文件中引入 SpirePDF 的依赖
这边需要注意 artifactId 是 spire.pdf.free 而非 spire.pdf。我没注意拉不下来依赖,以为是源的问题或者缓存问题,前前后后耽搁几个小时,都是泪
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf.free</artifactId>
<version>5.1.0</version>
</dependency>
3、工具类
package cn.iocoder.yudao.module.contract.service.content;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.general.find.PdfTextFind;
import com.spire.pdf.general.find.PdfTextFindCollection;
import com.spire.pdf.graphics.*;
import org.springframework.core.io.ClassPathResource;
import java.awt.geom.Dimension2D;
import java.awt.geom.Rectangle2D;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
public class SpirePDFUtil {
// 文字大小
private final static float DEFAULT_FONT_SIZE = 12f;
/**
* 旋转文字
*
* @param page 页码
* @param x 横坐标
* @param y 纵坐标
* @param newText 新文本
* @throws IOException 异常
*/
private static void RotateText(PdfPageBase page, double x, double y, String newText) throws IOException {
PdfGraphicsState state = page.getCanvas().save();// 保存画布状态
ClassPathResource resource = new ClassPathResource("font/原版宋体.ttf");
PdfTrueTypeFont customFont = new PdfTrueTypeFont(resource.getInputStream(), DEFAULT_FONT_SIZE);
PdfStringFormat centerAlignment = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);// 设置文本对齐方式
// 指定文本在画布中的坐标位置
page.getCanvas().translateTransform(x, y);
// 循环绘制 12 条文本内容,并设置每条文本内容间隔 30 度,即每一条文本内容以绘制的上一文本内容旋转 30 度(这里如只需绘制单个文本,直接指定旋转角度即可)
page.getCanvas().rotateTransform(90);
page.getCanvas().drawString(newText, customFont, PdfBrushes.getBlack(), 0, -5, centerAlignment);
// 再次保存画布状态
page.getCanvas().restore(state);
}
/**
* 替换 PDF 文件中的文本
*
* @param inputStream 被修改的 PDF 文件的字节数组
* @param outputStream 修改后的 PDF 文件的字节数组
* @param replacements 替换文本的键值对
* @throws IOException 异常
*/
public static void replaceTextInPdf(byte[] inputStream, ByteArrayOutputStream outputStream, Map<String, String> replacements) throws IOException {
// 创建PdfDocument类的实例
PdfDocument pdf = new PdfDocument();
// 加载PDF文件
pdf.loadFromBytes(inputStream);
// 遍历PDF文件的页面替换文本
for (PdfPageBase page : (Iterable<? extends PdfPageBase>) pdf.getPages()) {
for (Map.Entry<String, String> entry : replacements.entrySet()) {
String searchText = entry.getKey();
String replaceText = entry.getValue();
// 搜索关键字
PdfTextFindCollection collection = page.findText(searchText, false);
for (PdfTextFind findObj : collection.getFinds()) {
Dimension2D size = findObj.getSize();
// 获取文本在页面中的范围
Rectangle2D.Float rec = (Rectangle2D.Float) findObj.getBounds();
// 写入空白范围遮住原来的文本
page.getCanvas().drawRectangle(PdfBrushes.getWhite(), rec);
double width = size.getWidth();
double height = size.getHeight();
// 根据要替换的文本方向,如果要竖过来的需要旋转以下
if (width < height) {
RotateText(page, rec.getX(), rec.getY(), replaceText);
} else {
ClassPathResource resource = new ClassPathResource("font/原版宋体.ttf");
try (InputStream fontStream = resource.getInputStream()) {
PdfTrueTypeFont customFont = new PdfTrueTypeFont(fontStream, DEFAULT_FONT_SIZE);
page.getCanvas().drawString(replaceText, customFont, PdfBrushes.getBlack(), rec.getX(), rec.getY() - 3);
}
}
}
}
}
// 将修改后的PDF文档保存为字节数组
pdf.saveToStream(outputStream);
// 关闭文档
pdf.close();
}
}
4、调用工具类
private String saveContent(ContentSaveReqVO reqVO) throws Exception {
// 构建模板参数
Map<String, String> replacements = new HashMap<>();
replacements.put("\\$\\{起始日期}", reqVO.getStartDate());
replacements.put("\\$\\{结束日期}", reqVO.getEndDate());
// 获取模板文件内容,修改为你们自己获取模板的方式
byte[] fileContent = 例如从数据库读取或者读取本地文件;
if (fileContent == null) {
throw exception(TEMPLATE_NOT_EXISTS);
}
// 保存到字节数组,out 中就是替换后的文件的字节流,可以直接存数据库也可以生成文件后再进行处理
ByteArrayOutputStream out = new ByteArrayOutputStream();
SpirePDFUtil.replaceTextInPdf(fileContent, out, replacements);
}
5、部署时的注意点
还需要注意一点时如果你的生产环境没有设置线程的文化区域,部署到 Linux 之后运行时会报工具类初始化错误,提示 ClassNotFound。因为 SpiderPDF 要求当前线程的文化区域不能为空也不能是中立文化区域,所以可以再启动时设置一下,或者你们自己用合适的方式处理一下。
public static void main(String[] args) {
// 设置线程的当前文化为具体的区域文化
Locale.setDefault(Locale.CHINA);
SpringApplication.run(ServerApplication.class, args);
}