Docx4j 在页眉同时 添加logo图片和文字,logo图片显示在左边,文字显示在右边

    xiaoxiao2021-03-25  197

    Docx4j在页眉 同时加入图片和文字有两种实现方式,一种是用HTML写一个模板,通过模板一次加入,另一种是通过docx4j直接操作

    一、Html方式 上代码

    public class Docx4JSample {

       

        public static void main(String []args) throws Exception{

        Docx4JSample docx4jSample = new Docx4JSample();

        

        WordprocessingMLPackage worMLPackage = docx4jSample.createWordpreocessMLPackage();

        

        MainDocumentPart mpart = worMLPackage.getMainDocumentPart();

        

        ObjectFactory factory = Context.getWmlObjectFactory();

        

        Relationship relationship1 = docx4jSample.createHeaderPart(worMLPackage, mpart

        factory, true, "3");

        

        docx4jSample.createHeaderReference(worMLPackage, mpart, factory, relationship1);

        

        docx4jSample.saveWordPackage(worMLPackage, new File("./testpaper.docx"));

        }

        

        public void createHeaderReference(WordprocessingMLPackage wordprocessingMLPackage,MainDocumentPart t,

        ObjectFactory factory, Relationship relationship) throws Exception{

        List<SectionWrapper> sections = wordprocessingMLPackage.getDocumentModel().getSections();

        SectPr sectPr =sections.get(sections.size()-1).getSectPr();

        if (sectPr == null ){

        sectPr = factory.createSectPr();

        t.addObject(sectPr);    

        sections.get(sections.size()-1).setSectPr(sectPr);

        }

        

        HeaderReference headerReference = factory.createHeaderReference();

        headerReference.setId(relationship.getId()); //这里关联RelationShip

        headerReference.setType(HdrFtrRef.DEFAULT);

        sectPr.getEGHdrFtrReferences().add(headerReference);

        }

       //创建页眉    

        public Relationship createHeaderPart(WordprocessingMLPackage wordprocessingMLPackage,

        MainDocumentPart mpartDocumentPart , ObjectFactory factory , boolean isUnderLine ,

        String underLineSize) throws Exception{

        HeaderPart headerPart = new HeaderPart();

        

        Relationship relationship = mpartDocumentPart.addTargetPart(headerPart);

        String headerString="<html><body  width=\"90%\"><table width=\"100%\">    <tr width=\"20%\">    "

        + "<th align=\"left\"><img width=40 height=40 src=\"https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/"

        + "static/superman/img/logo/bd_logo1_31bdc765.png\"></th><th align=\"right\">"

        + "页眉右边的文字<br>这里还可以起一行</th>    </tr>    </table></body></html>";

            headerPart.addAltChunk(AltChunkType.Xhtml, headerString.getBytes());

        return relationship;

        }

        public void saveWordPackage(WordprocessingMLPackage wordPackage , File file) throws Exception{

    wordPackage.save(file);

        }

    }

    结果如下:

    另一种方式 见下一篇文章

    转载请注明原文地址: https://ju.6miu.com/read-9695.html

    最新回复(0)