yanghb
2024-12-24 fe6e43d5e1144156d0ca4e9d6080c9821c25d97c
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
package com.zzg.common.utils;
 
import com.zzg.common.exception.GlobalException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import java.io.*;
 
/**
 * office文件转pdf工具类
 */
public class Office2PDFUtils {
    private static final Logger log = LoggerFactory.getLogger(Office2PDFUtils.class);
 
 
    /**
     * 将office文档转成pdf文件
     *
     * @param sourcePath
     * @param targetPath
     * @throws Exception
     */
    public static boolean word2pdf(String sourcePath, String targetPath) throws Exception {
        if (!new File(sourcePath).exists()) {
            throw new FileNotFoundException();
        }
        String command = String.format("soffice --convert-to pdf:writer_pdf_Export %s --outdir %s", sourcePath, targetPath);
        boolean flag = executeCommand(command);
        log.info("word2pdf: convert pdf complete. flag=" + flag);
        return flag;
    }
 
    /**
     * linux下命令方式 word转PDF
     *
     * @param sourcePath /root/landexp-file/temp/青白江区人民政府土地征收预公告模板.docx
     * @param targetPath /root/landexp-file/temp
     * @return
     * @throws Exception
     */
    public static boolean convert2Pdf(String sourcePath, String targetPath) throws Exception {
        if (!new File(sourcePath).exists()) {
            throw new FileNotFoundException();
        }
        String os = System.getProperty("os.name");
        String command;
        if (os.contains("Windows")) {
//            command = String.format("soffice --convert-to pdf:writer_pdf_Export %s --outdir %s", sourcePath, targetPath);
            command = "cmd /c start soffice --headless --invisible --convert-to pdf:writer_pdf_Export " + sourcePath + " --outdir " + targetPath;
        } else {
//            command="libreoffice --headless --invisible --convert-to pdf:writer_pdf_Export " + inputFile + " --outdir " + pdfFile;
            command = String.format("/opt/libreoffice7.6/program/soffice --headless --invisible --convert-to pdf %s --outdir %s", sourcePath, targetPath);
        }
        log.info("command:" + command);
        boolean flag = executeCommand(command);
//        boolean flag = execute(command);
        if (!flag) {
            throw new GlobalException("转换PDF失败!");
        }
        log.info("word2pdf: convert pdf complete. flag=" + flag);
        return flag;
    }
 
    /**
     * 执行libreoffice的转换命令
     *
     * @param command
     * @return
     */
    public static boolean executeCommand(String command) {
        try {
            long start = System.currentTimeMillis();
            Process process = Runtime.getRuntime().exec(command);
//            Process process = new ProcessBuilder(command).directory(new File("C:\\Program Files\\LibreOffice\\program")).start();
            // 返回值是子线程执行完毕的返回值,返回0表示正常结束
            int exitStatus = process.waitFor();
            log.info("executeCommand: convert pdf exitStatus= " + exitStatus);
 
            // 销毁子进程
            process.destroy();
            long end = System.currentTimeMillis();
            log.info("executeCommand: convert pdf cost time " + (end - start) + "ms");
            return exitStatus == 0;
        } catch (Exception e) {
            log.error("executeCommand: runtime exec error", e);
        }
        return false;
    }
 
    /**
     * 执行DOS命令
     *
     * @param command
     * @return
     */
    public static boolean execute(String command) {
        try {
            Process process = Runtime.getRuntime().exec(command, null, new File("C:\\Program Files\\LibreOffice\\program"));
 
            // 获取命令执行的输入流
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            // 等待命令执行完成
            int exitCode = process.waitFor();
            System.out.println("命令执行完成,退出码:" + exitCode);
            return exitCode == 0;
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }
 
    /**
     * linux下 word转PDF
     *
     * @param fromPath 初始文件的路径,例:C:\Users\...\Desktop\test\1.doc
     * @param toPath   转换后的存储路径,例:C:\Users\...\Desktop\test\
     * @param name     转换后的文件保存名字
     */
    public static void convert2Pdf(String fromPath, String toPath, String name) {
        /*File fromFile = new File(fromPath);
        if (!fromFile.exists()) {
            System.out.println("源文件不存在");
            return;
        }
        File toFile = new File(toPath + name + ".pdf");
 
        SocketOpenOfficeConnection connection = new SocketOpenOfficeConnection("192.168.163.236", 8100);
        // 注:8100是openoffice的服务端口,8101是libreoffice的服务端口
        try {
            connection.connect();
            System.out.println("获取连接成功!");
        } catch (ConnectException e) {
            System.out.println("获取连接失败!");
            e.printStackTrace();
            return;
        }
        StreamOpenOfficeDocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);
        System.out.println("开始转换!");
        converter.convert(fromFile, toFile);
        System.out.println("转换成功!");
        System.out.println("关闭连接!");
        connection.disconnect();*/
    }
 
    /**
     * word转PDF方法(仅限windows)
     *
     * @param sourcePath
     * @param targetPath
     * @return
     */
    /*public static boolean word2pdf2(String sourcePath, String targetPath) {
//        File inputWord = new File("D:/temp/青白江区人民政府土地征收预公告模板.docx");
//        File outputFile = new File("D:/temp/pdf/temp.pdf");
        File inputWord = new File(sourcePath);
        File outputFile = new File(targetPath);
        try {
            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();
            throw new GlobalException("WORD文档转换PDF失败!");
        }
        return true;
    }*/
 
}