I often need to export many (> 1000) .docx documents to PDF with LibreOffice. The following code works but it’s quite slow (3.3 seconds on average for each PDF document):
import subprocess, docx, time # first do: pip install python-docx
for i in range(10):
doc = docx.Document('test.docx')
for paragraph in doc.paragraphs:
paragraph.text = paragraph.text.replace('{{num}}', str(i))
doc.save('test%i.docx' % i) # these 4 previous lines are super fast - a few ms
t0 = time.time()
subprocess.call(r'C:\Program Files\LibreOffice\program\soffice.exe --headless --convert-to pdf test%i.docx --outdir . --nocrashreport --nodefault --nofirststartwizard --nolockcheck --nologo --norestore"' % i)
print('PDF generated in %.1f sec' % (time.time()-t0))
How to speed up this PDF export?
I suspect much time to be wasted on "Start LibreOffice/Writer, (do the job), Close LibreOffice"
"Start LibreOffice/Writer, (do the job), Close LibreOffice"
"Start LibreOffice/Writer, (do the job), Close LibreOffice"
etc.
As a comparison: here: https://bugs.documentfoundation.org/show_bug.cgi?id=92274 the export time is said to be either 90ms or 810ms.