如何使用DOCX4J在docx文件生成中应用新行 [英] How to apply new line in docx file generation using DOCX4J
问题描述
通过我看过的教程。我学会了如何在生成docx文件时添加文本。但是每次我添加一行文字。我注意到第一行文本和第二行文本之间总是有一个空格。就像两次输入回车键一样。我知道主要原因是每次我添加一行文字,我都会使用一个段落。并且段落以另一段后面的空格开头。
By the tutorials that I have seen. I learned how to add text on generating 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. just like hitting the enter key twice. I know that the main cause is that everytime I add a line of text, I use a paragraph. and a paragraph starts with a space after another paragraph.
这是我添加文本的方式
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);
因此此代码成功运行并产生正确的输出。但是当我添加另一段时。或文字。我希望它只是在第一行文本之下。有没有办法,我可以添加一个简单的文本行而不使用段落?提前谢谢
so this code successfully runs and produces the right output. but when i add another paragraph. or text. i want it to be just under the first line of text. is there any way that i can add a simple line of text without using a paragraph? thanks in advance
编辑:我也尝试添加这样的简单org.docx4j.wml.Text
I've also tried adding a simple org.docx4j.wml.Text like this
Text newtext = factory.createText();
newtext.setValue("sample new text");
wordMLPackage.getMainDocumentPart().addObject(newtext);
程序将运行但是当我打开生成的docx文件时,它只会提示一条消息说内容有问题。
the program will run but when i open the generated docx file, it will just prompt a message saying that there are problem with the contents.
推荐答案
以下代码将逐行生成输出。
The below will code will generate out put as line by line.
Key在这里添加Text(1) - > paragraph1和Br - > paragraph1在Text(2)之后 - > paragraph1
Key is here add Text(1) ->paragraph1 and Br ->paragraph1 after Text(2) ->paragraph1
Br
是 Text
和 P
之类的元素。通过使用它我们可以去换行。
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"));
输出:
tset
tset2
这篇关于如何使用DOCX4J在docx文件生成中应用新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!