2020-09-28

跨平台文件在线预览解决方案(三)- LibreOffice vs OpenOffice 前言 突然有一天在业务系统中发现OpenOffice转换word为pdf时,出现个别中文字丢失以及格式发生变化。这在业务系统中预览合同等重要附件是致命的。Google了半天也没找到问题所在。于是采用LibreOffice进行转换,看看转换效果。office文件在线预览原理一样,先转换成pdf,然后采用pdf. js预览。 问题复现 原word文件 OpenOffice转换后pdf文件 链接 关于OpenOffice的使用方法,参考《跨平台(uni-app)文件在线预览解决方案》第四章节 关于 阅读详情

java后端实现将office转pdf功能,主要用于前端页面展示;

代码实现(libreOffice实现 + office实现):


 

libreOffice实现:

java实现逻辑:

import javax.annotation.Resource;

public class FileHandler1 {

    @Resource
    private DocumentConverter documentConverter;

    /**
     * 文件转换
     * @param filepath
     * @return
     * @throws OfficeException
     */
    @PostMapping("qwe")
    public String toPdf() throws OfficeException {
        long l = System.currentTimeMillis();
        log.info("++++++++++++++++++++++++++++++++++" + l);
        String filepath = "E:\\能源.docx";
        File word = new File("E:\\能源.docx");
        //截取字符串把word的后缀改为pdf
        String pdfpath= filepath.substring(0,filepath.lastIndexOf("."))+".pdf";
        File pdf = new File(pdfpath);
        //文件转换
        documentConverter.convert(word).to(pdf).execute();
        return (l - System.currentTimeMillis()) + "";
    }
}

application.yml

jodconverter:
  local:
    enabled: true
# 设置LibreOffice主目录
    office-home: D:/allSoltware/LibreOffice/install2
# 开启多个LibreOffice进程,每个端口对应一个进程
    portNumbers: 8100,8101,8102
# LibreOffice进程重启前的最大进程数
    maxTasksPerProcess: 100

pom.xml

<!-- word转pdf所需jar begin -->
		<dependency>
			<groupId>org.jodconverter</groupId>
			<artifactId>jodconverter-core</artifactId>
			<version>4.2.0</version>
		</dependency>
		<dependency>
			<groupId>org.jodconverter</groupId>
			<artifactId>jodconverter-local</artifactId>
			<version>4.2.0</version>
		</dependency>
		<dependency>
			<groupId>org.jodconverter</groupId>
			<artifactId>jodconverter-spring-boot-starter</artifactId>
			<version>4.2.0</version>
		</dependency>
		<dependency>
			<groupId>org.libreoffice</groupId>
			<artifactId>ridl</artifactId>
			<version>5.4.2</version>
		</dependency>
<!-- word转pdf所需jar end -->

注:这种实现方式转换时间很快,但是对于格式问题会有偏移,错位等影响

office实现:

java实现逻辑1(这个可以):

package energy.controller;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import java.io.File;
import org.springframework.stereotype.Component;

/**
 * @author 
 * @date 2020/9/27
 */
@Component
public class Jacob {
    /** 转PDF格式值 */
    static final int WORD_FORMAT_PDF = 17;
    static final int EXCEL_FORMAT_PDF = 0;
    static final int PPT_FORMAT_PDF = 32;
    /*** @Description:根据文件类型转换为pdf */

