使用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相机驱 ...
随机推荐
- [转帖]六种Socket I/O模型幽默讲解
六种Socket I/O模型幽默讲解 https://www.cnblogs.com/jikebiancheng/p/6225009.html 原贴已经找不到了.. 老陈有一个在外地工作的女儿,不能经 ...
- VMware虚拟机(Ubuntu)通过主机代理实现——浏览器+终端访问外网
环境说明:主机win10 + 虚拟机ubunut16.04 + 主机s-h-a-d-o-w-socks win10 主机相关操作配置1: 按下 Win + R 快捷键,输入 cmd ,然后在命令行中输 ...
- Linux追加磁盘扩展
一:查看磁盘空间信息: fdisk -l 查看当前的系统的磁盘空间的情况: 二:增加分区: fdisk /dev/sda 键入n,增加一个分区,得到: 键入 p,主分区,并键入3(编号): 默认起始扇 ...
- Python Django mysqlclient安装和使用
一.安装mysqlclient 网上看到很过通过命令:pip install mysqlclient 进行安装的教程,但是我却始终安装失败,遇到的错误千奇百怪,后来通过自己下载mysqlclient客 ...
- Windows下的Android Studio环境搭建、安装使用
https://jingyan.baidu.com/article/20b68a88ff2ca4796cec6232.html https://blog.csdn.net/jklinux/articl ...
- MySQL多表关联查询数量
//多表关联查询数量select user, t1.count1, t2.count2from user tleft join ( select user_id, count(sport_type) ...
- Django2.0 分页的应用
#分页例子from django.core.paginator import Paginatordef blog_list(request): blog_all_list = models. ...
- hive四种排序
order by order by 会对输入做全局排序,因此只有一个reducer(多个reducer无法保证全局有序)只有一个reducer,会导致当输入规模较大时,需要较长的计算时间. set h ...
- MYSQL安装与卸载(一)
系统:win10(其他版本系统不在本次内容) MYSQL下载地址:https://dev.mysql.com/downloads/mysql/ MySQL安装主流分为两种:msi,zip Zip:压缩 ...
- python selectors模块实现 IO多路复用机制的上传下载
import selectorsimport socketimport os,time BASE_DIR = os.path.dirname(os.path.abspath(__file__))''' ...