在这里用到的是aspose.words这个组件。
可能网上有狠多这样的demo但是要不就是maven拉jar拉不下来,要不就是拉下来报 license的签名错误,还有一点在liunx系统转换成功后的pdf是乱码。这里我总结一下来解决相应的问题。maven包下载。pom文件配置:注意标红的地方,不然是下载不下来的。仓库地址:
报错的问题解决办法 ,破解aspose-words-18.5-jdk16.jar文件,通过JByteMod字节码编辑器,打开jar文件,找到Licese类,然后找到签名验证的方法,把相应方法体清空,注意不能删除。然后删除两个文件。具体参考该网址(Aspose-words 18.8破解过程)
破解过程稍微有些复杂,供学习参考,以下是我破解之后的jar地址可直接使用。
字节码编辑器下载地址以及破解之后jar包地址:
链接: https://pan.baidu.com/s/11pfKrdExccBfWt-4Zijgng 提取码: atgr
相关java代码:
package com.lefancrm.backend.util;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import java.io.*;
public class WordToPDF {
/** * 获取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>0nRuwNEddXwLfXB7pw66G71MS93gW8mNzJ7vuh3Sf4VAEOBfpxtHLCotymv1PoeukxYe31K441Ivq0Pkvx1yZZG4O1KCv3Omdbs7uqzUB4xXHlOub4VsTODzDJ5MWHqlRCB1HHcGjlyT2sVGiovLt0Grvqw5+QXBuinoBY0suX0=</Signature>\n"
+ "</License>";
InputStream license = new ByteArrayInputStream(
licenseStr.getBytes("UTF-8"));
License asposeLic = new License();
asposeLic.setLicense(license);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static Boolean doc2pdf(String inPath,String outPath){
if (!getLicense()){
return false;
}
FileOutputStream os = null;
try {
File file = new File(outPath);
os = new FileOutputStream(file);
Document doc = new Document(inPath);
doc.save(os, SaveFormat.PDF);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
return true;
}
public static void main(String[] args) {
doc2pdf("E:\\mnt\\generate\\report\\cwt83201903131513\\report\\123.doc","E:\\mnt\\generate\\report\\cwt83201903131513\\report\\123.pdf");
}
}
最后一点解决pdf乱码
将windows系统的字体打包复制到liunx系统并安装,最后重启系统服务。
1、查看中文字体
fc-list :lang=zh
2、安装字体
yum -y install fontconfig #安装字体库
yum -y install ttmkfdir mkfontscale #安装字体索引信息
可拷贝Windows的字体目录:C:\Windows\Fonts
3、linux字体目录:/usr/share/fonts,建议创建一个目录mkdir chinese 放中文字体
4、把字体上传到/usr/share/fonts/chinese目录
5、然后在/usr/share/fonts/chinese执行命令,生成字库索引信息
mkfontscale
mkfontdir
6、更新字体缓存
fc-cache
实现效果:
word