    public void convert2PDF(String inputFile, String pdfFile) {
        String suffix = getFileSufix(inputFile);
        if (suffix.equals("doc") || suffix.equals("docx") || suffix.equals("txt")) {
            word2PDF(inputFile, pdfFile);
        } else if (suffix.equals("xls") || suffix.equals("xlsx")) {
            excel2PDF(inputFile, pdfFile);
        } else if (suffix.equals("ppt") || suffix.equals("pptx")) {
            ppt2PDF(inputFile, pdfFile);
        } else {
            System.out.println("文件格式不支持转换!");
        }
    }
    /** * @Description:word转pdf  */
    private void word2PDF(String inputFile, String pdfFile) {
        System.out.println("启动Word...");
        long start = System.currentTimeMillis();
        ActiveXComponent app = null;
        Dispatch doc = null;
        try {
            // 创建一个word对象
            app = new ActiveXComponent("Word.Application");
            // 不可见打开word (但默认是不可见的)
            app.setProperty("Visible", new Variant(false));
            // 获取文挡属性
            // 调用Documents对象中Open方法打开文档,并返回打开的文档对象Document
            Dispatch docs = app.getProperty("Documents").toDispatch();
            doc = Dispatch.call(docs, "Open", inputFile).toDispatch();
            System.out.println("打开文档..." + inputFile);
            System.out.println("转换文档到PDF..." + pdfFile);
            File tofile = new File(pdfFile);
            if(tofile.exists()) {
                tofile.delete();
            }
            // word保存为pdf格式宏,值为17
            Dispatch.call(doc, "SaveAs", pdfFile, WORD_FORMAT_PDF);
            long end = System.currentTimeMillis();
            System.out.println("转换完成..用时:" + (end - start) + "ms.");
        } catch (Exception e) {
            System.out.println("========Error:文档转换失败:" + e.getMessage());
        } finally {
            Dispatch.call(doc, "Close", false);
            System.out.println("关闭文档");
            if (app != null) {
                app.invoke("Quit", new Variant[]{});
            }
        }
        //如果没有这句话,winword.exe进程将不会关闭
        ComThread.Release();
    }
    /** * @Description:excel转pdf  */
    private void excel2PDF(String inputFile, String pdfFile) {
        System.out.println("启动Excel...");
        long start = System.currentTimeMillis();
        ActiveXComponent app = null;
        Dispatch excel = null;
        try {
            // 创建一个excel对象
            app = new ActiveXComponent("Excel.Application");
            // 不可见打开excel
            app.setProperty("Visible", new Variant(false));
            // 获取文挡属性
            Dispatch excels = app.getProperty("Workbooks").toDispatch();
            // 调用Documents对象中Open方法打开文档,并返回打开的文档对象Document
            excel = Dispatch.call(excels, "Open", inputFile).toDispatch();
            System.out.println("打开文档..." + inputFile);
            System.out.println("转换文档到PDF..." + pdfFile);
            File tofile = new File(pdfFile);
            if(tofile.exists()) {
                tofile.delete();
            }
            // Excel不能调用SaveAs方法
            Dispatch.call(excel, "ExportAsFixedFormat", EXCEL_FORMAT_PDF, pdfFile);
            long end = System.currentTimeMillis();
            System.out.println("转换完成..用时:" + (end - start) + "ms.");
        } catch (Exception e) {
            System.out.println("========Error:文档转换失败:" + e.getMessage());
        } finally {
            Dispatch.call(excel, "Close", false);
            System.out.println("关闭文档");
            if (app != null) {
                app.invoke("Quit", new Variant[]{});
            }
        }
        //如果没有这句话,winword.exe进程将不会关闭
        ComThread.Release();
    }
    /*** @Description:ppt转pdf  */
    private void ppt2PDF(String inputFile, String pdfFile) {
        System.out.println("启动PPT...");
        long start = System.currentTimeMillis();
        ActiveXComponent app = null;
        Dispatch ppt = null;
        try {
            // 创建一个ppt对象
            app = new ActiveXComponent("PowerPoint.Application");
            // 不可见打开(PPT转换不运行隐藏,所以这里要注释掉)
            // app.setProperty("Visible", new Variant(false));
            // 获取文挡属性
            Dispatch ppts = app.getProperty("Presentations").toDispatch();
            // 调用Documents对象中Open方法打开文档,并返回打开的文档对象Document
            ppt = Dispatch.call(ppts, "Open", inputFile, true, true, false).toDispatch();
            System.out.println("打开文档..." + inputFile);
            System.out.println("转换文档到PDF..." + pdfFile);
            File tofile = new File(pdfFile);
            if(tofile.exists()) {
                tofile.delete();
            }
            Dispatch.call(ppt, "SaveAs", pdfFile, PPT_FORMAT_PDF);
            long end = System.currentTimeMillis();
            System.out.println("转换完成..用时:" + (end - start) + "ms.");
        } catch (Exception e) {
            System.out.println("========Error:文档转换失败:" + e.getMessage());
        } finally {
            Dispatch.call(ppt, "Close");
            System.out.println("关闭文档");
            if (app != null) {
                app.invoke("Quit", new Variant[]{});
            }
        }
        //如果没有这句话,winword.exe进程将不会关闭
        ComThread.Release();
    }
    /*** @Description:获取文件后缀*/
    private String getFileSufix(String fileName) {
        int splitIndex = fileName.lastIndexOf(".");
        return fileName.substring(splitIndex + 1);
    }
}

