# Start Writer first: libreoffice --headless --accept="socket,host=localhost,port=20182;urp;StarOffice.ComponentContext" --norestore --nodefault
# Run with system Python providing python3-uno. Outputs go beside this script.
import uno, zipfile
from pathlib import Path
OUT = Path(__file__).resolve().parent
from com.sun.star.beans import PropertyValue
ctx=uno.getComponentContext()
resolver=ctx.ServiceManager.createInstanceWithContext('com.sun.star.bridge.UnoUrlResolver',ctx)
c=resolver.resolve('uno:socket,host=localhost,port=20182;urp;StarOffice.ComponentContext')
desktop=c.ServiceManager.createInstanceWithContext('com.sun.star.frame.Desktop',c)
def prop(n,v):
 p=PropertyValue(); p.Name=n; p.Value=v; return p
doc=desktop.loadComponentFromURL('private:factory/swriter','_blank',0,(prop('Hidden',True),))
t=doc.Text; cur=t.createTextCursor()
def text(s): t.insertString(cur,s,False)
def para(): t.insertControlCharacter(cur,0,False)
def field(kind,cond,value=None):
 f=doc.createInstance('com.sun.star.text.textfield.'+kind); f.Condition=cond
 if value is not None: f.Content=value
 t.insertTextContent(cur,f,False)
 return f
text('Gate code '); a=field('HiddenText','1','4471 (staff only)'); text('is posted.'); para()
b=field('HiddenParagraph','1'); text('Internal margin is 42%.'); para()
text('Shown field '); f=field('HiddenText','0','visible note'); text(' end.'); para()
field('HiddenParagraph','1'); field('HiddenParagraph','0'); text('Kept mixed paragraph.'); para()
text('Outer ')
frame=doc.createInstance('com.sun.star.text.TextFrame'); frame.Width=5000; frame.Height=1200
from com.sun.star.text.TextContentAnchorType import AS_CHARACTER
frame.AnchorType=AS_CHARACTER; t.insertTextContent(cur,frame,False)
ft=frame.Text; fc=ft.createTextCursor(); h=doc.createInstance('com.sun.star.text.textfield.HiddenParagraph'); h.Condition='1'; ft.insertTextContent(fc,h,False); ft.insertString(fc,'Boxed confidential.',False)
text('stays.')
doc.TextFields.refresh()
for name in ['writer-refreshed']:
 doc.storeAsURL(uno.systemPathToFileUrl(str(OUT / (name+'.odt'))),(prop('FilterName','writer8'),))
 doc.storeToURL(uno.systemPathToFileUrl(str(OUT / (name+'.pdf'))),(prop('FilterName','writer_pdf_Export'),))
# Change conditions without refreshing to test Writer's own saved stale fields.
a.Condition='0'; f.Condition='1'
doc.storeToURL(uno.systemPathToFileUrl(str(OUT / 'writer-unrefreshed.odt')),(prop('FilterName','writer8'),))
doc.close(True)
for n in ['writer-refreshed','writer-unrefreshed']:
 z=zipfile.ZipFile(str(OUT / (n+'.odt'))); s=z.read('content.xml').decode(); print(n,s[s.index('<office:body'):])
doc=desktop.loadComponentFromURL(uno.systemPathToFileUrl(str(OUT / 'writer-refreshed.odt')),'_blank',0,(prop('Hidden',True),))
fields=[]; en=doc.TextFields.createEnumeration()
while en.hasMoreElements():
 x=en.nextElement()
 if x.supportsService('com.sun.star.text.textfield.HiddenText'): fields.append(x)
for x in fields: x.Condition='0' if x.Content=='4471 (staff only)' else '1'
doc.TextFields.refresh()
for x in fields: x.Condition='1' if x.Content=='4471 (staff only)' else '0'
doc.storeToURL(uno.systemPathToFileUrl(str(OUT / 'writer-stale.odt')),(prop('FilterName','writer8'),))
doc.close(True)
doc=desktop.loadComponentFromURL(uno.systemPathToFileUrl(str(OUT / 'writer-stale.odt')),'_blank',0,(prop('Hidden',True),))
doc.TextFields.refresh()
doc.storeToURL(uno.systemPathToFileUrl(str(OUT / 'writer-reopened.pdf')),(prop('FilterName','writer_pdf_Export'),))
doc.close(True)
print(zipfile.ZipFile(str(OUT / 'writer-stale.odt')).read('content.xml').decode().split('<office:body>')[1])
