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();
    }
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Java的FileInputStream和FileOutputStream类来读写文件,然后使用LibreOffice的API将文件换为PDF格式。以下是一个示例代码: ```java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import com.sun.star.beans.PropertyValue; import com.sun.star.frame.XComponentLoader; import com.sun.star.lang.XComponent; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XComponentContext; public class ConvertToPDF { public static void main(String[] args) { String inputFile = "input.docx"; String outputFile = "output.pdf"; convertToPDF(inputFile, outputFile); } public static void convertToPDF(String inputFile, String outputFile) { try { // initialize LibreOffice API XComponentContext xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); XComponentLoader xLoader = UnoRuntime.queryInterface(XComponentLoader.class, xContext.getServiceManager().createInstanceWithContext("com.sun.star.frame.Desktop", xContext)); // load input file String inputURL = new File(inputFile).toURI().toString(); PropertyValue[] propertyValues = new PropertyValue[0]; XComponent xComponent = xLoader.loadComponentFromURL(inputURL, "_blank", 0, propertyValues); // prepare output file String outputURL = new File(outputFile).toURI().toString(); PropertyValue[] convertProperties = new PropertyValue[2]; convertProperties[0] = new PropertyValue(); convertProperties[0].Name = "FilterName"; convertProperties[0].Value = "writer_pdf_Export"; convertProperties[1] = new PropertyValue(); convertProperties[1].Name = "Overwrite"; convertProperties[1].Value = true; // convert to PDF UnoRuntime.queryInterface(XComponent.class, xComponent).storeToURL(outputURL, convertProperties); // close input file xComponent.dispose(); // shutdown LibreOffice API com.sun.star.util.XCloseable xCloseable = UnoRuntime.queryInterface(com.sun.star.util.XCloseable.class, xLoader); xCloseable.close(false); System.exit(0); } catch (Exception e) { e.printStackTrace(); } } } ``` 在这个示例,我们打开一个Word文档,将其换为PDF格式,并将其保存到输出文件。你需要将input.docx替换为你要换的文件名,将output.pdf替换为你想要保存的PDF文件名。请注意,你需要将LibreOffice的JAR文件添加到项目的类路径
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值