Docx4j 简单操作文字图片(包含页眉页脚和主体内容)

docx4j官方提供了一些例子 - v3.2.2,本文只是其中一部分应用的简单例子。

需要注意的地方是页眉和页脚,必须创建对应关系才能起作用。

页眉和页脚添加图片的时候,调用的createImagePart方法必须用包含sourcePart参数的,带这个参数的方法会创建图片的对应关系,否则就会出现页眉页脚看不到图片的情况。

基本上掌握了图片和页眉页脚后,其他的都没什么难的,更多的用法可以参考官方的例子。

下面是完整代码例子,具体说明看注释:

import org.docx4j.dml.wordprocessingDrawing.Inline;
import org.docx4j.jaxb.Context;
import org.docx4j.model.structure.SectionWrapper;
import org.docx4j.openpackaging.exceptions.InvalidFormatException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.Part;
import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage;
import org.docx4j.openpackaging.parts.WordprocessingML.FooterPart;
import org.docx4j.openpackaging.parts.WordprocessingML.HeaderPart;
import org.docx4j.relationships.Relationship;
import org.docx4j.wml.*;

import java.io.File;
import java.util.List;

/**
 * @author liuzh
 */
public class Docx4jTest {

    public static void main(String[] args) throws Exception {
        //创建一个word
        //读取可以使用WordprocessingMLPackage.load方法
        WordprocessingMLPackage word = WordprocessingMLPackage.createPackage();
        String imageFilePath = Docx4jTest.class.getResource("/lw.jpg").getPath();

        //创建页眉
        HeaderPart headerPart = createHeader(word);
        //页眉添加图片
        headerPart.getContent().add(newImage(word, headerPart, imageFilePath));

        //创建页脚
        FooterPart footerPart = createFooter(word);
        //添加图片
        footerPart.getContent().add(newImage(word, footerPart, imageFilePath));

        //主内容添加文本和图片
        word.getMainDocumentPart().getContent().add(newText("https://mybatis.io"));
        word.getMainDocumentPart().getContent().add(newText("http://blog.csdn.net/isea533"));

        word.getMainDocumentPart().getContent().add(
                newImage(word, word.getMainDocumentPart(), imageFilePath));

        //保存
        word.save(new File("d:/1.docx"));
    }

    private static final ObjectFactory factory = Context.getWmlObjectFactory();

    /**
     * 创建一段文本
     *
     * @param text
     * @return
     */
    public static P newText(String text){
        P p = factory.createP();
        R r = factory.createR();
        Text t = new Text();
        t.setValue(text);
        r.getContent().add(t);
        p.getContent().add(r);
        return p;
    }

    /**
     * 创建包含图片的内容
     *
     * @param word
     * @param sourcePart
     * @param imageFilePath
     * @return
     * @throws Exception
     */
    public static P newImage(WordprocessingMLPackage word,
                             Part sourcePart,
                             String imageFilePath) throws Exception {
        BinaryPartAbstractImage imagePart = BinaryPartAbstractImage
                .createImagePart(word, sourcePart, new File(imageFilePath));
        //随机数ID
        int id = (int) (Math.random() * 10000);
        //这里的id不重复即可
        Inline inline = imagePart.createImageInline("image", "image", id, id * 2, false);

        Drawing drawing = factory.createDrawing();
        drawing.getAnchorOrInline().add(inline);

        R r = factory.createR();
        r.getContent().add(drawing);

        P p = factory.createP();
        p.getContent().add(r);

        return p;
    }

    /**
     * 创建页眉
     *
     * @param word
     * @return
     * @throws Exception
     */
    public static HeaderPart createHeader(
            WordprocessingMLPackage word) throws Exception {
        HeaderPart headerPart = new HeaderPart();
        Relationship rel = word.getMainDocumentPart().addTargetPart(headerPart);
        createHeaderReference(word, rel);
        return headerPart;
    }

    /**
     * 创建页眉引用关系
     *
     * @param word
     * @param relationship
     * @throws InvalidFormatException
     */
    public static void createHeaderReference(
            WordprocessingMLPackage word,
            Relationship relationship )
            throws InvalidFormatException {
        List<SectionWrapper> sections = word.getDocumentModel().getSections();

        SectPr sectPr = sections.get(sections.size() - 1).getSectPr();
        // There is always a section wrapper, but it might not contain a sectPr
        if (sectPr==null ) {
            sectPr = factory.createSectPr();
            word.getMainDocumentPart().addObject(sectPr);
            sections.get(sections.size() - 1).setSectPr(sectPr);
        }
        HeaderReference headerReference = factory.createHeaderReference();
        headerReference.setId(relationship.getId());
        headerReference.setType(HdrFtrRef.DEFAULT);
        sectPr.getEGHdrFtrReferences().add(headerReference);
    }

    /**
     * 创建页脚
     *
     * @param word
     * @return
     * @throws Exception
     */
    public static FooterPart createFooter(WordprocessingMLPackage word) throws Exception {
        FooterPart footerPart = new FooterPart();
        Relationship rel = word.getMainDocumentPart().addTargetPart(footerPart);
        createFooterReference(word, rel);
        return footerPart;
    }

    /**
     * 创建页脚引用关系
     *
     * @param word
     * @param relationship
     * @throws InvalidFormatException
     */
    public static void createFooterReference(
            WordprocessingMLPackage word,
            Relationship relationship )
            throws InvalidFormatException {
        List<SectionWrapper> sections = word.getDocumentModel().getSections();

        SectPr sectPr = sections.get(sections.size() - 1).getSectPr();
        // There is always a section wrapper, but it might not contain a sectPr
        if (sectPr==null ) {
            sectPr = factory.createSectPr();
            word.getMainDocumentPart().addObject(sectPr);
            sections.get(sections.size() - 1).setSectPr(sectPr);
        }
        FooterReference footerReference = factory.createFooterReference();
        footerReference.setId(relationship.getId());
        footerReference.setType(HdrFtrRef.DEFAULT);
        sectPr.getEGHdrFtrReferences().add(footerReference);
    }
}

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

isea533

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值