documents4j 实现Word文档、xlsx、等格式转换PDF文件

1、documents4j 简介

document4j是一个用来进行文档格式转换的Java工具库,它通过借助本机中支持指定文件格式到目标文件格式转换的应用,来实现整个转换的过程。
document4j 实现了Microsoft Word、Excel的适配功能,可以将docx文件转换为pdf文件,并且在这个过程中不会出现非微软文件转换出现的扭曲情况。

document4j提供了一个简单的API,并且有两个具体的实现:

本地策略
在本地版的实现策略中,document4j将指定文件的转换任务委派给本机中相应的应用程序。因此,为了保证正常运行,这台机器需要在后台预装好支持转换的软件,诸如MicrosoftWord / Excel 。
document4j提供了一套简单易用的机制允许用户注册自定义的转换器,同时将具体的实现细节和Microsoft Word / Excel 进行对接结合。

远程策略
在远程版的实现策略中,document4j将文档的转换工作通过REST-API的方式提供到远程的服务端进行转换。在这个过程中,请求方将文件与相关的格式转换信息发送到服务器端,转换完毕后,转换完成的文件将通过response的方式传输回来。

对于document4j的用户来说,这些实现方式都是完全透明的。因此,用户完全可以在本地开发与测试的时候,采用本地版的实现策略,而在生产环境中,完全透明地切换成远程实现模式。所以,后台转换功能也更容易进行模拟操作。

2、documents4j 的简单使用

	<!--转pdf-->
		<dependency>
			<groupId>com.documents4j</groupId>
			<artifactId>documents4j-local</artifactId>
			<version>1.0.3</version>
		</dependency>
		<dependency>
			<groupId>com.documents4j</groupId>
			<artifactId>documents4j-transformer-msoffice-word</artifactId>
			<version>1.0.3</version>
		</dependency>

		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itextpdf</artifactId>
			<version>5.5.10</version>
		</dependency>
/**
     * docx、xlsx、转pdf
     * @param docPath
     * @param pdfPath
     * @return
     */
    public static boolean docTopdf(String docPath, String pdfPath) {
    
    

        File inputWord = new File(docPath);
        File outputFile = new File(pdfPath);
        try {
    
    
            InputStream docxInputStream = new FileInputStream(inputWord);
            OutputStream outputStream = new FileOutputStream(outputFile);
            IConverter converter = LocalConverter.builder().build();
            String fileTyle=docPath.substring(docPath.lastIndexOf("."),docPath.length());//获取文件类型
            if(".docx".equals(fileTyle)){
    
    
                converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
            }else if(".doc".equals(fileTyle)){
    
    
                converter.convert(docxInputStream).as(DocumentType.DOC).to(outputStream).as(DocumentType.PDF).execute();
            }else if(".xls".equals(fileTyle)){
    
    
                converter.convert(docxInputStream).as(DocumentType.XLS).to(outputStream).as(DocumentType.PDF).execute();
            }else if(".xlsx".equals(fileTyle)){
    
    
                converter.convert(docxInputStream).as(DocumentType.XLSX).to(outputStream).as(DocumentType.PDF).execute();
            }
            docxInputStream.close();
            outputStream.close();
            inputWord.delete();
            System.out.println("pdf转换成功");
            return true;
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return false;
        }
    }

3、使用报错 :document4j框架使用问题-java.util.concurrent.ExecutionException: Could not complete conversion

前言
使用document4j调用office将其它格式的文件转换成PDF时,有使用报错比如

java.util.concurrent.ExecutionException: Could not complete conversion
at com.documents4j.job.FailedConversionFuture.get(FailedConversionFuture.java:35)
… Caused by: com.documents4j.throwables.ConversionInputException: The input file
seems to be corrupt
at com.documents4j.util.Reaction$ConversionInputExceptionBuilder.make(Reaction.java:159)

出现这个错误是因为,如果我们把java程序当作window服务使用时,由于office不提供windows service的上下文环境,导致调用时输入流会中断。

解决办法
从document官方文档上得知

documents4j might malfunction when run as a Windows service together
with MS Office conversion. Note that MS Office does not officially
support execution in a service context. When run as a service, MS
Office is always started with MS Window’s local service account which
does not configure a desktop. However, MS Office expects a desktop to
exist in order to run properly. Without such a desktop configuration,
MS Office will start up correctly but fail to read any input file. In
order to allow MS Office to run in a service context, there are two
possible approaches of which the first approach is more recommended:

On a 32-bit system, create the folder
C:\Windows\System32\config\systemprofile\Desktop. On a 64-bit system,
create the folder C:\Windows\SysWOW64\config\systemprofile\Desktop.
Further information can be found on MSDN. You can manipulate MS
Window’s registry such that MS Office applications are run with
another account than the local service account. This approach is
documented on MSDN. Note that this breaks MS Window’s sandbox model
and imposes additional security threats to the machine that runs MS
Office.

当应用在window service上下文环境中运行,同时使用document4j的转换功能可能出现问题,MS Office不官方支持在上下文环境中使用,所以当我们的应用由服务的方式运行时,若使用document4j会报错。
一个典型的盒子,jenkins自动代部署时,执行java -jar test.jar启动test应用,应用就是在winows上下文环境中运行的。
有2种解决办法,第二种我没试过,尝试第一种有效,只介绍第一种方式。

win32位系统中,在C:\Windows\System32\config\systemprofile\位置下创建Desktop文件夹
win64位系统中,在C:\Windows\SysWOW64\config\systemprofile\位置下创建Desktop文件夹

创建完成后重启电脑即可。

协议

documents4j遵循Apache 2.0开源协议发布。

官方网站:http://documents4j.com
开源地址:https://github.com/documents4j/documents4j
其他方式实现 PDF转换:https://www.jb51.net/article/254043.htm

猜你喜欢

转载自blog.csdn.net/lijie0213/article/details/127796317