1

在搜索和阅读不同的论坛帖子之后,我想我现在可以在这里发布我的问题。

我正在生成一个 pdf 文件,其中包含一个大表格和表格末尾的一些文本。我有一个源文件(.txt)格式。源文件中的每一行在 pdf 文件的表格中构成一行。

我有一个脚本,当源文件很小时,它工作得很好。

import sys
import datetime
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, Table, TableStyle, Frame
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.rl_config import defaultPageSize
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.units import inch
from reportlab.lib import utils, colors
from reportlab.lib.enums import TA_JUSTIFY, TA_LEFT, TA_CENTER

def go():
    doc=SimpleDocTemplate(filePath+".pdf", rightMargin=0.35*inch,leftMargin=0.35*inch, topMargin=1.2*inch, bottomMargin=0.6*inch)
    story=[Spacer(1,0.15*inch)]
    # Title table
    tdata=[[Paragraph("<b>Title of the table</b>",styleBH),Paragraph(" ",styleBH)]]
    title=Table(tdata,colWidths=[6.25*inch,inch])
    story.append(title)
    story.append(Spacer(1,0.1*inch))
    #result table
    data=generateData(sourceFile)
    t=Table(data,colWidths[1.35*inch,1.35*inch,inch,0.8*inch,0.8*inch,1.60*inch],repeatRows=1)
    table_style=[('ALIGN',(0,0),(-1,-1),'CENTER'),
    ('VALIGN',(0,0),(-1,-1),'MIDDLE'),
    ('BACKGROUND',(0,0),(6,0),"#b47c42"),
    ('INNERGRID',(0,0),(-1,-1),0.25,colors.black),
    ('BOX',(0,0),(-1,-1),0.25,colors.black)]
    for i in range(1,len(data)):
        if i%2==0:
            table_style.append(('BACKGROUND',(0,i),(6,i),"#FAEBD7"))
    t.setStyle(TableStyle(table_style))
    story.append(t)
    story.append(Spacer(1,0.3*inch))
    story.append(Spacer(1,0.3*inch))
    #cit text
    hcit=Paragraph("<font size=13><b>my text comes here</b>",style=stylePara)
    story.append(hcit)
    doc.build(story,myPages,myPages)   #myPages is defined

并且,为表格生成矩阵的代码

def generateData(sourceFile):
    #Header
    h1 = Paragraph('''<font color=white><b>Heading1</b></font>''', styleN)
    h2 = Paragraph('''<font color=white><b>Heading2</b></font>''', styleN)
    h3 = Paragraph('''<font color=white><b>Heading3</b></font>''', styleN)
    h4 = Paragraph('''<font color=white><b>Heading4</b></font>''', styleN)
    h5 = Paragraph('''<font color=white><b>Heading5</b></font>''', styleN)
    h6 = Paragraph('''<font color=white><b>Heading6</b></font>''', styleN)
#Texts
    data=[[h1,h2,h3,h4,h5,h6]]
    f=open(sourceFile,"r")
    for line in f:
        if line.startswith("#"):
            continue
        splitline=line[:-1].split("\t")
        col1 = Paragraph(splitline[0], styleN)
        col2 = Paragraph(splitline[1], styleN)
        col3 = Paragraph(splitline[3], styleN)
        col4 = Paragraph(splitline[4], styleN)
        col5 = Paragraph(splitline[5], styleN)
        col6 = Paragraph(splitline[6], styleN)
        data.append([col1,col2,col3,col4,col5,col6])
    f.close()
    return data

样式和页面布局已定义但未在此处显示。

但是当源文件较大时,脚本会变慢。我在stackoverflow问题中找到了一个类似案例的帖子,它正在创建段落而不是表格。我可以分块读取我的源文件,但是我现在想知道如何将每个表附加到第一个表。

问题:对于大小约为 1MB 甚至更大的查询文件,如何使其快速运行?使用块,如何打印单个表中的所有数据?还有什么其他更好的选择?

4

0 回答 0