使用openoffice转pdf,详细
期由于项目的需求,需要word文档转pdf在线预览,由于一直没有接触这块,所以花了将近四天时间才弄明白。
写这篇文章的主要目的是加深自己的记忆,同时方便以后在用。
(最近有使用了这个功能,发现这篇文章有很多问题,已修改,抱歉)
所需要的工具openoffice
在openoffice安装成功之后,需要在安装目录下porgram文件下打开cmd命令行输入
- 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
- <!-- 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>
<!-- 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页面)
- <%@ 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>
<%@ 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
//这个方法是跳转到jsp的方法
@RequestMapping("/othre")
public String otre(){ return "otre"; }
- //这个方法是上传的方法
- @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 "上传失败,因为文件是空的.";
- }
- }
//这个方法是上传的方法 @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的工具类,下面是工具类
- 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");
- }
- }
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