docx4j学习笔记(3)

时间:2022-09-03 06:40:28

下面是一个获取本地所有字体,然后写入docx文件的例子。

不过看起来没有什么实用价值。

package me.test.docx4j;

import java.io.File;
import java.util.Map;

import org.docx4j.fonts.PhysicalFont;
import org.docx4j.fonts.PhysicalFonts;
import org.docx4j.jaxb.Context;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.wml.Body;
import org.docx4j.wml.Document;
import org.docx4j.wml.ObjectFactory;
import org.docx4j.wml.P;
import org.docx4j.wml.R;
import org.docx4j.wml.RFonts;
import org.docx4j.wml.RPr;
import org.docx4j.wml.Text;
import org.junit.Test;
/**
* 扫描所有的本地字体,并且用把字体英文名称写入docx文件。
*
*/
public class DocxWithAllPhysicalFonts {
@Test
public void doTest() throws Exception {
//扫描所有的字体文件
PhysicalFonts.discoverPhysicalFonts();
//获得所有的字体文件
Map<String, PhysicalFont> fonts = PhysicalFonts.getPhysicalFonts();

WordprocessingMLPackage pkg = WordprocessingMLPackage.createPackage();
MainDocumentPart main = pkg.getMainDocumentPart();
Document doc = main.getContents();
Body body = doc.getBody();

ObjectFactory factory = Context.getWmlObjectFactory();

for(String filename : fonts.keySet()) {
PhysicalFont font = fonts.get(filename);
P p = factory.createP();
R r = factory.createR();
RPr rpr = factory.createRPr();
RFonts rf = factory.createRFonts();
rf.setAscii(font.getName());
rf.setCs(font.getName());
rf.setHAnsi(font.getName());
rpr.setRFonts(rf);
r.setRPr(rpr);

Text t = factory.createText();
t.setValue(font.getName());
r.getContent().add(t);
p.getContent().add(r);
body.getContent().add(p);
}

pkg.save(new File(System.getProperty("user.dir"), "All Physical Fonts.docx"));
}
}