微信小程序实现PDF转Word文档

效果查看

1.打开微信小程序项目,并创建toword模块

1.两个主要文件,toword.wxml与toword.js。toword.wxml文件内容


<view class="view_main">
<image class="image_type" src="{{imgPath}}" mode="aspectFit"></image>
<button class="button_type" bindtap="upFile">上传文件</button>

<view class="view_items">

<text selectable='true' class="text_main">转换状态:{{msg}}</text>
<text selectable='true' class="text_main">下载地址: {{relink}}</text>

</view>
<view class="view_main">
<view class="button_type" bindtap='copyText' data-text="{{relink}}">点击复制</view>

</view>

</view>



2.toword.js文件内容

// miniprogram/pages/fanyi/fanyi.js

const app = getApp()


/**
* WxParse.wxParse(bindName , type, data, target,imagePadding)
* 1.bindName绑定的数据名(必填)
* 2.type可以为html或者md(必填)
* 3.data为传入的具体数据(必填)
* 4.target为Page对象,一般为this(必填)
* 5.imagePadding为当图片自适应是左右的单一padding(默认为0,可选)
*/Page({
data: {
imgPath: '../../images/wenzi.jpg',
items: null,
},

/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var that = this;
},

upFile: function() {
var that = this;
wx.chooseMessageFile({

count: 1,
type: 'file',
success(res) {
const tempFilePaths = res.tempFiles
wx.uploadFile({

url: '你的后台上传请求地址',//后台服务器地址
filePath: tempFilePaths[0].path,
name: 'file',
success: res => {
console.log(res)

that.setData({
msg: JSON.parse(res.data)['msg'],
relink: JSON.parse(res.data)['relink']
})
console.log(that.data.msg),
console.log(that.data.relink)
},

fail(res) {
console.log("失败")
console.log(res)
}
})

}
})
},
copyText: function (e) {
console.log(e)
wx.setClipboardData({
data: e.currentTarget.dataset.text,
success: function (res) {
wx.getClipboardData({
success: function (res) {
wx.showToast({
title: '复制成功'
})
}
})
}
})
},

})

3.创建文件转换后台服务,文件上传代码

/**

* word文件上传

*

* @param file

* @return

* @throws IOException

*/

@PostMapping("/upload")

@ResponseBody

public Map<String, Object> WordTransform(@RequestParam("file") MultipartFile file) throws IOException {

Map<String, Object> result = new HashMap<>();

long Rtime = new Date().getTime();

if (file.isEmpty()) {

result.put("code", 500);

result.put("data", null);

result.put("msg", "该文件是空文件");

return result;

}

// 文件名称

String filename = file.getOriginalFilename();

String time = year + File.separator + month + File.separator + day + File.separator + Rtime + File.separator;

// 本地文件路径

String filePath = path + time;

File newFile1 = new File(filePath);

System.out.println(newFile1);

// 创建路径

newFile1.mkdirs();

deleteFile(filePath + filename);

// 在创建的路径下创建文件

File newFile = new File(filePath + filename);

// 创建生成的Word路径

String wordPath = filePath + filename;

// link路径

String link = yuming + WebServer + time + filename;

String relink = link.replaceAll(".pdf", ".docx");

try {

file.transferTo(newFile);

String pdftoword = new PdfToWord().pdftoword(wordPath);

System.out.println(yuming + WebServer + time + "/" + filename);

// String pdftoword = pdfService.pdftoword(wordPath);

System.out.println("装换结果" + pdftoword);

result.put("code", 200);

result.put("data", filePath + filename);

result.put("relink", relink);

result.put("msg", "转换成功,复制下载地址去浏览器地址栏打开进行下载");

return result;

} catch (IOException e) {

e.printStackTrace();

result.put("code", 500);

result.put("data", null);

result.put("msg", "IO异常");

return result;

}

}

4文件转换代码,核心

long Rtime = new Date().getTime();

// 涉及到的路径

// 1、pdf所在的路径,真实测试种是从外部引入的

// 2、如果是大文件,需要进行切分,保存的子pdf路径

String splitPath = "./split/" +Rtime+"/";

// 3、如果是大文件,需要对子pdf文件一个一个进行转化

String docPath = "./doc/" +Rtime+"/";

public String pdftoword(String srcPath) {

// 4、最终生成的doc所在的目录,默认是和引入的一个地方,开源时对外提供下载的接口。

String desPath = srcPath.substring(0, srcPath.length()-4)+".docx";

boolean result = false;

try {

// 0、判断输入的是否是pdf文件

//第一步:判断输入的是否合法

boolean flag = isPDFFile(srcPath);

//第二步:在输入的路径下新建文件夹

boolean flag1 = create();

if (flag && flag1) {

// 1、加载pdf

PdfDocument pdf = new PdfDocument();

pdf.loadFromFile(srcPath);

PdfPageCollection num = pdf.getPages();

// 2、如果pdf的页数小于11,那么直接进行转化

if (num.getCount() <= 10) {

pdf.saveToFile(desPath, com.spire.pdf.FileFormat.DOCX);

}

// 3、否则输入的页数比较多,就开始进行切分再转化

else {

// 第一步:将其进行切分,每页一张pdf

pdf.split(splitPath+"test{0}.pdf",0);

// 第二步:将切分的pdf,一个一个进行转换

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);

}

//第三步:对转化的doc文档进行合并,合并成一个大的word

try {

result = MergeWordDocument.merge(docPath, desPath);

System.out.println(result);

} catch (Exception e) {

e.printStackTrace();

}

}

} else {

System.out.println("输入的不是pdf文件");

return "输入的不是pdf文件";

}

} catch (Exception e) {

e.printStackTrace();

}finally {

//4、把刚刚缓存的split和doc删除

if(result==true) {

new FileDeleteTest().clearFiles(splitPath);

new FileDeleteTest().clearFiles(docPath);

}

}

return "转换成功";

}

private boolean create() {

File f = new File(splitPath);

File f1 = new File(docPath);

if(!f.exists() ) f.mkdirs();

if(!f.exists() ) f1.mkdirs();

return true;

}

// 判断是否是pdf文件

private boolean isPDFFile(String srcPath2) {

File file = new File(srcPath2);

String filename = file.getName();

if (filename.endsWith(".pdf")) {

return true;

}

return false;

}

// 取得某一路径下所有的pdf

private File[] getSplitFiles(String path) {

File f = new File(path);

File[] fs = f.listFiles();

if (fs == null) {

return null;

}

return fs;

}

合并返回

public static boolean merge(String docPath,String desPath){

File[] fs = getSplitFiles(docPath);

System.out.println(docPath);

Document document = new Document(docPath+"test0.docx");

for(int i=1;i<fs.length;i++) {

document.insertTextFromFile(docPath+"test"+i+".docx",FileFormat.Docx_2013);

}

//第四步:对合并的doc进行保存2

document.saveToFile(desPath);

return true;

}

// 取得某一路径下所有的pdf

private static File[] getSplitFiles(String path) {

File f = new File(path);

File[] fs = f.listFiles();

if (fs == null) {

return null;

}

return fs;

}

  • 1
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值