使用 Python 的 ReportLab 包从大文本文件生成 PDF 文档很慢

问题描述

我有大量文本文件需要转换为 PDF(使用 Python 3.8.5),然后按@R_949_6404@分隔内容。@R_949_6404@在这些文本文件中编码为@H_502_1@表单提要,并在 Python 中用子字符串 \x0c 表示。我能够通过这些表单提要阅读文本并拆分文档。然后,我使用包 reportlab 创建具有正确分页的 PDF。这是我的代码的精简版:

import glob
from reportlab.lib,enums import TA_JUSTIFY
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate,Paragraph,PageBreak,Spacer
from reportlab.lib.styles import getSampleStyleSheet,ParagraphStyle
from reportlab.lib.units import inch

file = glob.glob(wdir + text_folder + "/**/*.txt",recursive=True)
for i in file:
     doc = SimpleDocTemplate(i[:-4] + ".pdf",pagesize=letter,rightmMargin=72,leftMargin=72,topMargin=72,bottomMargin=18)
     f = open(i,encoding='utf-8')
     k = f.read()
     k_breaks = k.split("\x0c")
     Story = []
     styles=getSampleStyleSheet()
     styles.add(ParagraphStyle(name='Justify',alignment=TA_JUSTIFY))
     for j in range(len(k_breaks)):
          ptext='<font size="12">' + k_breaks[j] + '</font>'
          Story.append(Paragraph(ptext,styles["Justify"]))
          Story.append(Spacer(1,12))
          if j != len(k_breaks)-1:
               Story.append(PageBreak())
     doc.build(Story)

通过跟踪,我发现我的代码似乎在线路上遇到了瓶颈

          Story.append(Paragraph(ptext,12))

虽然,这实际上只是大型文本文件(大于 1 或 2 mb)的问题。 100kb 范围内的较小文本文件不会@H_502_1@太慢,但这些较大的文件需要几个小时。完成后,生成的 PDF 将长达数百或数千页。我想减少处理时间。在 reportlab 中是否有更好的方法来执行此操作,或者建议更改方法(可能通过不同的包)?

解决方法

您可以查看 pdfme 库。是python中创建PDF文档最强大的库。

我不知道使用这些大文件是否会更快,但您可以尝试检查以下代码:

import glob
from pdfme import build_pdf

file = glob.glob(wdir + text_folder + "/**/*.txt",recursive=True)
for i in file:
     f = open(i,encoding='utf-8')
     k = f.read()
     k_breaks = k.split("\x0c")
     sections = [{"content": [k_break]} for k_break in k_breaks]
     with open(i[:-4] + ".pdf",'wb') as f:
         build_pdf({
             "style": {"s": 12,"text_aling": "j"},"page_style": {"page_size": "letter","margin": [72,72,18,72]},"sections": sections
         },f)

检查文档 here