期由于项目的需求,需要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


//这个方法是跳转到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. BufferedOutputStream out = new BufferedOutputStream(
  10. new FileOutputStream("d:/pdf/"+file.getOriginalFilename()));
  11. System.out.println(file.getOriginalFilename());
  12. out.write(file.getBytes());
  13. out.flush();
  14. out.close();
  15. } catch (FileNotFoundException e) {
  16. e.printStackTrace();
  17. return "上传失败," + e.getMessage();
  18. } catch (IOException e) {
  19. e.printStackTrace();
  20. return "上传失败," + e.getMessage();
  21. }
  22. //调用Doc2HtmlUtil工具类
  23. Doc2HtmlUtil coc2HtmlUtil = Doc2HtmlUtil.getDoc2HtmlUtilInstance();
  24. File file1 = null;
  25. FileInputStream fileInputStream = null;
  26. //这里写的是被转文件的路径
  27. file1 = new File("d:/pdf/"+file.getOriginalFilename());
  28. fileInputStream = new FileInputStream(file1);
  29. //为了后期方便,这里直接把文件名进行了截取,方便后续操作
  30. int i = file.getOriginalFilename().lastIndexOf(".");
  31. String substring = file.getOriginalFilename().substring(i);
  32. //上述的所有路径以及以下路劲均可自定义
  33. coc2HtmlUtil.file2pdf(fileInputStream, "d:/ss",substring);
  34. Doc2HtmlUtil doc = new Doc2HtmlUtil();
  35. return "上传成功";
  36. } else {
  37. return "上传失败,因为文件是空的.";
  38. }
  39. }
//这个方法是上传的方法
@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. import com.artofsolving.jodconverter.DocumentConverter;
  11. import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
  12. import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
  13. import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
  14. /**
  15. * 利用jodconverter(基于OpenOffice服务)将文件(*.doc、*.docx、*.xls、*.ppt)转化为html格式或者pdf格式,
  16. * 使用前请检查OpenOffice服务是否已经开启, OpenOffice进程名称:soffice.exe | soffice.bin
  17. *
  18. * @author yjclsx
  19. */
  20. /**
  21. * 利用jodconverter(基于OpenOffice服务)将文件(*.doc、*.docx、*.xls、*.ppt)转化为html格式或者pdf格式,
  22. * 使用前请检查OpenOffice服务是否已经开启, OpenOffice进程名称:soffice.exe | soffice.bin
  23. *
  24. * @author yjclsx
  25. */
  26. public class Doc2HtmlUtil {
  27. private static Doc2HtmlUtil doc2HtmlUtil;
  28. /**
  29. * 获取Doc2HtmlUtil实例
  30. */
  31. public static synchronized Doc2HtmlUtil getDoc2HtmlUtilInstance() {
  32. if (doc2HtmlUtil == null) {
  33. doc2HtmlUtil = new Doc2HtmlUtil();
  34. }
  35. return doc2HtmlUtil;
  36. }
  37. /**
  38. * 转换文件成pdf
  39. *
  40. * @param fromFileInputStream:
  41. * @throws IOException
  42. */
  43. public String file2pdf(InputStream fromFileInputStream, String toFilePath,String type) throws IOException {
  44. Date date = new Date();
  45. SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
  46. String timesuffix = sdf.format(date);
  47. String docFileName = null;
  48. String htmFileName = null;
  49. if(".doc".equals(type)){
  50. docFileName = "doc_" + timesuffix + ".doc";
  51. htmFileName = "doc_" + timesuffix + ".pdf";
  52. }else if(".docx".equals(type)){
  53. docFileName = "docx_" + timesuffix + ".docx";
  54. htmFileName = "docx_" + timesuffix + ".pdf";
  55. }else if(".xls".equals(type)){
  56. docFileName = "xls_" + timesuffix + ".xls";
  57. htmFileName = "xls_" + timesuffix + ".pdf";
  58. }else if(".ppt".equals(type)){
  59. docFileName = "ppt_" + timesuffix + ".ppt";
  60. htmFileName = "ppt_" + timesuffix + ".pdf";
  61. }else{
  62. return null;
  63. }
  64. File htmlOutputFile = new File(toFilePath + File.separatorChar + htmFileName);
  65. File docInputFile = new File(toFilePath + File.separatorChar + docFileName);
  66. if (htmlOutputFile.exists())
  67. htmlOutputFile.delete();
  68. htmlOutputFile.createNewFile();
  69. if (docInputFile.exists())
  70. docInputFile.delete();
  71. docInputFile.createNewFile();
  72. /**
  73. * 由fromFileInputStream构建输入文件
  74. */
  75. try {
  76. OutputStream os = new FileOutputStream(docInputFile);
  77. int bytesRead = 0;
  78. byte[] buffer = new byte[1024 * 8];
  79. while ((bytesRead = fromFileInputStream.read(buffer)) != -1) {
  80. os.write(buffer, 0, bytesRead);
  81. }
  82. os.close();
  83. fromFileInputStream.close();
  84. } catch (IOException e) {
  85. }
  86. OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
  87. try {
  88. connection.connect();
  89. } catch (ConnectException e) {
  90. System.err.println("文件转换出错,请检查OpenOffice服务是否启动。");
  91. }
  92. // convert
  93. DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
  94. converter.convert(docInputFile, htmlOutputFile);
  95. connection.disconnect();
  96. // 转换完之后删除word文件
  97. docInputFile.delete();
  98. return htmFileName;
  99. }
  100. public static void main(String[] args) throws IOException {
  101. Doc2HtmlUtil coc2HtmlUtil = getDoc2HtmlUtilInstance ();
  102. File file = null;
  103. FileInputStream fileInputStream = null;
  104. file = new File("C:/Users/MACHENIKE/Desktop/xxx.doc");
  105. fileInputStream = new FileInputStream(file);
  106. coc2HtmlUtil.file2pdf(fileInputStream, "E:/360","doc");
  107. }
  108. }
 
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