java实现逻辑2(这个也可以):

package energy.controller;

import java.io.File;

import com.google.common.base.Objects;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import org.springframework.stereotype.Component;

@Component
public class PdfUtil {
	
	
	/**
	 * 将word/excel/ppt转成pdf
	 * Title: WPSToPdf
	 * Description: 
	 * @param wpsPath
	 * @return
	 */
	public String WPSToPdf(String wpsPath){
		boolean flag = false;
		String pdfPath = null;
		File file = new File(wpsPath);
		if (file.exists()) {
			if (wpsPath.startsWith("/")) {
				wpsPath = wpsPath.substring(1);
				wpsPath = wpsPath.replace("/", "\\");
			}
			pdfPath = wpsPath.substring(0, wpsPath.lastIndexOf("."))+".pdf";
			String fileType = wpsPath.substring(wpsPath.lastIndexOf(".")+1);
			if (Objects.equal(fileType, "docx") || Objects.equal(fileType, "doc")) {
				flag = wordToPdf(wpsPath, pdfPath);
			}else if (Objects.equal(fileType, "xlsx") || Objects.equal(fileType, "xls")) {
				flag = excelToPdf(wpsPath, pdfPath);
			}else if (Objects.equal(fileType, "pptx") || Objects.equal(fileType, "ppt")) {
				flag = pptToPdf(wpsPath, pdfPath);
			}
		}
		
		if (flag) {
			return pdfPath;
		}
		return null;
	}
	/**
	 * 将word文档转换为pdf文件
	 * Title: wordToPdf
	 * Description: 
	 * @param wordPath
	 * @param pdfPath
	 * @return
	 */
	public boolean wordToPdf(String wordPath,String pdfPath){
		ActiveXComponent component = new ActiveXComponent("Word.Application");
		try {
			component.setProperty("Visible", false);
			Dispatch dispatch = component.getProperty("Documents").toDispatch();
			Dispatch doc = Dispatch.call(dispatch, "Open",new Object[]{wordPath,false,true}).toDispatch();
			
			Dispatch.call(doc, "ExportAsFixedFormat",new Object[]{pdfPath,17});
			Dispatch.call(doc, "Close", new Object[]{false});
			component.invoke("Quit",0);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			component.invoke("Quit",0);
			return false;
		}
	}
	/**
	 * 将excel文件转换为pdf文件
	 * Title: excelToPdf
	 * Description: 
	 * @param excelPath
	 * @param pdfPath
	 * @return
	 */
	public boolean excelToPdf(String excelPath,String pdfPath){
		ComThread.InitSTA(true);
		ActiveXComponent component = new ActiveXComponent("Excel.Application");
		
		try {
			component.setProperty("Visible", false);
			component.setProperty("AutomationSecurity", new Variant(3));
			Dispatch dispatch = component.getProperty("Workbooks").toDispatch();
			Dispatch doc = Dispatch.invoke(dispatch,"Open",1, 
					new Object[]{excelPath,new Variant(false),new Variant(false)},new int[9]).toDispatch();
			Dispatch.invoke(doc, "ExportAsFixedFormat", 1, new Object[]{new Variant(0),pdfPath,new Variant(0)}, new int[1]);
			Dispatch.call(doc,"close", new Object[]{false});
			if (component != null) {
				component.invoke("Quit",new Variant[0]);
				component = null;
			}
			ComThread.Release();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			component.invoke("Quit");
			return false;
		}
	}
	/**
	 * ppt文件转pdf文件
	 * Title: pptToPdf
	 * Description: 
	 * @param pptPath
	 * @param pdfPath
	 * @return
	 */
	public boolean pptToPdf(String pptPath,String pdfPath){
		ActiveXComponent component = new ActiveXComponent("Powerpoint.Application");
		try {
			
			Dispatch ppts = component.getProperty("Presentations").toDispatch();
			Dispatch ppt = Dispatch.call(ppts, "Open", new Object[]{pptPath,true,true,false}).toDispatch();
			Dispatch.call(ppt, "SaveAs",new Object[]{pdfPath,32});
			Dispatch.call(ppt,"Close");
			component.invoke("Quit");
			
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			component.invoke("Quit");
			return false;
		}
		
		
	}
}

