Headless LibreOffice 在 Windows 上导出为 PDF 非常慢(比 Linux 慢 6 倍)

Headless LibreOffice very slow to export to PDF on Windows (6 times slow than on Linux)

我经常需要使用 LibreOffice 将许多 (> 1000) .docx 文档导出为 PDF。这是一个示例文档:test.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"

备注:

确实,所有时间都浪费在 starting/quitting LibreOffice 上了。我们可以在 soffice.exe:

的一次调用 中传递许多 docx 文档
import subprocess, docx
for i in range(1000):
    doc = docx.Document('test.docx')
    for paragraph in doc.paragraphs:
        paragraph.text = paragraph.text.replace('{{num}}', str(i))
    doc.save('test%i.docx' % i)

# all PDFs in one pass:
subprocess.call(['C:\Program Files\LibreOffice\program\swriter.exe', 
    '--headless', '--convert-to', 'pdf', '--outdir', '.'] + ['test%i.docx' % i for i in range(1000)])

总共 107 秒,因此每个 PDF 的平均时间约为 107 毫秒,好多了!

备注:

  • 它不适用于 10,000 个文档,因为命令行参数的长度将超过 32k 个字符,如 explained here

  • 我想知道是否可以通过一种更具交互性的方式来无头地使用 LibreOffice:

    • 启动 Writer headless,保持启动状态
    • 向此进程发送类似 open test1.docx 的操作
    • 发送操作 export to pdf,并关闭 docx
    • 发送open test2.docx,然后导出等
    • ...
    • 无头退出 Writer

    这适用于 COM(组件对象模型)和 MS Office:.doc to pdf using python but I wonder if something similar exists with LibreOffice. The answer seems to be no: Does LibreOffice/OpenOffice Support the COM Model