【java】doc转pdf
市场上主流的 WORD 转 PDF 工具有两个:OpenOffice 和 Microsoft Office 转
换插件,可以通过部署这两个工具实现 WORD 转 PDF 功能。
1:
Microsoft 提 供 了 一 个 转 换 插 件 实 现 Office 转 PDF 功 能 , 即
SaveAsPDFandXPS。此插件是一个 com 组件,对于 C++、C#等语言可以直接使
用,如果是 JAVA 语言,需要通过 jacob 来调用 com 组件。
SaveAsPDFandXPS 插件要求必须有一台 Windows 服务器作为转换服务器安
装部署 Microsoft Office2007 以上的版本,然后再安装 SaveAsPDFandXPS 插件。
最后调用 com 组件实现转换。
官网地址:https://msdn.microsoft.com/en-us/library/dd301166(v=nav.90).aspx
2.
OpenOffice 是个开源的办公套件,提供了与 MS Word,Excel,PowerPoint 等
对应的多个软件,它支持包括 MS Office 2007 在内的多种格式,并且能够将其导
出为 PDF 文件。
这个方案是在 linux 服务器上安装 openOffice 然后通过 openOffice 命令来转换
pdf。
官方网址:http://www.openoffice.org/
在ubuntu下:
- tar -xvzf Apache_OpenOffice_4.1.3_Linux_x86-64_install-deb_zh-CN.tar.gz
 - cd zh-CN/DEBS/
 - sudo dpkg -i *.deb
 - cd desktop-integration/
 - sudo dpkg -i openoffice4.1-debian-menus_4.1.3-9783_all.deb
 
soffice --headless --accept="socket,host=127.0.0.1,port=8100;urp;" --nofirststartwizard &
启动服务,# netstat -an|more,可查看是否启动成功(是否有8100端口的服务)
package openofficeTest; import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ConnectException; import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.DocumentFormat;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter; public class Word2Pdf { public static int PORT = 8100; public static void main(String[] args){ String path1 = "/tmp/1.doc";
String path2 = "/tmp/2.pdf";
try {
wordToPdf(path1, path2);
} catch (Exception e) {
e.printStackTrace();
}
} public static void wordToPdf(String path1, String path2)
throws Exception {
File file1 = new File(path1);
File file2 = new File(path2);
// 获得文件格式
DefaultDocumentFormatRegistry formatReg = new DefaultDocumentFormatRegistry();
DocumentFormat pdfFormat = formatReg.getFormatByFileExtension("pdf");
DocumentFormat docFormat = formatReg.getFormatByFileExtension("doc");
// stream 流的形式
InputStream inputStream = new FileInputStream(file1);
OutputStream outputStream = new FileOutputStream(file2); /**
*
*/
OpenOfficeConnection connection = new SocketOpenOfficeConnection(PORT);
System.out.println(connection);
try { connection.connect();
DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
converter.convert(inputStream, docFormat, outputStream, pdfFormat);
} catch (ConnectException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
connection = null;
}
}
} }
但是,经过测试,openoffice转换的速度明显很慢,主要是在获取OpenOfficeConnection这块,我目前还没有找到能明显提升速度的方法,下面还有第三种基于libreoffice做转换的方式。
前提条件:要安装libreoffice, libreoffice-headless
安装命令:
yum install libreoffice -y
yum install libreoffice-headless -y
转换命令:libreoffice --headless --convert-to pdf:writer_pdf_Export --outdir /tmp/ /tmp/test.doc
其中/tmp/test.doc为测试用的doc文件,生成的pdf文件会在/tmp/下,名称会默认和doc的名字一样。
下面是项目中以doc文件流输入,返回pdf文件流的方法。
public static byte[] toPDF(byte[] b, String sourceFileName) throws Exception{
        File tempDir = null;
        try{
            tempDir = Files.createTempDir();
            String canonicalPath = tempDir.getCanonicalPath();
            File file = new File(canonicalPath + "/" + sourceFileName);
            OutputStream os = new FileOutputStream(file);
            BufferedOutputStream bufferedOutput = new BufferedOutputStream(os);
            bufferedOutput.write(b);
            String command = "libreoffice";
            Process proc = new ProcessBuilder(command, "--headless", "--convert-to", "pdf:writer_pdf_Export", "--outdir", canonicalPath, canonicalPath + "/" + sourceFileName)
                               .redirectErrorStream(true)
                               .start(); 
            ArrayList<String> output = new ArrayList<String>();
            BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line = null;
            while ((line = br.readLine()) != null)
                output.add(line);
            logger.info("执行pdf转换命令的输出:" + StringUtils.join(output, System.lineSeparator()));
            if (0 != proc.waitFor())
                throw new Exception("转换失败");
            File[] files = tempDir.listFiles();
            for (File file2 : files) {
                if (file2.getPath().endsWith(".pdf")) {
                    return IOUtils.toByteArray(new FileInputStream(file2));
                }
            }
            return null;
        }finally{
            if(tempDir != null)
                FileUtils.deleteDirectory(tempDir);
        }
    }
【java】doc转pdf的更多相关文章
- 利用Java动态生成 PDF 文档
		
