Using DocumentBuild to insert Html and Paragraph

Hi,
I’m trying to make a Word document out of Html strings and Strings representing section titles.
I am having issue with out of order writings

My code from below generates example.docx (11 KB)

for (Section section : req.getSections())
{
    if (section.isShowTitle())
    {
        LOG.info("adding title");
        builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.TITLE);
        builder.writeln(section.getTitle());

    }
    LOG.info("adding html");
    builder.insertHtml(section.getHtmlContent());
}

I would expect document to have form:
Title
html body
title 2
html body 2
Can you please help me and provide me the code that I should use for my use case.

Thanks,
Kind regards
Uros

@velicko91 Please check the following code. It produces the output you described:

DocumentBuilder builder = new DocumentBuilder();
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.TITLE);
builder.writeln("Title");
builder.insertHtml("<p>html body</p>");
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.TITLE);
builder.writeln("title 2");
builder.insertHtml("<p>html body 2</p>");

Hi @Konstantin.Kornilov, I tested your code and it works, it creates desired result. I’m really not sure why for loop creates different result…
This is definition of Section class:

public class Section {
      private  String title;
      private  boolean showTitle;
      private  String htmlContent; 
}

And this is test data I’m trying in the test…

List<Section> ss = new ArrayList<>();
ss.add(new Section("Title 1", true, 0, html1));
ss.add(new Section("Title 2", true, 0, html2));

I have no idea how come this doesn’t work with loop and why the document is written differently.
Can you please test it out with for loop?

@velicko91 Unfortunately, the problem is still not reproducible on our side. Here is a simple code I have used for testing:

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
for (int i = 0; i < 10; i++)
{
    builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.TITLE);
    builder.writeln("Title " + i);
    builder.insertHtml("<p>html body of " + i + " section.</p>");
}
doc.save("C:\\Temp\\out.docx");