使用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
使用openoffice转pdf,详细的更多相关文章
- java根据模板导出PDF详细教程
原文:https://blog.csdn.net/pengyufight/article/details/75305128 题记:由于业务的需要,需要根据模板定制pdf文档,经测试根据模板导出word ...
- openoffice转换pdf 异常问题查找处理 errorCode 525
could not save output document; OOo errorCode: 525 该问题是由于java程序和openoffice的启动所属用户不同导致.使用以下命令查看端口和进程 ...
- Java使用Openoffice将word、ppt转换为PDF
最近项目中要实现WORD的文件预览功能,我们可以通过将WORD转换成PDF或者HTML,然后通过浏览器预览. OpenOffice OpenOffice.org 是一套跨平台的办公室软件套件,能在 W ...
- word转PDF,PDF转Image,使用oppenOffice注意事项等
最近在电子合同等项目中需要把word或者pdf转换成image,用到了openOffice把word转换pdf,以及把pdf转换成图片 感谢小伙伴张国清花费了三天时间来实现了此功能.下面我将把具体的步 ...
- openoffice下中文乱码问题解决
在系统安装完OpenOffice进行pdf文档转换的时候 文档会出现乱码如下: 这里主要有两个原因: 1.上传的文件的编码是Windows上的默认编码GBK,而linux服务器默认编码是UTF-8,这 ...
- python从TXT创建PDF文件——reportlab
使用reportlab创建PDF文件电子书一般都是txt格式的,某些电子阅读器不能读取txt的文档,如DPT-RP1.因此本文从使用python实现txt到pdf的转换,并且支持生成目录,目录能够生成 ...
- 渗透测试报告收集、生成工具MagicTree
0x00 软件介绍: MagicTree是Gremwell开发的一个Java程序,支持主动收集数据和生成报告的工具.他通过树形结构节点来管理数据,这种分层存储的方法对管理主机和网络数据特别有效. 其分 ...
- linuxtoy.org资源
https://linuxtoy.org/archives.html Archives 在 Android 系统上安装 Debian Linux 与 R (2015-07-14) Pinos:实现摄像 ...
- Basler usb SDK安装在opencv采集图像
近期,入手一台baslerUSB接口的CCD相机,但是貌似之前图像采集的编程无法调动其摄像头,在网上搜了一下,大家的说法就是安装它的SDK文件包,并且调用它内部函数编写代码.其实新版的Basle相机驱 ...
随机推荐
- [转帖]亚马逊彻底去掉 Oracle 数据库:迁移完成
亚马逊彻底去掉 Oracle 数据库:迁移完成 https://mp.weixin.qq.com/s/KFonq8efDZ5K6x4YzIVbbg 云头条的信息挺不错的.. 2019 年 10 月 1 ...
- Docker 学习笔记(三):数据、网络、系统权限、docker-compose
一.Docker 数据管理 Docker 持久化数据有两种方式: 使用数据卷:更安全,和主机耦合度低 将主机的目录挂载到容器中:更方便,主机和容器可以很方便地交换数据. 数据卷相关的命令: docke ...
- IO是否会一直占用CPU?(转)
原文来自知乎:https://www.zhihu.com/question/27734728 这是一个很好的关于并发/并行系统的问题.简单回答就是:IO所需要的CPU资源非常少.大部分工作是分派给DM ...
- 轻松玩转Ant Design Pro一
ant design pro来源于ant design,其是一段自带样式的react组件,用于企业后台的漂亮的,可控的组件.ant design有很多组件和样式,不可能所有都记住,我们只要记住常用的, ...
- HTTP响应状态码整理
1xx:信息 100 Continue服务器仅接收到部分请求,但是一旦服务器并没有拒绝该请求,客户端应该继续发送其余的请求.101 Switching Protocols服务器转换协议:服务器将遵从客 ...
- .NET调用腾讯云API实例
最近项目有用到腾讯云的身份识别接口,话不多说,直接上代码: private void IDCardVerification(HttpContext context) { string imgStr = ...
- ABP 基于DDD的.NET开发框架 学习(二)创建实体
1.创建模型类打开.Core项目,新建新建一个项目文件夹(Demo);为了演示表关联及外键的使用,创建两个类:创建类ClothesCategoty.csusing Abp.Domain.Entitie ...
- 关于MQ的几件小事(三)如何保证消息不重复消费
1.幂等性 幂等(idempotent.idempotence)是一个数学与计算机学概念,常见于抽象代数中. 在编程中一个幂等操作的特点是其任意多次执行所产生的影响均与一次执行的影响相同.幂等函数,或 ...
- restTemplate源码解析(目录)
restTemplate是spring实现的,基于restful风格的http请求模板.使用restTemplate可以简化请求操作的复杂性,同时规范了代码风格.本系列文章,将根据以下目录顺序,从源码 ...
- springboot启动流程(目录)
springboot出现有段时间了,不过却一直没有怎么去更多地了解它.一方面是工作的原因,另一方面是原来觉得是否有这个必要,但要持续做java似乎最终逃不开要去了解它的命运.于是考虑花一段时间去学习一 ...