Java使用openoffice将office系列文档转换为PDF

前导:

  1. 开发过程中经常会使用java将office系列文档转换为PDF, 一般都使用微软提供的openoffice+jodconverter 实现转换文档。
  2. openoffice既有windows版本也有linux版。不用担心生产环境是linux系统。
  3. 关于linux系统安装openoffice软件请参照:待更新...

 

java使用SWFTools将PDF转成swf并使用flexpaper播放PDF

1、openoffice依赖jar,以maven为例:

<dependency>
			<groupId>com.artofsolving</groupId>
			<artifactId>jodconverter</artifactId>
			<version>2.2.1</version>
		</dependency>
		<dependency>
			<groupId>org.openoffice</groupId>
			<artifactId>jurt</artifactId>
			<version>3.0.1</version>
		</dependency>
		<dependency>
			<groupId>org.openoffice</groupId>
			<artifactId>ridl</artifactId>
			<version>3.0.1</version>
		</dependency>
		<dependency>
			<groupId>org.openoffice</groupId>
			<artifactId>juh</artifactId>
			<version>3.0.1</version>
		</dependency>
		<dependency>
			<groupId>org.openoffice</groupId>
			<artifactId>unoil</artifactId>
			<version>3.0.1</version>
		</dependency>

		<!--jodconverter2.2.1必须依赖slf4j-jdk14必须这个版本,不然源码中日志会报错,很low的一个问题-->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-jdk14</artifactId>
			<version>1.4.3</version>
		</dependency>

2、直接上转换代码,需要监听openoffice应用程序8100端口即可。

	public void convert(File sourceFile, File targetFile) {

		try {
			// 1: 打开连接
			OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
			connection.connect();

			DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
			// 2:获取Format
			DocumentFormatRegistry factory = new BasicDocumentFormatRegistry();
			DocumentFormat inputDocumentFormat = factory
					.getFormatByFileExtension(getExtensionName(sourceFile.getAbsolutePath()));
			DocumentFormat outputDocumentFormat = factory
					.getFormatByFileExtension(getExtensionName(targetFile.getAbsolutePath()));
			// 3:执行转换
			converter.convert(sourceFile, inputDocumentFormat, targetFile, outputDocumentFormat);
		} catch (ConnectException e) {
			log.info("文档转换PDF失败");
		}
	}

3、需注意:jodconverter 在转换2007版本以后的xxx.docx文档会报错,原因大家都明03后缀名xxx.doc  07以后版本xxx.docx

查看jodconverter源码发现documentFormat不支持xxx.docx格式BasicDocumentFormatRegistry中public DocumentFormat getFormatByFileExtension(String extension)默认支持是使用doc格式

BasicDocumentFormatRegistry类源码

//
// JODConverter - Java OpenDocument Converter
// Copyright (C) 2004-2007 - Mirko Nasato <[email protected]>
//
// This library is free software; you can redistribute i
  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值