无头的LibreOffice在Windows上导出为PDF非常慢(比Linux上慢6倍)。

问题描述 投票:0回答:1

我经常需要用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" 等。

笔记。

  • 作为对比:这里。https:/bugs.documentfoundation.orgshow_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)
    
python pdf docx libreoffice
1个回答
0
投票

事实上,所有的时间都浪费在了开始退出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)])

总共107秒,所以平均每张PDF约107毫秒,好得多了!

注释。

  • 它不工作与10,000个文件,因为命令行参数的长度将超过32k个字符,因为。在此解释

  • 不知道能不能用LibreOffice无头工作时有更多的交互方式。

    • 启动Writer无头,保持它的启动
    • 发出 open test1.docx 在这个过程中
    • 出手 export to pdf,并关闭docx
    • 发出 open test2.docx,然后导出等。
    • ...
    • 退出Writer无头

       

    这与MS Office的COM(组件对象模型)一起工作。使用python将.doc转为pdf 但我想知道LibreOffice是否存在类似的东西。答案似乎是否定的。LibreOfficeOpenOffice支持COM模型吗?

© www.soinside.com 2019 - 2024. All rights reserved.