我经常需要使用 LibreOffice 将许多(> 1000).docx 文档导出为 PDF。这是一个示例文档:测试.docx。以下代码可以工作,但在 Windows 上速度相当慢(每个 PDF 文档平均 3.3 秒):
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])
如何在 Windows 上加快 PDF 导出速度?
我怀疑浪费了很多时间"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:
作为比较:这里:https://bugs.documentfoundation.org/show_bug.cgi?id=92274据说导出时间为 90ms 或 810ms。
-
soffice.exe
取而代之swriter.exe
:同样的问题:平均3.3秒
subprocess.call(r'C:\Program Files\LibreOffice\program\swriter.exe --headless --convert-to pdf test%i.docx --outdir ."' % i)