从本地文件读取word,word本身字体是仿宋,读取之后怎么将整个word 文字设置为宋体或自定义的某个字体呢?
在后续保存为pdf 时如何指定字体?可以加载系统字体吗?
String inputFile="data/Template_Docx_1.docx";
String outputFile="output/setFont.docx";
String fontFile="data/PT_Serif-Caption-Web-Regular.ttf";
Document doc = new Document();
doc.loadFromFile(inputFile);
//设置字体和大小
CharacterFormat format = new CharacterFormat(doc);
format.setFontName("宋体");
format.setFontSize(16);
//设置自定义字体
CharacterFormat customFormat = new CharacterFormat(doc);
//允许在word文档中嵌入字体
doc.setEmbedFontsInFile(true);
//嵌入自定义字体在word文档中
doc.getPrivateFontList().add(new PrivateFontPath("PT Serif Caption",fontFile));
customFormat.setFontName("PT Serif Caption");
customFormat.setFontSize(16);
//遍历文档每个section
for (int i = 0; i < doc.getSections().getCount(); i++) {
Section section = doc.getSections().get(i);
//遍历section的每个段落
for (int k = 0; k < section.getBody().getParagraphs().getCount(); k++) {
Paragraph paragraph = section.getParagraphs().get(k);
//遍历段落的每个子对象
for (int j = 0; j < paragraph.getChildObjects().getCount(); j ++)
{
if ( paragraph.getChildObjects().get(j) instanceof TextRange)
{
TextRange tr = (TextRange) paragraph.getChildObjects().get(j);
//Apply character format
tr.applyCharacterFormat(format);
}
}
}
}
//保存文档
doc.saveToFile(outputFile, FileFormat.Docx);
String inputFile="data/convertedTemplate.docx";
String fontFile="data/PT_Serif-Caption-Web-Regular.ttf";
String outputFile="output/embedNoninstalledFonts.pdf";
Document document = new Document();
document.loadFromFile(inputFile);
//嵌入字体到pdf文档中
ToPdfParameterList parms = new ToPdfParameterList();
List<PrivateFontPath> fonts = new ArrayList<PrivateFontPath>();
fonts.add(new PrivateFontPath("PT Serif Caption", fontFile));
parms.setPrivateFontPaths(fonts);
//保存文档
document.saveToFile(outputFile, parms);