前言:
两种方法:documents4j
和aspose
最开始是用documents4j,在本地使用很方便,但是部署到LINUX上面之后,抛出异常,就看了下官方文档,documents4j是使用本地的MS Office应用做的文件格式转换,Linux没有对应的MS Office应用,所以直接就废除.后来改用aspose,在本地也是测试完成,没有问题,但是服务器上就是各种中文乱码(中文小方格),跟之前使用openoffice的乱码虽然不一样,但是还是乱码.不过最终解决了问题.
一、documents4j实现格式转换
需要MS Office,官方并没有说documents4j不支持Linux下运行,但是LINUX确实没安装MS应用,我也没费工夫去研究安装MS,如果谁好了,麻烦告知一下.
依赖
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-local</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-transformer-msoffice-word</artifactId>
<version>1.1.1</version>
</dependency>
代码
package com.qingyu.transform.utils;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import org.junit.jupiter.api.Test;
import java.io.*;
/**
* @ProjectName: transform
* @Package: com.qingyu.transform.utils
* @ClassName: WordToPdf
* @Author: qingyu
* @Description:
* @Date: 2020/3/19 13:46
* @Version: 1.0
*/
class WordToPdf {
/**
* 将之前对应的word文件转换成pdf,然后预览pdf文件
*/
public static String wordToPdf( String suffix ){
// 转换之后的pdf文件
File inputWord = new File("C:/Users/Administrator/Desktop/测试.docx");
File outputFile = new File("C:/Users/Administrator/Desktop/测试.pdf");
try {
InputStream docxInputStream = new FileInputStream(inputWord);
OutputStream outputStream = new FileOutputStream(outputFile);
IConverter converter = LocalConverter.builder().build();
if(suffix.equals("doc")){
converter.convert(docxInputStream).as(DocumentType.DOC).to(outputStream).as(DocumentType.PDF).execute();
} else if(suffix.equals("docx")){
converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
} else if(suffix.equals("txt")){
converter.convert(docxInputStream).as(DocumentType.TEXT).to(outputStream).as(DocumentType.PDF).execute();
}
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
wordToPdf("docx");
}
}
二、aspose实现文件转换
依赖
首先aspose是收费软件,pom依赖无法直接下载(反正我是没下载下来),我是通过下载别人分享的链接拿到的jar包。通过Project StraStructure引用进来的,在项目中直接放在lib包下面.
下面的依赖是根据jar包的pom文件写的,不是正确的
,不过你可以自己上传到自己的repository中,构建一个pom,然后作为依赖加到项目中
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>16.8.0</version>
</dependency>
代码
/**
* @ProjectName: transform
* @Package: com.qingyu.transform.utils
* @ClassName: Word2PdfUtil
* @Author: qingyu
* @Description:
* @Date: 2020/3/20 10:47
* @Version: 1.0
*/
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
public class Word2PdfUtil {
/**
* The constant LOG.
*
*/
private static final Logger LOG = LoggerFactory.getLogger(Word2PdfUtil.class);
/**
* 获取license
*
* @return
*/
private static boolean getLicense() {
boolean result = false;
try {
// 凭证
String licenseStr =
"<License>\n" +
" <Data>\n" +
" <Products>\n" +
" <Product>Aspose.Total for Java</Product>\n" +
" <Product>Aspose.Words for Java</Product>\n" +
" </Products>\n" +
" <EditionType>Enterprise</EditionType>\n" +
" <SubscriptionExpiry>20991231</SubscriptionExpiry>\n" +
" <LicenseExpiry>20991231</LicenseExpiry>\n" +
" <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n" +
" </Data>\n" +
" <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n" +
"</License>";
InputStream license = new ByteArrayInputStream(licenseStr.getBytes("UTF-8"));
License asposeLic = new License();
asposeLic.setLicense(license);
result = true;
} catch (Exception e) {
LOG.error("error:", e);
}
return result;
}
/**
* Word 2 pdf.
*
* @param pdfFilePath the pdf file path
*/
public static void word2Pdf( String pdfFilePath) {
FileOutputStream fileOS = null;
// 验证License
if (!getLicense()) {
LOG.error("验证License失败!");
return;
}
File inputWord = new File("C:/Users/Administrator/Desktop/测试.docx");
try {
//此处处理乱码和小方块
//如果在本地运行,此处报错,请注释这个这是字体,主要是为了解决linux环境下面运行jar时找不到中文字体的问题
FontSettings.getDefaultInstance().setFontsFolders(
new String[] {"/usr/share/fonts", "/usr/share/fonts/chinese"}
, true);
Document doc = new Document(new FileInputStream(inputWord));
fileOS = new FileOutputStream(new File(pdfFilePath));
// 保存转换的pdf文件
doc.save(fileOS, SaveFormat.PDF);
} catch (Exception e) {
LOG.error("error:", e);
} finally {
try {
if(fileOS != null){
fileOS.close();
}
} catch (IOException e) {
LOG.error("error:", e);
}
}
}
public static void main(String[] args) {
word2Pdf("C:/Users/Administrator/Desktop/测试.pdf");
}
}
问题
-
本地测试正常,Linux还是乱码
原因:
(1)Linux服务器上没有安装对应的中文字体,参考
(2)字体并不是被所有用户通用的
(3)没有构建字体索引,没有刷新字体路径缓存
解决:
百度Linux安装中文字体,之后,运行命令看看是否能看到中文字体 -
安装了中文字体还是乱码
原因:在Linux上运行Jar无法找到中文字体,可以在代码里面添加路径指向中文字体文件夹