Insert empty paragraph using insertHtml

783 views Asked by At

I try to fill a document in aspose words java (v.20.6) using DocumentBuilder and insertHtml. But when i insert empty paragraphs they are ignored in word. Is it not possible to insert empty paragraphs with insertHtml?

Example:

Document doc = new Document("tmp.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.moveToBookmark("Text", false, false);
builder.insertHtml("<p>Before empty paragraph</p><p></p><p>After empty paragraph</p>", true);
doc.save("C:/TMP/doc.docx");
1

There are 1 answers

2
Alexey Noskov On BEST ANSWER

Empty paragraphs in HTML are ignored by Aspose.Words to mimic MS Word and browsers behavior. If you open the following HTML in any browser you will not see an empty paragraph.

<html>
<body>
    <p>Before empty paragraph</p><p></p><p>After empty paragraph</p>
</body>
</html>

Also, if you open it in MS Word you will notice that there is no empty paragraph too. enter image description here

But if add non-breaking space, the empty paragraph is there. enter image description here

So there are two options to keep an empty paragraph, either put non-breaking space into the empty paragraph in your HTML string

builder.insertHtml("<p>Before empty paragraph</p><p>&nbsp;</p><p>After empty paragraph</p>", true);

or use DocumentBuilder.writeln method

builder.insertHtml("<p>Before empty paragraph</p>", true);
builder.writeln();
builder.insertHtml("<p>After empty paragraph</p>", true);