这里写自定义目录标题
依赖
无法自动引入,去网上下载一个aspose提取码: nnmr
安装到本地maven
First 配置pom文件
second 执行命令:mvn install:install-file -Dfile=C:\Users\ASUS\Desktop\U盘\word转pdf\aspose-words-15.8.0-jdk16.jar -DgroupId=com.aspose -DartifactId=aspose-words -Dversion=15.8.0 -Dpackaging=jar
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>15.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无法找到中文字体,可以在代码里面添加路径指向中文字体文件夹