Why is ElementWriter.WriteString() writing to the wrong location of the content stream?

Q:

We have a scenario where we need to insert new operators into an existing PDF page content stream using ElementWriter.WriteString(). The easiest way seems to be to use ElementReader to determine where the insertions need to occur, while also using ElementWriter in e_replacement mode to simply pass through all of the existing operators as-is.

This seems to mostly work, but in some cases the operators we’re trying to insert are not appearing in the sequence that we would expect. For example, we want to write a new operator preceding every existing ET operator:

while ((element = elementReader.Next()) != null)
{
switch (element.GetType())
{
case Element.Type.e_text_end:
elementWriter.WriteString(“test”);
elementWriter.Flush();
break;
}
elementWriter.WriteElement(element);
}

We would expect that this would result in:

(some char codes) Tj
test
ET

But what we’re getting is:

test
(some char codes) Tj
ET

Do you know why the ElementWriter.WriteString() output would end up prior to the preceding text element that was already processed and passed through as-is?

A:

You should call Flush() prior to calling WriteString(“test”). The idea is that Flush() commits any pending writes to the ElementWriter stream (like the “fflush” system call in POSIX).