lxw
2022-05-31 5df14a8787b4b5f5c40548522de6d63116877175
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
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, "/");
    }
 
}