How to apply a new line in docx file generation using DOCX4J

In the textbooks that I saw. I learned how to add text when creating a docx file. but then every time I add a line of text. I noticed that there is always a space between the first line of text and the second line of text. same as pressing the enter key twice. I know that the main reason is that every time I add a line of text, I use a paragraph. and the paragraph begins with a space after another paragraph.

This is how I add text

ObjectFactory factory;
factory = Context.getWmlObjectFactory();
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
P spc = factory.createP();
R rspc = factory.createR();
rspc.getContent().add(wordMLPackage.getMainDocumentPart().createParagraphOfText("sample"));
spc.getContent().add(rspc);

java.io.InputStream is = new java.io.FileInputStream(file);
wordMLPackage.getMainDocumentPart().addObject(spc);

therefore, this code runs successfully and produces the correct output. but when I add another paragraph. or text. I want it under the first line of text. Is there a way that I can add a simple line of text without using a paragraph? thanks in advance

EDIT: org.docx4j.wml.Text,

Text newtext = factory.createText();
newtext.setValue("sample new text");
wordMLPackage.getMainDocumentPart().addObject(newtext);

, docx, , .

+5
2

, .

(1) → paragraph1 Br → paragraph1 (2) → paragraph1

Br - Text P. , .

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"));

:

TSET

tset2

+7

ObjectFactory.createBr() .

    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"));
+3

All Articles