利用Java动态生成 PDF 文档,则需要开源的API.首先我们先想象需求,在企业应用中,客户会提出一些复杂的需求,比如会针对具体的业务,构建比较典型的具备文档性质的内容,一般会导出PDF进行存档.那 ...
 - 利用LibreOffice转换ppt、doc转化pdf
		
利用LibreOffice转换ppt.doc转化pdf LibreOffice下载地址: http://www.libreoffice.org/download/libreoffice-fresh/ ...
 - Java实现Word/Pdf/TXT转html
		
引言: 最近公司在做一个教育培训学习及在线考试的项目,本人主要从事网络课程模块,主要做课程分类,课程,课件的创建及在线学习和统计的功能,因为课件涉及到多种类型,像视频,音频,图文,外部链接及文档类型. ...
 - Eclipse如何生成带有自定tag的Java Doc
		
1. 选择要生成Java Doc的工程,单击鼠标右键,在弹出菜单中选择[Export],会弹出以下对话框: 2. 选择[Java]--->[Javadoc],点击[Next]按钮,弹出以下对话框 ...
 - Android Studio 自动生成 Java Doc
		
Android Studio 生成 Java Doc 出现"编码GBK的不可映射字符"问题 错误的解决方案,复制粘贴一万遍也是错误的,下面是查找出来的,没有用的解决方案(还有几个, ...
 - IntelliJ IDEA使用maven-javadoc-plugin生成Java Doc控制台乱码
		
问题描述 在使用IDEA生成Java Doc的过程中,发现IDEA控制台乱码,作为有轻微代码强迫症的我来说,这是不可忍受的,需要鼓捣一番.先上pom.xml中的javadoc插件配置 <!--配 ...
 - Java 动态生成 PDF 文件
		
每片文章前来首小诗: 今日夕阳伴薄雾,印着雪墙笑开颜.我心仿佛出窗前,浮在半腰望西天. --泥沙砖瓦浆木匠 需求: 项目里面有需要java动态生成 PDF 文件,提供下载.今天我找了下有关了,系 ...
 - Python实现doc转化pdf
		
Python实现doc转化pdf python源码实现doc转化pdf #-*- coding:utf-8 -*- # doc2pdf.py: python script to convert doc ...
 - 推荐2本学习java书和PDF
		
推荐2本学习java书和PDF下载地址 <深入理解Java虚拟机:JVM高级特性与最佳实践>共分为五大部分,围绕内存管理.执行子系统.程序编译与优化.高效并发等核心主题对JVM进行了全面而 ...
 - 如何写Java文档注释(Java Doc Comments)
		
本文翻译自How to Write Doc Comments for the Javadoc Tool,但是精简了一些私以为不重要的东西 本文不讨论如何使用javadoc工具自动生成文档的方法,而是主 ...
 
随机推荐
- Android实用代码七段(二)
			
正文 一.获取应用程序下所有Activity public static ArrayList<String> getActivities(Context ctx) { Arra ...
 - Jedis操作Redis
			
Jedis操作Redis的常用封装方法 @Resource(name="jedispool") private JedisPool pool=null; /** * 设置缓存对象过 ...
 - openjudge(四)
			
关于switch的应用: #include <iostream>#include<iomanip>using namespace std;int main(){int a,b; ...
 - NSRC技术分享——自制Linux Rootkit检测工具
			
### 前言 Linux系统中存在用户态与内核态,当用户态的进程需要申请某些系统资源时便会发起系统调用.而内核态如何将系统的相关信息实时反馈给用户态呢,便是通过proc文件系统.如此便营造了一个相对隔 ...
 - JavaWeb学习笔记四 request&response
			
HttpServletResponse 我们在创建Servlet时会覆盖service()方法,或doGet()/doPost(),这些方法都有两个参数,一个为代表请求的request和代表响应res ...
 - C语言助教批改
			
作业批改 每次作业批改后写一篇作业点评,助教轮流写作业总结.(总结分工老师安排). 每个助教点评自己负责的同学博客,点评要详细,不能只有一句话. 有比较优秀博客请或典型问题推荐到qq群,并发给写总结助 ...
 - C语言--函数嵌套
			
一.实验作业 注意: 1.可以先初始化2个结构体数组数据以便测试. 2.要求用模块化方式组织程序结构,合理设计各自定义函数.同时,程序能够进行异常处理,检查用户输入数据的有效性,用户输入数据有错误,如 ...
 - 201621123050 《Java程序设计》第11周学习总结
			
1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结多线程相关内容. 2. 书面作业 本次PTA作业题集多线程 1. 源代码阅读:多线程程序BounceThread 1.1 BallR ...
 - 去掉xcode编译warning:ld: warning: directory not found for option '-L
			
选择工程, 编译的 (targets) 选择 Build Settings 菜单 查找 Library Search Paths 和 Framework Search Paths, 删掉编译报warn ...
 - Spring Boot jar包linux服务器部署
			
Spring Boot 部署 一.使用命令行java -jar 常驻 nohup java -jar spring-boot-1.0-SNAPSHOT.jar > log.file 2>& ...