SpringBoot集成SpirePDF實(shí)現(xiàn)文本替換功能
SpirePDF 10.6.2 很強(qiáng)大,API 也封裝的很好,使用的時候及其舒適。但是需要購買許可,不然有很大限制,最大的問題在于會添加水印,這就導(dǎo)致基本上用不了。有錢真好,真是嘴饞。
好在 SpirePDF 也有版本較老的免費(fèi)版本,有查到一個 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;
/**
* 旋轉(zhuǎn)文字
*
* @param page 頁碼
* @param x 橫坐標(biāo)
* @param y 縱坐標(biāo)
* @param newText 新文本
* @throws IOException 異常
*/
private static void RotateText(PdfPageBase page, double x, double y, String newText) throws IOException {
PdfGraphicsState state = page.getCanvas().save();// 保存畫布狀態(tài)
ClassPathResource resource = new ClassPathResource("font/原版宋體.ttf");
PdfTrueTypeFont customFont = new PdfTrueTypeFont(resource.getInputStream(), DEFAULT_FONT_SIZE);
PdfStringFormat centerAlignment = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);// 設(shè)置文本對齊方式
// 指定文本在畫布中的坐標(biāo)位置
page.getCanvas().translateTransform(x, y);
// 循環(huán)繪制 12 條文本內(nèi)容,并設(shè)置每條文本內(nèi)容間隔 30 度,即每一條文本內(nèi)容以繪制的上一文本內(nèi)容旋轉(zhuǎn) 30 度(這里如只需繪制單個文本,直接指定旋轉(zhuǎn)角度即可)
page.getCanvas().rotateTransform(90);
page.getCanvas().drawString(newText, customFont, PdfBrushes.getBlack(), 0, -5, centerAlignment);
// 再次保存畫布狀態(tài)
page.getCanvas().restore(state);
}
/**
* 替換 PDF 文件中的文本
*
* @param inputStream 被修改的 PDF 文件的字節(jié)數(shù)組
* @param outputStream 修改后的 PDF 文件的字節(jié)數(shù)組
* @param replacements 替換文本的鍵值對
* @throws IOException 異常
*/
public static void replaceTextInPdf(byte[] inputStream, ByteArrayOutputStream outputStream, Map<String, String> replacements) throws IOException {
// 創(chuàng)建PdfDocument類的實(shí)例
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();
// 搜索關(guān)鍵字
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();
// 根據(jù)要替換的文本方向,如果要豎過來的需要旋轉(zhuǎn)以下
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文檔保存為字節(jié)數(shù)組
pdf.saveToStream(outputStream);
// 關(guān)閉文檔
pdf.close();
}
}4、調(diào)用工具類
private String saveContent(ContentSaveReqVO reqVO) throws Exception {
// 構(gòu)建模板參數(shù)
Map<String, String> replacements = new HashMap<>();
replacements.put("\\$\\{起始日期}", reqVO.getStartDate());
replacements.put("\\$\\{結(jié)束日期}", reqVO.getEndDate());
// 獲取模板文件內(nèi)容,修改為你們自己獲取模板的方式
byte[] fileContent = 例如從數(shù)據(jù)庫讀取或者讀取本地文件;
if (fileContent == null) {
throw exception(TEMPLATE_NOT_EXISTS);
}
// 保存到字節(jié)數(shù)組,out 中就是替換后的文件的字節(jié)流,可以直接存數(shù)據(jù)庫也可以生成文件后再進(jìn)行處理
ByteArrayOutputStream out = new ByteArrayOutputStream();
SpirePDFUtil.replaceTextInPdf(fileContent, out, replacements);
}5、部署時的注意點(diǎn)
還需要注意一點(diǎn)時如果你的生產(chǎn)環(huán)境沒有設(shè)置線程的文化區(qū)域,部署到 Linux 之后運(yùn)行時會報工具類初始化錯誤,提示 ClassNotFound。因?yàn)?SpiderPDF 要求當(dāng)前線程的文化區(qū)域不能為空也不能是中立文化區(qū)域,所以可以再啟動時設(shè)置一下,或者你們自己用合適的方式處理一下。
public static void main(String[] args) {
// 設(shè)置線程的當(dāng)前文化為具體的區(qū)域文化
Locale.setDefault(Locale.CHINA);
SpringApplication.run(ServerApplication.class, args);
}到此這篇關(guān)于SpringBoot集成SpirePDF實(shí)現(xiàn)文本替換功能的文章就介紹到這了,更多相關(guān)SpringBoot SpirePDF文本替換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
intellij idea快速查看當(dāng)前類中的所有方法(推薦)
這篇文章主要介紹了intellij idea快速查看當(dāng)前類中的所有方法,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09
Java二維數(shù)組實(shí)現(xiàn)數(shù)字拼圖效果
這篇文章主要為大家詳細(xì)介紹了Java二維數(shù)組實(shí)現(xiàn)數(shù)字拼圖效果,控制臺可以對空格進(jìn)行移動,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-07-07
SpringBoot項(xiàng)目部署在weblogic中間件的注意事項(xiàng)說明
這篇文章主要介紹了SpringBoot項(xiàng)目部署在weblogic中間件的注意事項(xiàng)說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
基于Java的界面開發(fā)詳細(xì)步驟(用戶注冊登錄)
通過一段時間Java Web的學(xué)習(xí),寫一個簡單的注冊登陸界面來做個總結(jié),這篇文章主要給大家介紹了基于Java的界面開發(fā)(用戶注冊登錄)的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-01-01
SpringBoot RestTemplate請求日志打印方式
這篇文章主要介紹了SpringBoot RestTemplate請求日志打印方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07
java 使用HttpURLConnection發(fā)送數(shù)據(jù)簡單實(shí)例
這篇文章主要介紹了java 使用HttpURLConnection發(fā)送數(shù)據(jù)簡單實(shí)例的相關(guān)資料,需要的朋友可以參考下2017-06-06

