zoukankan      html  css  js  c++  java
  • 使用openoffice转pdf,详细

    期由于项目的需求,需要word文档转pdf在线预览,由于一直没有接触这块,所以花了将近四天时间才弄明白。

     写这篇文章的主要目的是加深自己的记忆,同时方便以后在用。

    (最近有使用了这个功能,发现这篇文章有很多问题,已修改,抱歉)

     所需要的工具openoffice

    http://www.openoffice.org/

    在openoffice安装成功之后,需要在安装目录下porgram文件下打开cmd命令行输入

    1. soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard  
    soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard

    这时会启动两个openoffice的进程,打开任务管理器就可以看见。

    需要的java包 JodConverter 下载地址  http://sourceforge.net/projects/jodconverter/files/JODConverter/

    pom.xml 

    1. <!-- https://mvnrepository.com/artifact/com.artofsolving/jodconverter-maven-plugin -->  
    2. <dependency>  
    3.     <groupId>com.artofsolving</groupId>  
    4.     <artifactId>jodconverter-maven-plugin</artifactId>  
    5.     <version>2.2.1</version></dependency>  
    <!-- https://mvnrepository.com/artifact/com.artofsolving/jodconverter-maven-plugin -->
    <dependency>
        <groupId>com.artofsolving</groupId>
        <artifactId>jodconverter-maven-plugin</artifactId>
        <version>2.2.1</version></dependency>

    在这里需要详细讲解一下openoffice的安装,最好是默认安装路径

    安装完之后就开始干正事了。、

    首先我们要先写一个上传页面(名字随意,我写的是jsp页面)

    1. <%@ page language="java" contentType="text/html; charset=utf-8"  
    2.     pageEncoding="utf-8"%>  
    3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
    4. <html>  
    5. <head>  
    6. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">  
    7. <title>Insert title here</title>  
    8. <link rel="stylesheet" href="/js/bootstrap/css/bootstrap.css">  
    9.     <link rel="stylesheet" href="/js/bootstrap/css/bootstrap-theme.css">  
    10.     <script src="/js/bootstrap/js/jquery.js"></script>  
    11.     <script src="/js/bootstrap/js/bootstrap.js"></script>  
    12.     <style>  
    13.         .fileinput-button {  
    14.             position: relative;  
    15.             display: inline-block;  
    16.             overflow: hidden;  
    17.         }  
    18.         .fileinput-button input{  
    19.             position:absolute;  
    20.             right: 0px;  
    21.             top: 0px;  
    22.             opacity: 0;  
    23.             -ms-filter: 'alpha(opacity=0)';  
    24.             font-size: 200px;  
    25.         }  
    26.     </style>  
    27. </head>  
    28. <body style="padding: 10px">  
    29. <form action="/upload" method="post" enctype="multipart/form-data">  
    30. <div align="center">  
    31.     <div class="btn btn-success"><table><tr><td width="20%">上传文件</td></tr></table></div>  
    32.         <span  class="btn fileinput-button">  
    33.             <img src="/img/up55.png" width="40" height="40">  
    34.             <input type="file" name = "file" accept="application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">  
    35.         </span>  
    36.         <input type="submit" value="上传"  />  
    37.     </div>  
    38.     </form>  
    39.    <img alt="" src="${msg }">  
    40. </body>  
    41. </html>  
    <%@ page language="java" contentType="text/html; charset=utf-8"
        pageEncoding="utf-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Insert title here</title>
    <link rel="stylesheet" href="/js/bootstrap/css/bootstrap.css">
        <link rel="stylesheet" href="/js/bootstrap/css/bootstrap-theme.css">
        <script src="/js/bootstrap/js/jquery.js"></script>
        <script src="/js/bootstrap/js/bootstrap.js"></script>
        <style>
            .fileinput-button {
                position: relative;
                display: inline-block;
                overflow: hidden;
            }
            .fileinput-button input{
                position:absolute;
                right: 0px;
                top: 0px;
                opacity: 0;
                -ms-filter: 'alpha(opacity=0)';
                font-size: 200px;
            }
        </style>
    </head>
    <body style="padding: 10px">
    <form action="/upload" method="post" enctype="multipart/form-data">
    <div align="center">
    	<div class="btn btn-success"><table><tr><td width="20%">上传文件</td></tr></table></div>
            <span  class="btn fileinput-button">
                <img src="/img/up55.png" width="40" height="40">
                <input type="file" name = "file" accept="application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">
            </span>
            <input type="submit" value="上传"  />
        </div>
        </form>
       <img alt="" src="${msg }">
    </body>
    </html>

    在这里面我是加了bootstar,bootstar可以自行在百度下载。

    在其up55说我在网上下载的上传图标,为了页面好看点

    再接下来是controller

    1.   
    
    

    //这个方法是跳转到jsp的方法

    @RequestMapping("/othre")

    public String otre(){ return "otre"; }

    1. //这个方法是上传的方法  
    2.     @RequestMapping(value = "/upload", method = RequestMethod.POST)    
    3.     @ResponseBody    
    4.     public String upload(@RequestParam("file") MultipartFile file) throws IOException {    
    5.         if (!file.isEmpty()) {    
    6.             try {    
    7.                 // 这里只是简单例子,文件直接输出到项目路径下。    
    8.                 // 实际项目中,文件需要输出到指定位置,需要在增加代码处理。    
    9.                     
    10.            
    11.                 BufferedOutputStream out = new BufferedOutputStream(    
    12.                         new FileOutputStream("d:/pdf/"+file.getOriginalFilename()));    
    13.                 System.out.println(file.getOriginalFilename());    
    14.                 out.write(file.getBytes());    
    15.                 out.flush();    
    16.                 out.close();    
    17.             } catch (FileNotFoundException e) {    
    18.                 e.printStackTrace();    
    19.                 return "上传失败," + e.getMessage();    
    20.             } catch (IOException e) {    
    21.                 e.printStackTrace();    
    22.                 return "上传失败," + e.getMessage();    
    23.             }    
    24.   
    25.   //调用Doc2HtmlUtil工具类    
    26.             Doc2HtmlUtil coc2HtmlUtil = Doc2HtmlUtil.getDoc2HtmlUtilInstance();  
    27.             File file1 = null;    
    28.             FileInputStream fileInputStream = null;    
    29.             //这里写的是被转文件的路径    
    30.             file1 = new File("d:/pdf/"+file.getOriginalFilename());   
    31.   
    32.             fileInputStream = new FileInputStream(file1);    
    33.   
    34. //为了后期方便,这里直接把文件名进行了截取,方便后续操作    
    35.             int i = file.getOriginalFilename().lastIndexOf(".");    
    36.             String substring = file.getOriginalFilename().substring(i);  
    37.             //上述的所有路径以及以下路劲均可自定义  
    38.             coc2HtmlUtil.file2pdf(fileInputStream, "d:/ss",substring);    
    39.             Doc2HtmlUtil doc = new Doc2HtmlUtil();    
    40.                 
    41.                 
    42.             return "上传成功";    
    43.                 
    44.                 
    45.         } else {    
    46.             return "上传失败,因为文件是空的.";    
    47.         }    
    48.     }  
    //这个方法是上传的方法
    	@RequestMapping(value = "/upload", method = RequestMethod.POST)  
        @ResponseBody  
        public String upload(@RequestParam("file") MultipartFile file) throws IOException {  
            if (!file.isEmpty()) {  
                try {  
                    // 这里只是简单例子,文件直接输出到项目路径下。  
                    // 实际项目中,文件需要输出到指定位置,需要在增加代码处理。  
                      
             
                    BufferedOutputStream out = new BufferedOutputStream(  
                            new FileOutputStream("d:/pdf/"+file.getOriginalFilename()));  
                    System.out.println(file.getOriginalFilename());  
                    out.write(file.getBytes());  
                    out.flush();  
                    out.close();  
                } catch (FileNotFoundException e) {  
                    e.printStackTrace();  
                    return "上传失败," + e.getMessage();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                    return "上传失败," + e.getMessage();  
                }  
    
      //调用Doc2HtmlUtil工具类  
                Doc2HtmlUtil coc2HtmlUtil = Doc2HtmlUtil.getDoc2HtmlUtilInstance();
                File file1 = null;  
                FileInputStream fileInputStream = null;  
                //这里写的是被转文件的路径  
                file1 = new File("d:/pdf/"+file.getOriginalFilename()); 
    
                fileInputStream = new FileInputStream(file1);  
    
    //为了后期方便,这里直接把文件名进行了截取,方便后续操作  
                int i = file.getOriginalFilename().lastIndexOf(".");  
                String substring = file.getOriginalFilename().substring(i);
                //上述的所有路径以及以下路劲均可自定义
                coc2HtmlUtil.file2pdf(fileInputStream, "d:/ss",substring);  
                Doc2HtmlUtil doc = new Doc2HtmlUtil();  
                  
                  
                return "上传成功";  
                  
                  
            } else {  
                return "上传失败,因为文件是空的.";  
            }  
        }

    Controller中调用了word转PdF的工具类,下面是工具类

    1. import java.io.File;  
    2. import java.io.FileInputStream;  
    3. import java.io.FileOutputStream;  
    4. import java.io.IOException;  
    5. import java.io.InputStream;  
    6. import java.io.OutputStream;  
    7. import java.net.ConnectException;  
    8. import java.text.SimpleDateFormat;  
    9. import java.util.Date;  
    10.   
    11. import com.artofsolving.jodconverter.DocumentConverter;  
    12. import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;  
    13. import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;  
    14. import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;  
    15. /** 
    16.  * 利用jodconverter(基于OpenOffice服务)将文件(*.doc、*.docx、*.xls、*.ppt)转化为html格式或者pdf格式, 
    17.  * 使用前请检查OpenOffice服务是否已经开启, OpenOffice进程名称:soffice.exe | soffice.bin 
    18.  *  
    19.  * @author yjclsx 
    20.  */  
    21. /** 
    22.  * 利用jodconverter(基于OpenOffice服务)将文件(*.doc、*.docx、*.xls、*.ppt)转化为html格式或者pdf格式, 
    23.  * 使用前请检查OpenOffice服务是否已经开启, OpenOffice进程名称:soffice.exe | soffice.bin 
    24.  *  
    25.  * @author yjclsx 
    26.  */  
    27. public class Doc2HtmlUtil {  
    28.   
    29.     private static Doc2HtmlUtil doc2HtmlUtil;  
    30.   
    31.     /** 
    32.      * 获取Doc2HtmlUtil实例 
    33.      */  
    34.     public static synchronized Doc2HtmlUtil getDoc2HtmlUtilInstance() {  
    35.         if (doc2HtmlUtil == null) {  
    36.             doc2HtmlUtil = new Doc2HtmlUtil();  
    37.         }  
    38.         return doc2HtmlUtil;  
    39.     }  
    40.     /** 
    41.      * 转换文件成pdf 
    42.      *  
    43.      * @param fromFileInputStream: 
    44.      * @throws IOException  
    45.      */  
    46.     public String file2pdf(InputStream fromFileInputStream, String toFilePath,String type) throws IOException {  
    47.         Date date = new Date();  
    48.         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");  
    49.         String timesuffix = sdf.format(date);  
    50.         String docFileName = null;  
    51.         String htmFileName = null;  
    52.         if(".doc".equals(type)){  
    53.             docFileName = "doc_" + timesuffix + ".doc";  
    54.             htmFileName = "doc_" + timesuffix + ".pdf";  
    55.         }else if(".docx".equals(type)){  
    56.             docFileName = "docx_" + timesuffix + ".docx";  
    57.             htmFileName = "docx_" + timesuffix + ".pdf";  
    58.         }else if(".xls".equals(type)){  
    59.             docFileName = "xls_" + timesuffix + ".xls";  
    60.             htmFileName = "xls_" + timesuffix + ".pdf";  
    61.         }else if(".ppt".equals(type)){  
    62.             docFileName = "ppt_" + timesuffix + ".ppt";  
    63.             htmFileName = "ppt_" + timesuffix + ".pdf";  
    64.         }else{  
    65.             return null;  
    66.         }  
    67.   
    68.         File htmlOutputFile = new File(toFilePath + File.separatorChar + htmFileName);  
    69.         File docInputFile = new File(toFilePath + File.separatorChar + docFileName);  
    70.         if (htmlOutputFile.exists())  
    71.             htmlOutputFile.delete();  
    72.         htmlOutputFile.createNewFile();  
    73.         if (docInputFile.exists())  
    74.             docInputFile.delete();  
    75.         docInputFile.createNewFile();  
    76.         /** 
    77.          * 由fromFileInputStream构建输入文件 
    78.          */  
    79.         try {  
    80.             OutputStream os = new FileOutputStream(docInputFile);  
    81.             int bytesRead = 0;  
    82.             byte[] buffer = new byte[1024 * 8];  
    83.             while ((bytesRead = fromFileInputStream.read(buffer)) != -1) {  
    84.                 os.write(buffer, 0, bytesRead);  
    85.             }  
    86.   
    87.             os.close();  
    88.             fromFileInputStream.close();  
    89.         } catch (IOException e) {  
    90.         }  
    91.   
    92.         OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);  
    93.         try {  
    94.             connection.connect();  
    95.         } catch (ConnectException e) {  
    96.             System.err.println("文件转换出错,请检查OpenOffice服务是否启动。");  
    97.         }  
    98.         // convert  
    99.         DocumentConverter converter = new OpenOfficeDocumentConverter(connection);  
    100.         converter.convert(docInputFile, htmlOutputFile);  
    101.         connection.disconnect();  
    102.         // 转换完之后删除word文件  
    103.         docInputFile.delete();                                                                  
    104.         return htmFileName;  
    105.     }  
    106.   
    107.     public static void main(String[] args) throws IOException {  
    108.         Doc2HtmlUtil coc2HtmlUtil = getDoc2HtmlUtilInstance ();  
    109.         File file = null;  
    110.         FileInputStream fileInputStream = null;  
    111.           
    112.         file = new File("C:/Users/MACHENIKE/Desktop/xxx.doc");  
    113.         fileInputStream = new FileInputStream(file);  
    114.   
    115.         coc2HtmlUtil.file2pdf(fileInputStream, "E:/360","doc");  
    116.   
    117.     }  
    118.   
    119. }  
     
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.ConnectException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import com.artofsolving.jodconverter.DocumentConverter;
    import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
    import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
    import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
    /**
     * 利用jodconverter(基于OpenOffice服务)将文件(*.doc、*.docx、*.xls、*.ppt)转化为html格式或者pdf格式,
     * 使用前请检查OpenOffice服务是否已经开启, OpenOffice进程名称:soffice.exe | soffice.bin
     * 
     * @author yjclsx
     */
    /**
     * 利用jodconverter(基于OpenOffice服务)将文件(*.doc、*.docx、*.xls、*.ppt)转化为html格式或者pdf格式,
     * 使用前请检查OpenOffice服务是否已经开启, OpenOffice进程名称:soffice.exe | soffice.bin
     * 
     * @author yjclsx
     */
    public class Doc2HtmlUtil {
    
        private static Doc2HtmlUtil doc2HtmlUtil;
    
        /**
         * 获取Doc2HtmlUtil实例
         */
        public static synchronized Doc2HtmlUtil getDoc2HtmlUtilInstance() {
            if (doc2HtmlUtil == null) {
                doc2HtmlUtil = new Doc2HtmlUtil();
            }
            return doc2HtmlUtil;
        }
        /**
         * 转换文件成pdf
         * 
         * @param fromFileInputStream:
         * @throws IOException 
         */
        public String file2pdf(InputStream fromFileInputStream, String toFilePath,String type) throws IOException {
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String timesuffix = sdf.format(date);
            String docFileName = null;
            String htmFileName = null;
            if(".doc".equals(type)){
                docFileName = "doc_" + timesuffix + ".doc";
                htmFileName = "doc_" + timesuffix + ".pdf";
            }else if(".docx".equals(type)){
                docFileName = "docx_" + timesuffix + ".docx";
                htmFileName = "docx_" + timesuffix + ".pdf";
            }else if(".xls".equals(type)){
                docFileName = "xls_" + timesuffix + ".xls";
                htmFileName = "xls_" + timesuffix + ".pdf";
            }else if(".ppt".equals(type)){
                docFileName = "ppt_" + timesuffix + ".ppt";
                htmFileName = "ppt_" + timesuffix + ".pdf";
            }else{
                return null;
            }
    
            File htmlOutputFile = new File(toFilePath + File.separatorChar + htmFileName);
            File docInputFile = new File(toFilePath + File.separatorChar + docFileName);
            if (htmlOutputFile.exists())
                htmlOutputFile.delete();
            htmlOutputFile.createNewFile();
            if (docInputFile.exists())
                docInputFile.delete();
            docInputFile.createNewFile();
            /**
             * 由fromFileInputStream构建输入文件
             */
            try {
                OutputStream os = new FileOutputStream(docInputFile);
                int bytesRead = 0;
                byte[] buffer = new byte[1024 * 8];
                while ((bytesRead = fromFileInputStream.read(buffer)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
    
                os.close();
                fromFileInputStream.close();
            } catch (IOException e) {
            }
    
            OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
            try {
                connection.connect();
            } catch (ConnectException e) {
                System.err.println("文件转换出错,请检查OpenOffice服务是否启动。");
            }
            // convert
            DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
            converter.convert(docInputFile, htmlOutputFile);
            connection.disconnect();
            // 转换完之后删除word文件
            docInputFile.delete();                                                                
            return htmFileName;
        }
    
        public static void main(String[] args) throws IOException {
            Doc2HtmlUtil coc2HtmlUtil = getDoc2HtmlUtilInstance ();
            File file = null;
            FileInputStream fileInputStream = null;
            
            file = new File("C:/Users/MACHENIKE/Desktop/xxx.doc");
            fileInputStream = new FileInputStream(file);
    
            coc2HtmlUtil.file2pdf(fileInputStream, "E:/360","doc");
    
        }
    
    }

    修改过后的代码已经可以转化pdf了,如果有什么问题可以在下方留言,我会及时回复,感谢大家的支持。
    本文转自:https://blog.csdn.net/weixin_41623274/article/details/79044422

  • 相关阅读:
    刚子扯谈 活着 没那么简单
    改写整数
    刚子扯谈:一起聊聊微信这孙子
    刚子扯谈:未完待续的微信5.0
    Citrix 服务器虚拟化之十 Xenserver高可用性HA
    JS实现——俄罗斯方块
    一种文件捆绑型病毒研究
    XP系统登录界面,需要手动点击用户帐户后才会出现输入密码的界面
    加密javascript代码
    Python的在线编辑环境
  • 原文地址:https://www.cnblogs.com/honey01/p/8821704.html
Copyright © 2011-2022 走看看