使用Spire.Doc for Java转换Word文档到PDF时,Word文档中应用到的安装字体会被自动嵌入PDF文档;若Word文档应用了非安装字体,则该字体不会被自动嵌入PDF文档。这就容易造成转换前后效果不一致,甚至出现乱码。为了避免这个问题,我们需要将Word文档中应用到的非安装字体嵌入转换后的PDF文档。
import com.spire.doc.Document;
import com.spire.doc.PrivateFontPath;
import com.spire.doc.ToPdfParameterList;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.TextRange;
import java.util.*;
public class EmbedPrivateFontInConvertedPDF {
public static void main(String[] args) {
//创建Document对象
Document document = new Document(false);
//添加段落
Paragraph paragraph = document.addSection().addParagraph();
//初始化PrivateFontPath对象,指定私有字体路径
PrivateFontPath fontPath = new PrivateFontPath("方正手迹-乾坤体","C:\\Users\\Administrator\\Desktop\\Fzsj.ttf");
//添加文本到段落
TextRange tr = paragraph.appendText("Spire.Doc for Java是一款专门对Word文档进行操作的Java类库。"+
"这款控件的主要功能在于帮助开发人员轻松快捷高效地创建、编辑、转换和打印Microsoft Word文档。");
//应用字体
tr.getCharacterFormat().setFontName("方正手迹-乾坤体");
tr.getCharacterFormat().setFontSize(18f);
//创建ToPdfParameterList对象,用于设置Word转PDF的参数
ToPdfParameterList toPdfParameterList = new ToPdfParameterList();
//将私有字体作为Word转PDF的参数之一
List pathList = new LinkedList<>();
pathList.add(fontPath);
toPdfParameterList.setPrivateFontPaths(pathList);
//将Word文档保存为PDF
document.saveToFile("output/EmbedFont.pdf",toPdfParameterList);
}
}