pom.xml

<dependency>
		<groupId>com.java</groupId>
		<artifactId>example-app</artifactId>
		<scope>system</scope>
		<systemPath>${project.basedir}/src/main/resources/repo/jacob.jar</systemPath>
</dependency>

需要将jar包放入项目中

还需要将jacob-1.19-x64.dll这个文件放入jdk的bin目录下,不然会报初始化失败的错误!

注:采用office的话需要安装office办公,速度要慢一些,但是还原度高,从事商业的话,可能会存在购买使用权的问题

FreeSWITCH安装指南:三种部署方式解析与实践对比 Freeswitch部署方案比较:Yum安装简单快捷但灵活性差;源码安装可定制性强,适合深度开发和性能优化;Docker部署环境一致性好但网络配置复杂。生产环境推荐源码安装以获得最佳性能和定制能力,而Docker适合快速部署和扩展。不同方案各有利弊,需根据具体需求选择。 阅读详情

相关推荐

跨厂商网络设备的RADIUS认证:Windows NPS的兼容性与最佳实践

本文详细探讨了Windows NPS在多厂商网络环境中的RADIUS认证实践,特别针对华为、华三、思科等主流设备的兼容性问题提供解决方案。从基础配置到高级优化,涵盖VSA属性映射、认证协议选择及安全加固措施,帮助企业实现统一身份认证并提升网络安全性。

weixin_29213827的博客 434

关于LibreOffice在linux上的使用以及出现的问题保姆级教程

关于解决LibreOffice在linux系统上面的安装以及Java程序进行连接可能出现的问题Java.net.ConnectException: connection failed: socket,host=127.0.0.1,port=8100,tcpNoDelay=1

xky0138的博客 1万+

基于python的超市历年数据可视化分析

包含:Order_Date Sales Quantity Profit year month。所有这些物品都在美国4个地区的49个州销售,来着793位客户的5009个订单。9994行,21列数据。

m0_74872863的博客 551

使用Openoffice实现并发多进程word文档转换预览

一、环境介绍 java openoffice 4.1.6 springboot整合开发 二、代码实现 pom文件依赖 在pom文件中添加项目依赖: <!-- https://mvnrepository.com/artifact/org.jodconverter/jodconverter-core --> <dependency> <groupId&gt...

qq_44470091的博客 4663

Hadoop与Kafka集群部署与优化实践指南

