天天看点

Java word aspose(3.7 word生成常规的页眉页脚)

作者:EYE33

1 实现方法

/**
     * 常规页眉页脚
     * @return
     */
    @SneakyThrows
    @PostMapping("normalHeaderFooter")
    public Ret normalHeaderFooter(){
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        for (int i = 1; i <= 6; i++) {
            builder.writeln("第"+ i +"页");
            builder.insertBreak(BreakType.PAGE_BREAK);
        }

        //设置页眉
        HeaderFooter header = new HeaderFooter(doc, HeaderFooterType.HEADER_PRIMARY);
        doc.getFirstSection().getHeadersFooters().add(header);
        Paragraph headerParagraph = new Paragraph(doc);
        headerParagraph.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
        //设置文字
        headerParagraph.appendChild(this.getDefautlHeaderFooterRun(doc,"XXX文档"));
        header.appendChild(headerParagraph);
        //word节点结构:详见文章:Java word读取/导出/修改 最强工具 aspose(1.2初识word与aspose对象)
        //一共Paragraph 可以由Run 或者 Shape 组成

        //设置页脚
        HeaderFooter footer = new HeaderFooter(doc, HeaderFooterType.FOOTER_PRIMARY);
        doc.getFirstSection().getHeadersFooters().add(footer);
        Paragraph footerParagraph = new Paragraph(doc);
        footerParagraph.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
        //设置页码
        footerParagraph.appendChild(this.getDefautlHeaderFooterRun(doc,"第 "));
        footerParagraph.appendField(FieldType.FIELD_PAGE,true);//当前页
        footerParagraph.appendChild(this.getDefautlHeaderFooterRun(doc," 页,共 "));
        footerParagraph.appendField(FieldType.FIELD_NUM_PAGES,true);//总页数
        footerParagraph.appendChild(this.getDefautlHeaderFooterRun(doc," 页 "));
        footer.appendChild(footerParagraph);

        doc.save("C:/Users/Administrator/Desktop/aspose/常规页眉页脚.docx", SaveFormat.DOCX);
        return Ret.success();
    }

 /**
     * 设置默认的run对象 用于页眉页脚 宋体 小五
     * 字号 与 字体大小数值的对应关系 初号=42 小初=36 一号=26 小一=24 二号=22 小二=18 三号=16 小三=15 四号=14 小四=12 五号=10.5 小五=9 六号=7.5 小六=6.5 七号=5.5 八号=5
     * @param doc
     * @param text
     * @return
     */
    @SneakyThrows
    private Run getDefautlHeaderFooterRun(Document doc,String text){
        Run run = new Run(doc);
        Font font = run.getFont();
        font.setName("宋体");
        font.setSize(9);//小五
        run.setText(text);
        return run;
    }           

2 实现效果

Java word aspose(3.7 word生成常规的页眉页脚)