使用openoffice转pdf,详细的更多相关文章

  1. java根据模板导出PDF详细教程

    原文:https://blog.csdn.net/pengyufight/article/details/75305128 题记:由于业务的需要,需要根据模板定制pdf文档,经测试根据模板导出word ...

  2. openoffice转换pdf 异常问题查找处理 errorCode 525

    could not save output document; OOo errorCode: 525 该问题是由于java程序和openoffice的启动所属用户不同导致.使用以下命令查看端口和进程 ...

  3. Java使用Openoffice将word、ppt转换为PDF

    最近项目中要实现WORD的文件预览功能,我们可以通过将WORD转换成PDF或者HTML,然后通过浏览器预览. OpenOffice OpenOffice.org 是一套跨平台的办公室软件套件,能在 W ...

  4. word转PDF,PDF转Image,使用oppenOffice注意事项等

    最近在电子合同等项目中需要把word或者pdf转换成image,用到了openOffice把word转换pdf,以及把pdf转换成图片 感谢小伙伴张国清花费了三天时间来实现了此功能.下面我将把具体的步 ...

  5. openoffice下中文乱码问题解决

    在系统安装完OpenOffice进行pdf文档转换的时候 文档会出现乱码如下: 这里主要有两个原因: 1.上传的文件的编码是Windows上的默认编码GBK,而linux服务器默认编码是UTF-8,这 ...

  6. python从TXT创建PDF文件——reportlab

    使用reportlab创建PDF文件电子书一般都是txt格式的,某些电子阅读器不能读取txt的文档,如DPT-RP1.因此本文从使用python实现txt到pdf的转换,并且支持生成目录,目录能够生成 ...

  7. 渗透测试报告收集、生成工具MagicTree

    0x00 软件介绍: MagicTree是Gremwell开发的一个Java程序,支持主动收集数据和生成报告的工具.他通过树形结构节点来管理数据,这种分层存储的方法对管理主机和网络数据特别有效. 其分 ...

  8. linuxtoy.org资源

    https://linuxtoy.org/archives.html Archives 在 Android 系统上安装 Debian Linux 与 R (2015-07-14) Pinos:实现摄像 ...

  9. Basler usb SDK安装在opencv采集图像

    近期,入手一台baslerUSB接口的CCD相机,但是貌似之前图像采集的编程无法调动其摄像头,在网上搜了一下,大家的说法就是安装它的SDK文件包,并且调用它内部函数编写代码.其实新版的Basle相机驱 ...

随机推荐

  1. 关于wireshark的过滤器规则学习小结

    关于wireshark的过滤器规则学习小结 [前言] 这两天一直在熟悉wireshark的过滤器语法规则,以前也接触过这个工具,但只是学校老师教的如何去选择一个接口进行抓取,以及如何去分析一个包的数据 ...

  2. 【Webservice】2 counts of IllegalAnnotationExceptions Two classes have the same XML type name

    在使用客户端调用服务端的时候发生了2 counts of IllegalAnnotationExceptions Two classes have the same XML type name的错误, ...

  3. 下载安装Git,学习笔记

    官方地址为:https://git-scm.com/download/win 2.下载完之后,双击安装,全部选择默认. 3.选择安装目录 4.选择组件 5.开始菜单目录名设置  6.选择使用命令行环境 ...

  4. 基于UDP的编程

    前提:基于Linux系统的学习 服务器端编程模型1 socket(2) 创建通讯端点,返回一个文件描述符fd2 bind(2) 将fd绑定到本地的地址和端口while(1){ 阻塞等待客户端请求数据的 ...

  5. 2019牛客暑期多校训练营(第四场)A meeting(dfs或dp,dp待更新)

    示例1: 输入: 4 21 23 13 42 4 输出:2 说明: They can meet at place 1 or 3. 题意:从K个点到达不联通图某个点需要的最短时间,这个最短时间是这K个人 ...

  6. 暑期ACM集训

    2019-07-17 08:42:11 这是总结昨天的做题情况 总体来说,好久的没做题了,实力下降了许多,这一个月假又学习吧!!!! A - Ropewalkers Polycarp decided ...

  7. Java架构笔记:用JWT对SpringCloud进行认证和鉴权

    写在前面 喜欢的朋友可以关注下专栏:Java架构技术进阶.里面有大量batj面试题集锦,还有各种技术分享,如有好文章也欢迎投稿哦. image.png JWT(JSON WEB TOKEN)是基于RF ...

  8. C#-System.Dynamic.ExpandoObject

    dynamic dynamicObject = new System.Dynamic.ExpandoObject(); dynamicObject.Id = Guid.NewGuid(); (dyna ...

  9. CentOS 6.5 iptables原理详解以及功能说明

    CentOS 6.5 iptables原理详解以及功能说明 来源 https://blog.51cto.com/tanxw/1389114 前言 iptables其实就是Linux下的一个开源的信息过 ...

  10. 【转载】使用Response.WriteFile输出文件以及图片

    Response对象是Asp.Net应用程序中非常重要的一个内置对象,其作用为负责将服务器执行好的信息输出给客户端,可以使用Response.WriteFile方法来像客户端输出文件或者图片,输出图片 ...