分布式系统是现代大数据处理的核心架构,其中Hadoop作为分布式存储与计算框架,Kafka作为分布式消息队列系统,共同构成了实时数据处理的基础设施。通过HDFS实现海量数据存储,结合YARN进行资源调度,而Kafka则保障了数据流的实时传输与高吞吐。这种技术组合在电商用户行为分析、物联网数据采集等场景中表现卓越。部署过程中需关注硬件资源配置、关键参数调优以及集群监控方案,例如通过调整HDFS块大小和Kafka partition数量来优化性能。合理运用Flume、Spark Streaming等工具可实现系

weixin_29061997的博客 369

避坑指南:ArcGIS 做莫兰指数分析,你的‘空间关系概念化’选对了吗?

本文深入解析了ArcGIS中莫兰指数分析的关键参数——'空间关系概念化'的选择策略。通过对比反距离法、固定距离法和K最近邻法的适用场景与影响机制,帮助研究者避免常见误区,提升空间自相关分析的准确性和解释力。特别针对全域莫兰指数和局域莫兰指数的计算差异提供了实用建议。

weixin_30872157的博客 830

Linux环境下安装Libreoffice

Libreoffice6.4网盘地址: 链接:https://pan.baidu.com/s/1Oii6OAprUExy2LvBmgmJNw 提取码:1234 1.上传libreoffice到/usr目录下 2.解压文件 tar -zxvf LibreOffice_6.4.6_Linux_x86-64_rpm.tar.gz 3.进入到解压文件 cd LibreOffice_6.4.6.2_Linux_x86-64_rpm/RPMS 4.安装依赖 yum install cairo -

Nxl19980606的博客 3997

通俗傻瓜式理清光栅化渲染和光线追踪渲染的原理

用通俗语言傻瓜式的讲清楚光栅渲染和光线追踪渲染的原理,方便没有相关理论基础的朋友理解入门。

qq_37366618的博客 2万+

批量杀进程libreoffice命令

geeklee@geeklee-ThinkPad-E420:~$ ps -ef UID PID PPID C STIME TTY TIME CMD root 1 0 0 08:06 ? 00:00:01 /sbin/init splash root 2 0 0 08:06 ? 00:0

GeekLee的博客 5453

如何使用Ray和PyTorch训练模型

用户编写训练函数 → 定义单机训练逻辑。通过扩缩容配置 → 指定需要多少资源(Worker 数量、CPU/GPU)。训练器整合训练函数和配置 → 自动将训练函数分发到多个 Worker 上并行执行。Worker 运行训练函数 → 在分布式环境中完成模型训练。通过这种模式,Ray Train 实现了对分布式训练的抽象,用户只需关注单机训练逻辑,无需手动管理分布式通信和资源分配。

m0_62464865的博客 1928

三层网络架构:核心层、汇聚层、接入层,每一层有啥作用?

分层模型的核心思想是和。接下来,我们将逐一剖析这三大层次的作用和特点。

网络技术联盟站 772

2020-09-28课堂笔记

2020-09-28课堂笔记主知识点1.连接查询2.删除(delete、drop、truncate)3.更新(update)4.插入insert into value()5.外键与主从表 主知识点 1.连接查询 1.内连接 select * from pro_dish pd inner join pro_dish_standard pds on pd.id = pds.dish_id 2.左连接(以左为主) select * from pro_dish pd left join pro_dish_stan

sxh06的博客 2120

scp 出现Permission denied错误 解决方法

第一种说辞(来源于网络),说是scp涉及root远程登录,默认是没有打开的,只需要把配置文件中的permit打开即可。最后scp的时候发现还不行,只需要将其scp的服务器用户名 修改为root即可。第二种解决方案,将scp 传输的服务器用户名改为root即可。(这是最基本的,一开始我忽视了这个问题,导致一直scp不了)window系统下,向ubuntu操作系统 scp传输文件。

码农研究僧的博客 6737
上一篇: docker学习------docker常用命令
下一篇: 发布Demo环境遇到的问题:jar包运行的服务,启动后运行一段时间莫名其妙就自己挂掉了
向超丶
博客等级 码龄9年 72粉丝 9原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值