lxw
2022-05-31 5df14a8787b4b5f5c40548522de6d63116877175
world转pdf
2个文件已修改
2个文件已添加
297 ■■■■■ 已修改文件
pom.xml 15 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/whyc/controller/WorldToPdfController.java 208 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/whyc/util/UrlDownload.java 69 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/whyc/util/Word2PdfJacobUtil.java 5 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
pom.xml
@@ -166,6 +166,21 @@
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>
        <dependency>
            <groupId>com.documents4j</groupId>
            <artifactId>documents4j-local</artifactId>
            <version>1.0.3</version>
        </dependency>
        <dependency>
            <groupId>com.documents4j</groupId>
            <artifactId>documents4j-transformer-msoffice-word</artifactId>
            <version>1.0.3</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>28.0-jre</version>
        </dependency>
        <!--外部引入-->
        <dependency>
            <groupId>com.whyc</groupId>
src/main/java/com/whyc/controller/WorldToPdfController.java
New file
@@ -0,0 +1,208 @@
package com.whyc.controller;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import com.whyc.dto.Response;
import com.whyc.util.UrlDownload;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
@RestController
@Api(tags = "文件转换")
@RequestMapping("WorldToPdf")
public class WorldToPdfController {
    @Autowired
    private Environment env;
    @ApiOperation("world转pdf")
    @GetMapping(value = "wordTurnPdf")
    public Response wordTurnPdf(@RequestParam("url") String url, @RequestParam("fileName") String fileName) {
        try {
            url = URLDecoder.decode(url, "UTF-8");
            fileName = URLDecoder.decode(fileName, "UTF-8").split("\\.")[0];
            ;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
       /* String[] urlSplit = url.split("=");
        String urlStr = urlSplit[0].replace("&fileName","");
        String fileName = urlSplit[1].split("\\.")[0];*/
        ApplicationHome applicationHome = new ApplicationHome(getClass());
        File jarFile = applicationHome.getDir();
        String savePath = "";
        if (env.getProperty("configFile.type").equals("1")) {
            //开发路径
            savePath = jarFile.getParentFile().toString() + File.separator + "fg_photo" + File.separator + "zentao";
        } else {
            //打包路径
            savePath = jarFile.toString() + File.separator + "fg_photo" + File.separator + "zentao";
        }
        try {
            UrlDownload.downLoadFromUrl(url, fileName + ".doc", savePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            //截取文件前缀
            String caselsh = fileName;
            //需要转换的word文件
            File inputWord = new File(savePath + fileName + ".doc");
            //转换后生成的pdf文件
            File outputFile = new File(savePath + caselsh + ".pdf");
            InputStream docxInputStream = new FileInputStream(inputWord);
            OutputStream outputStream = new FileOutputStream(outputFile);
            IConverter converter = LocalConverter.builder().build();
            converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Response().set(1, fileName, "转化成功");
    }
    public static boolean downByFileLink(String urlString, String fileName) {
        boolean ret = false;
        File file = new File("D:\\" + fileName + ".doc");
        try {
            if (file.exists()) {
                file.delete();
            }
            // 构造URL
            URL url = new URL(urlString);
            // 打开连接
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.connect();
            int contentLength = con.getContentLength();
            // 输入流
            InputStream is = con.getInputStream();
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流
            File file2 = new File(file.getParent());
            file2.mkdirs();
            if (file.isDirectory()) {
            } else {
                file.createNewFile();//创建文件
            }
            OutputStream os = new FileOutputStream(file);
            // 开始读取
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            // 完毕,关闭所有链接
            os.close();
            is.close();
            if (contentLength != file.length()) {
                file.delete();
                ret = false;
            } else {
                ret = true;
            }
        } catch (IOException e) {
            file.delete();
            ret = false;
        } finally {
            return ret;
        }
    }
    /**
     * 从网络Url中下载文件
     *
     * @param url url的路径
     * @throws IOException
     */
    @GetMapping("downLoadByUrl")
    @ApiOperation("从网络Url中下载文件")
    public Map<String, Object> downLoadByUrl(@RequestParam String url) {
        String[] urlSplit = url.split("=");
        String urlStr = urlSplit[0].replace("&fileName", "");
        String fileName = urlSplit[1].split("\\.")[0];
        ApplicationHome applicationHome = new ApplicationHome(getClass());
        File jarFile = applicationHome.getDir();
        String savePath = "";
        if (env.getProperty("configFile.type").equals("1")) {
            //开发路径
            savePath = jarFile.getParentFile().toString() + File.separator + "wordTurnPdf" + File.separator;
        } else {
            //打包路径
            savePath = jarFile.toString() + File.separator + "wordTurnPdf" + File.separator;
        }
        Map<String, Object> map = new HashMap<>();
        try {
            fileName = fileName + ".doc";
            URL urlhttp = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) urlhttp.openConnection();
            //设置超时间为5秒
            conn.setConnectTimeout(5 * 1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            //得到输入流
            InputStream inputStream = conn.getInputStream();
            //获取自己数组
            byte[] getData = readInputStream(inputStream);
            //文件保存位置
            File saveDir = new File(savePath);
            if (!saveDir.exists()) { // 没有就创建该文件
                saveDir.mkdir();
            }
            File file = new File(saveDir + File.separator + fileName);
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(getData);
            fos.close();
            inputStream.close();
            map.put("msg", "success");
            map.put("data", savePath + file.getName() + ".pdf");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "error");
        }
        return map;
    }
    /**
     * 从输入流中获取字节数组
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    private static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[4 * 1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }
    private static String getFileName(String srcRealPath) {
        return StringUtils.substringAfterLast(srcRealPath, "/");
    }
}
src/main/java/com/whyc/util/UrlDownload.java
New file
@@ -0,0 +1,69 @@
package com.whyc.util;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
/**
 * zzx
 */
public class UrlDownload {
    /**
     * 从网络Url中下载文件
     *
     * @param urlStr
     * @param fileName
     * @param savePath
     * @throws IOException
     */
    public static void downLoadFromUrl(String urlStr, String fileName, String savePath) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(3 * 1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        conn.setRequestProperty("lfwywxqyh_token", "v32Eo2Tw+qWI/eiKW3D8ye7l19mf1NngRLushO6CumLMHIO1aryun0/Y3N3YQCv/TqzaO/TFHw4=");
        //得到输入流
        InputStream inputStream = conn.getInputStream();
        //获取自己数组
        byte[] getData = readInputStream(inputStream);
        //文件保存位置
        File saveDir = new File(savePath);
        if (!saveDir.exists()) {
            saveDir.mkdir();
        }
        File file = new File(saveDir + File.separator + fileName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getData);
        if (fos != null) {
            fos.close();
        }
        if (inputStream != null) {
            inputStream.close();
        }
    }
    /**
     * 从输入流中获取字节数组
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }
}
src/main/java/com/whyc/util/Word2PdfJacobUtil.java
@@ -47,8 +47,9 @@
        } finally {
            Dispatch.call(doc, "Close", false);
            System.out.println("关闭文档");
            if (app != null)
                app.invoke("Quit", new Variant[] {});
            if (app != null) {
                app.invoke("Quit", new Variant[]{});
            }
            // 如果没有这句话,winword.exe进程将不会关闭
            ComThread.Release();
            ComThread.quitMainSTA();