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

Bas*_*asj 2 python pdf docx libreoffice

我经常需要使用 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])  
Run Code Online (Sandbox Code Playgroud)

如何在 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"等等上了。

笔记:

Bas*_*asj 5

事实上,所有时间都浪费在启动/退出 LibreOffice 上。我们可以在一次调用中传递许多 docx 文档soffice.exe

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)])
Run Code Online (Sandbox Code Playgroud)

总共 107 秒,因此每个 PDF 平均需要约 107 毫秒,要好得多!

笔记:

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

  • 我想知道是否可以有一种更具交互性的方式来使用 LibreOffice headless:

    • 开始作家无头,保持它开始
    • open test1.docx向此进程发送类似的操作
    • 发送操作export to pdf,并关闭 docx
    • 发送open test2.docx,然后导出等
    • ...
    • 退出无头作家

       

    这适用于 MS Office 的 COM(组件对象模型):使用 python 将 .doc 转换为 pdf,但我想知道 LibreOffice 是否存在类似的东西。答案似乎是否定的:LibreOffice/OpenOffice 是否支持 COM 模型

  • 您可以将 LibreOffice 作为服务启动并使用它,而无需启动/退出时间。https://github.com/unoconv/unoserver (2认同)