How to apply new line in docx file generation using DOCX4J

别来无恙 提交于 2019-12-04 08:05:52

The below will code will generate out put as line by line.

Key is here add Text(1) ->paragraph1 and Br ->paragraph1 after Text(2) ->paragraph1

Br is element like Text and P. by using this we can go for new line.

ObjectFactory factory = Context.getWmlObjectFactory();
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
        .createPackage();

P spc = factory.createP();
R rspc = factory.createR();

Text t1 = factory.createText();
t1.setValue("tset");
rspc.getContent().add(t1);
Br br = factory.createBr(); // this Br element is used break the current and go for next line
rspc.getContent().add(br);
Text t2 = factory.createText();
t2.setValue("\r\n tset2");
rspc.getContent().add(t2);

spc.getContent().add(rspc);

wordMLPackage.getMainDocumentPart().addObject(spc);

wordMLPackage.save(new java.io.File("helloworld.docx"));

OUTPUT:

tset

tset2

You can use ObjectFactory.createBr() to create a new line ending.

    ObjectFactory factory = Context.getWmlObjectFactory();

    R run = factory.createR();

    Text text1 = factory.createText();
    text1.setValue("asd");
    run.getContent().add(text1);

    Br nl = factory.createBr();
    run.getContent().add(nl);

    Text text2 = factory.createText();
    text2.setValue("efg");
    run.getContent().add(text2);

    P para = factory.createP();
    para.getParagraphContent().add(run);

    WordprocessingMLPackage wordMLPackage =
            WordprocessingMLPackage.createPackage();
    wordMLPackage.getMainDocumentPart().addObject(para);

    wordMLPackage.getMainDocumentPart().addParagraphOfText("p1");
    wordMLPackage.getMainDocumentPart().addParagraphOfText("p2");

    wordMLPackage.save(new File("test.docx"));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!