向Docx4j生成的word文档中添加布局--第二部分

原文标题:Adding layout to your Docx4j-generated word documents, part 2

原文链接:http://blog.iprofs.nl/2012/11/19/adding-layout-to-your-docx4j-generated-word-documents-part-2/

原文作者:lvdpal

发表日期:2012年11月19日

注:我没有再试着翻译代码中的注释,因为我觉得我水平实在有限,翻译过来的注释还不如看英文来地明白...



在前面发表的两篇博客中,我写了一些关于在docx文档中创建表格和添加图像和布局的内容。本篇博客中我将继续介绍一些文档布局相关的示例:

  1. 更改默认样式
  2. 添加页眉或者页脚
  3. 在页脚添加页码

更改默认样式


几乎所有的客户都想要他们自己的风格。Word提供了一些默认的样式但它们不够好(注意一下我没有更改两个图像之间的文本,因此图像中的文本并不反映实际的风格):

大多数客户会想改变这些风格,在应用了我们在本例中创建的风格之后,上面的word文档看起来会像这样:

public class ChangingTheStyleSheet {
    private static WordprocessingMLPackage  wordMLPackage;
 
    /**
     *  First we create the package, then we alter the style sheet and add some
     *  styled paragraphs. Finally we save the package.
     */
    public static void main (String[] args) throws Docx4JException {
        wordMLPackage = WordprocessingMLPackage.createPackage();
        alterStyleSheet();
 
        wordMLPackage.getMainDocumentPart().addStyledParagraphOfText("Title",
            "Hello World! This title is now in Arial.");
        wordMLPackage.getMainDocumentPart().addStyledParagraphOfText("Subtitle",
            "Subtitle, this subtitle is now Arial too");
        wordMLPackage.getMainDocumentPart().addStyledParagraphOfText("Heading1",
            "As is Heading1");
        wordMLPackage.getMainDocumentPart().addStyledParagraphOfText("Heading2",
            "Heading2 is now Arial, no longer bold and has an underline " +
            "and fontsize 12");
        wordMLPackage.getMainDocumentPart().addStyledParagraphOfText("Heading3",
            "Heading3 is now Arial");
        wordMLPackage.getMainDocumentPart().addStyledParagraphOfText("Normal",
            "And normal text has changed to Arial and fontsize 10");
 
        wordMLPackage.save(new java.io.File("src/main/files/HelloWord12.docx") );
    }
 
    /**
     *  This method alters the default style sheet that is part of each document.
     *
     *  To do this, we first retrieve the style sheet from the package and then
     *  get the Styles object from it. From this object, we get the list of actual
     *  styles and iterate over them.
     *  We check against all styles we want to alter and apply the alterations if
     *  applicable.
     *
     *  @param wordMLPackage
     */
    public static void alterStyleSheet() {
        StyleDefinitionsPart styleDefinitionsPart =
            wordMLPackage.getMainDocumentPart().getStyleDefinitionsPart();
        Styles styles = styleDefinitionsPart.getJaxbElement();
 
        List