
如何快速實現(xiàn)REST API集成以優(yōu)化業(yè)務(wù)流程
大家日常工作當(dāng)中有時候需要把Excel轉(zhuǎn)換為pdf打印或者轉(zhuǎn)換為圖片進行分享,目前有許多在線工具,不過大部分都是需要看激勵廣告或者收費才可以正常使用,今天給大家分享通過微信小程序自己搭建一個Excel轉(zhuǎn)換工具,隨時隨地使用免受付費或者看廣告的困擾,感興趣的朋友可以一起來了解一下!
● 開發(fā)后端PDF轉(zhuǎn)換為Word接口服務(wù)● 購買云服務(wù)器● 申請域名、SSL證書、部署后端接口服務(wù)到云服務(wù)器并配置SSL證書● 微信小程序端界面開發(fā)● 微信小程序部署上線
后端接口這里選擇Java編程語法和SpingBoot快速搭建API接口,實現(xiàn)PDF轉(zhuǎn)換為Word的功能。首先我們打開IDEA創(chuàng)建SpringBoot 接口項目。
在pom.xml文件引入pdf依賴包,具體內(nèi)容如下:
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf.free</artifactId>
<version>2.6.3</version>
<scope>provided</scope>
</dependency>
注意:為了保證Maven可以正常聯(lián)網(wǎng)拉取到依賴庫需要在pom.xml 增加官方倉儲庫如下內(nèi)容:
<repositories>
<repository>
<id>com.e-iceblue</id>
<url>http://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
后端接口采用小程序上傳文件的方式傳遞到后端接口的實現(xiàn)轉(zhuǎn)換。新建PdfToWord.java 文件
package com.spring.demo.springbootdemo.utils;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.graphics.PdfImageType;
import com.spire.pdf.widget.PdfPageCollection;
import org.apache.pdfbox.pdmodel.PDDocument;
import javax.imageio.ImageIO;
public class PdfToWord {
/**
* 根據(jù)文件流轉(zhuǎn)換為word
*
* @param stream
* @return
*/
public String pdftoword(InputStream stream, String fileNameOld) {
Date currentDate = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS"); // 指定日期格式,包含毫秒
String formattedDate = sdf.format(currentDate);
String pathPath = "/mnt/files/" + formattedDate + "_" + fileNameOld;
// 4、最終生成的doc所在的目錄,默認是和引入的一個地方,開源時對外提供下載的接口。
saveInputStreamToFile(stream, pathPath);
String fileName = "result" + formattedDate + ".docx";
String desPath = "/mnt/files/" + fileName; // 構(gòu)造文件名
String sux = fileNameOld + "_" + formattedDate;// 臨時文件前綴
boolean result = false;
try {
// 0、判斷輸入的是否是pdf文件
//第一步:判斷輸入的是否合法
//boolean flag = isPDFFile(srcPath);
//第二步:在輸入的路徑下新建文件夾
boolean flag1 = create();
if (flag1) {
// 1、加載pdf
PdfDocument pdf = new PdfDocument();
//pdf.loadFromStream(stream);
pdf.loadFromFile(pathPath);
PdfPageCollection num = pdf.getPages();
// 2、如果pdf的頁數(shù)小于11,那么直接進行轉(zhuǎn)化
if (num.getCount() <= 10) {
pdf.saveToFile(desPath, com.spire.pdf.FileFormat.DOCX);
}
// 3、否則輸入的頁數(shù)比較多,就開始進行切分再轉(zhuǎn)化
else {
//saveInputStreamToFile(stream, pathPath);
// 第一步:將其進行切分,每頁一張pdf
//pdf.split(splitPath+"test{0}.pdf",0);
splitPDF(pathPath, splitPath, 10);
clearFiles(pathPath, formattedDate);
// 第二步:將切分的pdf,一個一個進行轉(zhuǎn)換
File[] fs = getSplitFiles(splitPath);
for (int i = 0; i < fs.length; i++) {
PdfDocument sonpdf = new PdfDocument();
sonpdf.loadFromFile(fs[i].getAbsolutePath());
sonpdf.saveToFile(docPath + fs[i].getName().substring(0, fs[i].getName().length() - 4) + ".docx", FileFormat.DOCX);
}
//授權(quán)問題轉(zhuǎn)換為zip壓縮包
try {
desPath = desPath.replace(".docx", ".zip");
fileName = fileName.replace(".docx", ".zip");
result = MergeWordDocument.merge(docPath, desPath);
if (!result) {
fileName = "";
}
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
System.out.println("輸入的不是pdf文件");
fileName = "";
return fileName;
}
} catch (Exception e) {
fileName = "";
e.printStackTrace();
} finally {
//4、把剛剛緩存的split和doc刪除
if (result == true) {
clearFiles(pathPath, formattedDate);
clearFiles(splitPath, formattedDate);
clearFiles(docPath, formattedDate);
}
}
return fileName;
}
/**
* 保存原始的pdf文件為了方便拆分
*
* @param inputStream
* @param filePath
*/
public static void saveInputStreamToFile(InputStream inputStream, String filePath) {
// 使用try-with-resources自動關(guān)閉流
try (FileOutputStream outputStream = new FileOutputStream(new File(filePath))) {
byte[] buffer = new byte[1024];
int length;
// 讀取輸入流并寫入到輸出流
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
System.out.println("文件保存成功!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/***
* 分隔pdf文件10頁為一個文件
* @param pdfPath
* @param outputDirectory
* @param pageSize
*/
public static void splitPDF(String pdfPath, String outputDirectory, int pageSize) {
try {
// 加載PDF文件
//PDDocument document = PDDocument.load(stream);
PDDocument document = PDDocument.load(new File(pdfPath));
int pageCount = document.getNumberOfPages();
int fileCounter = 1;
int startPage = 0;
int index = 0;
while (startPage < pageCount) {
// 創(chuàng)建新的PDDocument對象
PDDocument newDocument = new PDDocument();
// 每指定頁數(shù)為一個文件
for (int i = startPage; i < Math.min(startPage + pageSize, pageCount); i++) {
newDocument.addPage(document.getPage(i));
}
// 保存新的PDF文件
String outputFile = outputDirectory + File.separator + "result" + index + ".pdf";
index++;
newDocument.save(outputFile);
newDocument.close();
fileCounter++;
startPage += pageSize;
}
// 關(guān)閉原始的PDF文檔
document.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
代碼思路:控制器接收到文件轉(zhuǎn)換為InputStream,然后把文件保存到的服務(wù)端,調(diào)用PDF轉(zhuǎn)換類庫進行轉(zhuǎn)換為Word。最后刪除客戶上傳的源文件就行了。說明:考慮到該PDF框架免費版目前只支持轉(zhuǎn)換10頁。這里考慮先把PDF按照10頁進行拆分。然后循環(huán)去轉(zhuǎn)換為Word,最后再把轉(zhuǎn)換后的多個word打包到一個壓縮包里面。當(dāng)然也可以去做轉(zhuǎn)換后多個word合并,這個大家可以自己去研究一下。
新建控制器用來提供接口服務(wù),供微信小程序端轉(zhuǎn)換服務(wù)調(diào)用,主要代碼如下:
package com.spring.demo.springbootdemo.control;
import com.spring.demo.springbootdemo.utils.ExcelUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
/**
* Excel 轉(zhuǎn)換 API
*/
@RestController
@RequestMapping("PDF")
public class PDFToFileApi {
/**
* pdf 轉(zhuǎn)word
* @param uploadFile
* @return
* @throws IOException
*/
@PostMapping("pdftoword")
public String pdftoword(@RequestPart("file") MultipartFile uploadFile) throws IOException {
if (null == uploadFile) {
return null;
}
// 判斷文件格式是否為pdf
String fileName = uploadFile.getOriginalFilename().toLowerCase();
if (!fileName.endsWith(".pdf")) {
return null;
}
String image= PdfUtils.pdfToDoc(uploadFile.getInputStream(),fileName);
// 返回響應(yīng)實體
return image;
}
}
說明:該方法首先要校驗文件格式是否為pdf,格式正確后才可以正常調(diào)用。
因為最終需要部署到微信小程序,所以云服務(wù)器是必須要購買的,當(dāng)然如果大家本身已經(jīng)有云服務(wù)器的話,可以跳過這個過程。我這邊使用的是騰訊云提供的2核2G的輕量級服務(wù)器,目前接口運行還是非常穩(wěn)定的。如果大家需要搭建的話,推薦使用騰訊云的輕量級服務(wù)器。
大家可以參加騰訊云雙十一拼團活動,購買服務(wù)器優(yōu)惠力度非常大,首單購買輕量級云服務(wù)器配置為2核2G3M帶寬一年僅需要68元,并且加贈三個月。作為部署轉(zhuǎn)換服務(wù)接口來說如果并發(fā)量不大的情況下是完全夠用的。月底活動結(jié)束,距離活動結(jié)束還有一周左右的時間,有需要的可以抓取最后的福利。
專屬鏈接后端服務(wù)部署簡要說明:建議購買Centos版本的操作系統(tǒng),然后給操作系統(tǒng)安裝JDK即并且配置環(huán)境變量。具體的JDK安裝步驟大家可以網(wǎng)上找一下步驟。JDK安裝后把后端服務(wù)的Jar包上傳到服務(wù)器,然后使用命令行后臺啟動即可。當(dāng)然如果有不清楚的可以評論區(qū)溝通交流!
建議選擇購買 CentOS 版本的操作系統(tǒng),并在其上安裝 JDK 及正確配置環(huán)境變量。關(guān)于 JDK 的具體安裝步驟,網(wǎng)絡(luò)上已有豐富的教程可供參考。安裝完成后,將后端服務(wù)的 Jar 包上傳至服務(wù)器,并通過命令行以后臺模式啟動服務(wù)。大家如果有問題歡迎溝通交流!如果你已經(jīng)有域名并且有SSL證書,本步驟可以跳過。因為微信小程序調(diào)用接口需要HTTPS的域名進行調(diào)用。所以該步驟是微信小程序上線必備的操作。大家可以登錄騰訊云官網(wǎng)購買域名核的SSL證書的申請.注意:目前免費的SSL證書有效期是三個月,大家注意及時更換。證書申請后可以安裝nginx來配置證書,首先需要把申請通過的SSL證書上傳到服務(wù)器指定的文件夾,然后直接在nginx.conf文件里面配置即可。因為過程比較簡單,大家可以自行配置。
首先看下界面的效果
界面主要包括上傳方式的選擇、轉(zhuǎn)換類型、按鈕、結(jié)果文件展示。首先是選擇PDF文件上傳后會自動調(diào)用后端接口實現(xiàn)文件轉(zhuǎn)換,轉(zhuǎn)換成功后結(jié)果文件會體現(xiàn)轉(zhuǎn)換成功后的文件名稱。然后點擊下載可以下載轉(zhuǎn)換后的Word或者壓縮包文件。wxml主要代碼文件
<view style="text-align: center;">
<image style="width: 98%;" src="https://programmerblog.xyz/upload/2024/08/pdf%E8%BD%ACwod%E5%B7%A5%E5%85%B7.png"></image>
</view>
<view class="selectSection">
<text class="textmag">上傳方式:</text>
<radio-group bindchange="radioChange" class="radio-group">
<label class="radio" wx:for="{{direction}}" wx:key="i">
<icon class="radioIcon {{item.checked?'actIcon':''}}"></icon>
<radio checked="{{item.checked}}" value="{{item.name}}"></radio>{{item.value}}
</label>
</radio-group>
</view>
<view class="container">
<view wx:if="{{directionType==1}}" class="item"> <button style="width: 120px;" class="butss" bindtap="chooseFile">選擇pdf</button></view>
<view wx:if="{{directionType==2}}" class="item"> <button style="width: 120px;" class="butss" bindtap="chooseFileNew">生成文檔</button></view>
<view class="item"> <button style="width: 90px;" class="butss" bindtap="saveTap">下載</button></view>
<view class="item"> <button style="width: 90px;" class="butss" bindtap="clearTap">清空</button></view>
</view>
<view style="padding: 20px;">
<span style="color: red;font-size: 12px;">溫馨提示:pdf超過10頁,生成的是zip,每10頁一個word</span>
</view>
<view>
<textarea auto-height="true" bindinput="handleInput" class="input-content" value="{{uploadUrl}}" placeholder="請輸入pdf文件url" wx:if="{{directionType==2}}"></textarea>
</view>
<view class="instruction" style="padding: 20px;">
<!-- <text>上傳的pdf文件:{{pdfPath}}</text> -->
<span style="color: black;">結(jié)果文件:{{data}}</span>
</view>
js 主要代碼如下:
// 選擇文件上傳的方法
chooseFile: function () {
var that = this;
wx.showLoading({
title: 'Word文檔生成中,請稍后...',
});
wx.chooseMessageFile({
count: 1,
type: 'file',
extension: ['pdf'], // 限定選擇的文件格式為.pdf
success: function (res) {
const tempFilePath = res.tempFiles[0].path;
if (res.tempFiles[0].size > 10 * 1024 * 1024) { // 限定文件大小為10MB
wx.showToast({
title: '文件大小超過限制,請選擇小于10MB的文件',
icon: 'none'
});
return;
}
that.setData({
pdfPath: tempFilePath
})
console.log(tempFilePath);
wx.uploadFile({
url: '后端服務(wù)接口',
filePath: tempFilePath,
formData: {
'type': that.data.directionType
},
name: 'file',
success: function (res) {
if (res.statusCode == "200") {
console.log(res.data);
that.setData({
imageUrl: res.data,
data: res.data
});
// console.log('上傳成功', imageUrl);
wx.showToast({
title: '轉(zhuǎn)換成功',
icon: 'success',
duration: 2000
});
} else {
wx.showToast({
title: '轉(zhuǎn)換失敗,請聯(lián)系管理員',
icon: 'none',
duration: 2000
});
}
},
fail: function (res) {
wx.showToast({
title: '上傳失敗',
icon: 'none',
duration: 2000
});
}
});
},
fail: function (res) {
console.error('選擇文件失敗', res);
wx.showToast({
title: '選擇文件失敗',
icon: 'none',
duration: 2000
});
}
});
},
// 下載按鈕事件
saveTap: function () {
if (this.data.imageUrl) {
wx.downloadFile({
url: this.data.imageUrl,
success: function (res) {
if (res.statusCode === 200) {
var filePath = res.tempFilePath;
wx.openDocument({
filePath: filePath,
showMenu: true,
success: function (res) {
console.log('打開文檔成功')
},
fail: function (res) {
console.log('打開文檔失敗', res)
}
})
};
}
}, );
} else {
wx.showToast({
title: '請先上傳pdf文件,轉(zhuǎn)換成功后再下載',
icon: 'none',
duration: 2000
});
}
},
轉(zhuǎn)換成功后的效果如下圖:
如果需要體驗轉(zhuǎn)換效果的話可以搜索微信小程序【小明工作助手】小程序體驗!
微信小程序開發(fā)、測試完成后需要通過微信開發(fā)者工具把代碼上傳到云端。然后登錄微信小程序后臺。提交版本審核。版本審核通過后,發(fā)布你的小程序就可以正常使用了。
以上是完整的微信小程序PDF轉(zhuǎn)換為Word工具的完整流程,大家如果有什么疑問的話,歡迎評論區(qū)溝通交流!
本文轉(zhuǎn)載微信公眾號@小明互聯(lián)網(wǎng)技術(shù)分享社區(qū)