code: protected void insertAtPreferredLocation(Element parent, Element child, Counter counter)
     {
        int contentIndex = 0;
        int elementCounter = 0;
        Iterator it = parent.getContent().iterator();
        Text lastText = null;
        int offset = 0;
        while (it.hasNext() && (elementCounter <= counter.getCurrentIndex()))
        {
           Object next = it.next();
           offset = offset + 1;
           if (next instanceof Element)
           {
              elementCounter = elementCounter + 1;
              contentIndex = contentIndex + offset;
              offset = 0;
           }
           if ((next instanceof Text) && it.hasNext())
           {
              lastText = (Text) next;
           }
        }
        if ((lastText != null) && (lastText.getTextTrim().length() == 0))
        {
           lastText = (Text) lastText.clone();
        }
        else
        {
           StringBuilder starter = new StringBuilder(lineSeparator);
           for (int i = 0; i < counter.getDepth(); i++)
           {
              starter.append("  "); // TODO make settable?
           }
           lastText = factory.text(starter.toString());
        }
        if (parent.getContentSize() == 0)
        {
           Text finalText = (Text) lastText.clone();
           finalText.setText(finalText.getText().substring(0, finalText.getText().length() - "  ".length()));
           parent.addContent(contentIndex, finalText);
        }
        parent.addContent(contentIndex, child);
        parent.addContent(contentIndex, lastText);
     }
docs: Method insertAtPreferredLocation.
  
  @param parent
  @param counter
  @param child