java中使用libreoffice將word轉換成pdf格式

1. 下載libreoffice
2. 配置path路徑,F:\Program Files\LibreOffice 5\program  之後cmd窗口執行soffice命令可以打開libreoffice軟件
3. 引依賴
<dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
</dependency>
4. 代碼

@RequestMapping("/openPDF")
    public void openPDF(HttpServletResponse response) {
        try {
            String targetPath = System.getProperty("java.io.tmpdir")+File.separator;
            String docxPath = "http://192.168.200.201:9093/M00/00/01/wKjIyVqQ34yAUO-uAAAtY6q46LU28.docx";
            wordConverterToPdf(docxPath, targetPath);
            String name = docxPath.substring(docxPath.lastIndexOf("/")+1);
            String[] nameArr = name.split("\\.");

            CommandExecute.findPdf(response,targetPath+nameArr[0]+".pdf");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
// 執行轉換的方法
public static boolean wordConverterToPdf(String docxPath,String targetPath) throws IOException {
        File file = new File(docxPath);
//        String path = file.getParent();
        try {
            String osName = System.getProperty("os.name");
            String command = "";
            if (osName.contains("Windows")) {
                command = "soffice --convert-to pdf  -outdir " + targetPath + " " + docxPath;
            } else {
                command = "doc2pdf --output=" + targetPath + File.separator + file.getName().replaceAll(".(?i)docx", ".pdf") + " " + docxPath;
            }
            String result = CommandExecute.executeCommand(command);
            if (result.equals("") || result.contains("writer_pdf_Export")) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return false;
    }
// CommandExecute類
import org.apache.commons.io.IOUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/**
 * linux或windows命令執行
 */
public class CommandExecute {
//    public static void main(String[] args) {
//        CommandExecute obj = new CommandExecute();
//        String domainName = "www.baidu.com";
//        //in mac oxs
//        String command = "ping " + domainName;
//        //in windows
//        //String command = "ping -n 3 " + domainName;
//        String output = obj.executeCommand(command);
//        System.out.println(output);
//    }
    public static String executeCommand(String command) {
        StringBuffer output = new StringBuffer();
        Process p;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        try {
            p = Runtime.getRuntime().exec(command);
            p.waitFor();
            inputStreamReader = new InputStreamReader(p.getInputStream(), "UTF-8");
            reader = new BufferedReader(inputStreamReader);
            String line = "";
            while ((line = reader.readLine()) != null) {
                output.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(reader);
            IOUtils.closeQuietly(inputStreamReader);
        }
        System.out.println(output.toString());
        return output.toString();
    }
    public static void findPdf(HttpServletResponse response, String targetPath) throws IOException {
        response.setContentType("application/pdf");
        response.setCharacterEncoding("utf-8");
        FileInputStream in = new FileInputStream(new File(targetPath));
        OutputStream out = response.getOutputStream();
        byte[] b = new byte[512];
        while ((in.read(b)) != -1) {
            out.write(b);
        }
        out.flush();
        in.close();
        out.close();
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章