Docx4j 簡單操作文字圖片(包含頁首頁尾和主體內容)

isea533發表於2015-11-12

docx4j官方提供了一些例子,本文只是其中一部分應用的簡單例子。

需要注意的地方是頁首和頁尾,必須建立對應關係才能起作用。

頁首和頁尾新增圖片的時候,呼叫的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("http://www.mybatis.tk"));
        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);
    }
}

相關文章