I often need to export many (> 1000) .docx documents to PDF with LibreOffice. Here is a sample document: test.docx. The following code works but it's quite slow on Windows (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))
# for linux:
# (0.54 seconds on average, so it's 6 times better than on Windows!)
# subprocess.call(['/usr/bin/soffice', '--headless', '--convert-to', 'pdf', '--outdir', '/home/user', 'test%i.docx' % i])
How to speed up this PDF export on Windows?
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.
Notes:
As a comparison: here: https://bugs.documentfoundation.org/show_bug.cgi?id=92274 the export time is said to be either 90ms or 810ms.
soffice.exe
replaced byswriter.exe
: same problem: 3.3 second on averagesubprocess.call(r'C:\Program Files\LibreOffice\program\swriter.exe --headless --convert-to pdf test%i.docx --outdir ."' % i)