word转pdf文档乱码问题解决

我们在使用com.aspose.words进行word转pdf时,可能会因为服务器环境问题导致乱码。

我们可以使用如下代码自定义字体解决乱码问题,需要事先准备好中文字体文件,将其放置子特定目录下,下面是完整的工具类,欢迎大家测试:

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import com.aspose.words.Document;

import com.aspose.words.FontSettings;

import com.aspose.words.SaveFormat;

public class Word2PdfUtil {

/**

* 原始方法

* @Title: doc2pdf   

* @Description: TODO(描述这个方法的作用)   

* @param: @param inPath

* @param: @param outPath      

* @return: void      

* @throws

*/

public static void doc2pdf(String inPath, String outPath) {

//默认使用此方法进行pdf转换,需要的字体放置在这里

doc2pdf("/usr/share/fonts/chinese", inPath, outPath);

}

/**

* @Title: doc2pdf   

* @Description: TODO(兼容原始方法)   

* @param: @param fontsPath 字体文件目录。使用此方法必须设定

* @param: @param inPath

* @param: @param outPath      

* @return: void      

* @throws

*/

public static void doc2pdf(String fontsPath,String inPath, String outPath) {

FileOutputStream os = null;

try {

// 新建一个空白pdf文档

File file = new File(outPath);

os = new FileOutputStream(file);

Document doc = new Document(inPath);

if(System.getProperty("os.name").toLowerCase().indexOf("win")<0) {

FontSettings.setFontsFolder(fontsPath, false);

}

//SaveFormat可设置为其他,如jpg,文件后缀需要对应修改

doc.save(os, SaveFormat.PDF);

} catch (Exception e) {

e.printStackTrace();

} finally {

if (os != null) {

try {

os.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

}

需要引入的包:

                <!-- word转pdf依赖 -->

<dependency>

<groupId>com.aspose.words</groupId>

<artifactId>aspose-words-jdk16</artifactId>

<version>${aspose.words.jdk16.version}</version>

</dependency>


爆款云服务器s6 2核4G 低至0.46/天,具体规则查看活动详情Blog Img