利用腾讯云轻量应用服务器构建后端API,轻松打造PDF转Word的小程序工具

大家日常工作当中有时候需要把Excel转换为pdf打印或者转换为图片进行分享,目前有许多在线工具,不过大部分都是需要看激励广告或者收费才可以正常使用,今天给大家分享通过微信小程序自己搭建一个Excel转换工具,随时随地使用免受付费或者看广告的困扰,感兴趣的朋友可以一起来了解一下!

一、完整的开发部署流程

● 开发后端PDF转换为Word接口服务

● 购买云服务器

● 申请域名、SSL证书、部署后端接口服务到云服务器并配置SSL证书

● 微信小程序端界面开发

● 微信小程序部署上线

二、后端PDF转换接口服务开发

后端接口这里选择Java编程语法和SpingBoot快速搭建API接口,实现PDF转换为Word的功能。首先我们打开IDEA创建SpringBoot 接口项目

2.1 引入依赖包

在pom.xml文件引入pdf依赖包,具体内容如下

<dependency>
	<groupId>e-iceblue</groupId>
	<artifactId>spire.pdf.free</artifactId>
	<version>2.6.3</version>
	<scope>provided</scope>
</dependency>

注意:为了保证Maven可以正常联网拉取到依赖库需要在pom.xml 增加官方仓储库如下内容

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <url>http://repo.e-iceblue.cn/repository/maven-public/</url>
    </repository>
</repositories>

2.2 编写PDF转换为工具类

后端接口采用小程序上传文件的方式传递到后端接口实现转换。

新建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 { 


 /**
     * 根据文件流转换为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; // 构造文件名
        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的页数小于11,那么直接进行转化
                if (num.getCount() <= 10) {
                    pdf.saveToFile(desPath, com.spire.pdf.FileFormat.DOCX);
                }
                // 3、否则输入的页数比较多,就开始进行切分再转化
                else {

                    //saveInputStreamToFile(stream, pathPath);
                    // 第一步:将其进行切分,每页一张pdf
                    //pdf.split(splitPath+"test{0}.pdf",0);
                    splitPDF(pathPath, splitPath, 10);
                    clearFiles(pathPath, formattedDate);
                    // 第二步:将切分的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);
                    }
                    //授权问题转换为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自动关闭流
        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) {
                // 创建新的PDDocument对象
                PDDocument newDocument = new PDDocument();

                // 每指定页数为一个文件
                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;
            }

            // 关闭原始的PDF文档
            document.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

代码思路控制器接收到文件转换为InputStream然后把文件保存服务调用PDF转换类库进行转换为Word。最后删除客户上传源文件就行了

说明考虑PDF框架免费版目前只支持转换10这里考虑先把PDF按照10进行拆分然后循环转换为Word最后再把转换的多个word打包一个压缩包里面当然也可以转换后多个word合并这个大家可以自己去研究一下

2.3 新建控制器 PdfToFileApi.java

新建控制器用来提供接口服务,供微信小程序端转换服务调用,主要代码如下:


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 转换 API
 */
@RestController
@RequestMapping("PDF")
public class PDFToFileApi { 
   /**
     * pdf 转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);
        // 返回响应实体
        return image;
    }
}

说明该方法首先校验文件格式是否pdf格式正确后才可以正常调用

三、购买服务器

因为最终需要部署微信小程序所以云服务器必须购买当然如果大家本身已经云服务器可以跳过这个过程

我这边使用的是腾讯云提供的2核2G轻量级服务器,目前接口运行还是非常稳定的。如果大家需要搭建推荐使用腾讯云轻量级服务器

大家可以参加腾讯云双十一拼团活动,购买服务器优惠力度非常大,首单购买轻量级云服务器配置为2核2G3M带宽一年仅需要68元,并且加赠三个月。作为部署转换服务接口来说如果并发量不大的情况下是完全够用的。月底活动结束,距离活动结束还有一周左右时间有需要可以抓取最后福利

专属链接

四、申请域名、SSL证书、部署后端接口服务到云服务器并配置SSL证书

建议选择购买 CentOS 版本的操作系统,并在其上安装 JDK 及正确配置环境变量。关于 JDK 的具体安装步骤,网络上已有丰富的教程可供参考。安装完成后,将后端服务的 Jar 包上传至服务器,并通过命令行以后台模式启动服务。大家如果有问题欢迎沟通交流

如果你已经有域名并且有SSL证书,本步骤可以跳过。因为微信小程序调用接口需要HTTPS的域名进行调用。所以该步骤是微信小程序上线必备的操作。

大家可以登录腾讯云官网购买域名核的SSL证书的申请.

注意目前免费的SSL证书有效期是三个月,大家注意及时更换

证书申请可以安装nginx配置证书首先需要把申请通过的SSL证书上传到服务器指定的文件夹,然后直接在nginx.conf文件里面配置即可。因为过程比较简单大家可以自行配置

微信小程序端界面开发

首先看下界面的效果

界面主要包括上传方式选择、转换类型、按钮、结果文件展示。首先是选择PDF文件上传后会自动调用后端接口实现文件转换,转换成功后结果文件会体现转换成功后的文件名称。然后点击下载可以下载转换后的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;">结果文件:{{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: '后端服务接口',
                    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: '转换成功',
                                icon: 'success',
                                duration: 2000
                            });
                        } else {
                            wx.showToast({
                                title: '转换失败,请联系管理员',
                                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文件,转换成功后再下载',
                icon: 'none',
                duration: 2000
            });
        }
    },

转换成功后的效果如下图:

如果需要体验转换效果的话可以搜索微信小程序【小明工作助手】小程序体验!

、微信小程序部署上线

微信小程序开发测试完成后需要通过微信开发者工具把代码上传到云端。

然后登录微信小程序后台。提交版本审核。版本审核通过后,发布你的小程序就可以正常使用了。

、总结

以上是完整的微信小程序PDF转换为Word工具的完整流程,大家如果有什么疑问的话,欢迎评论区沟通交流!

利用腾讯云轻量应用服务器构建后端API,轻松打造PDF转Word的小程序工具-腾讯云开发者社区-腾讯云

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT技术分享社区

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值