How to set Font size and font family in document using docx4j

▼魔方 西西 提交于 2019-12-25 01:44:03

问题


FileReader fr=new FileReader("E://HtmlToDoc//LETTER.html" );
BufferedReader br=new BufferedReader(fr); 
while( (s=br.readLine())!= null ){
    html=html+s;}

html="<html><body>"+html.substring(html.indexOf("<body>"));

/************************ Setting Page Size   **********************************/
Docx4jProperties.getProperties().setProperty("docx4j.PageSize", "B4JIS");
String papersize= Docx4jProperties.getProperties().getProperty("docx4j.PageSize", "B4JIS");

String landscapeString = Docx4jProperties.getProperties().getProperty("docx4j.PageOrientationLandscape", "true");
boolean landscape= Boolean.parseBoolean(landscapeString);

WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage(PageSizePaper.valueOf(papersize), landscape);

AlternativeFormatInputPart afiPart = new AlternativeFormatInputPart(new PartName("/hw.html"));
afiPart.setBinaryData(html.getBytes());
//afiPart.setBinaryData(fileContent);

afiPart.setContentType(new ContentType("text/html"));
Relationship altChunkRel = wordMLPackage.getMainDocumentPart().addTargetPart(afiPart);

// .. the bit in document body
CTAltChunk ac = Context.getWmlObjectFactory().createCTAltChunk();
ac.setId(altChunkRel.getId() );
wordMLPackage.getMainDocumentPart().addObject(ac);

// .. content type
wordMLPackage.getContentTypeManager().addDefaultContentType("html", "text/html");
wordMLPackage.save(new java.io.File("E://HtmlToDoc//" + "test.docx"));

This is my code converts from HTML to Word document. How to set font size and font family for this word document.


回答1:


You're pulling HTML content in to a Word document as a collection of AltChunk instances, which means the HTML exists in the docx 'bundle' as separate file, and not as part of the flow of the actual Word document.

If you want to manipulate the imported content as native MS Word content, you need to import the source XHTML instead. This means that docx4j takes the mark-up and (some) related styles, converting them into the various constituent parts of a docx file (for example, table, text, run and paragraph elements). Once you have content imported in that way, you can style it as you would any other docx entities.



来源:https://stackoverflow.com/questions/27356235/how-to-set-font-size-and-font-family-in-document-using-docx4j

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!