将CSV文件写入PDF文档

3
我有一个 Python 脚本,可以解析 SQLite DB 文件中的数据并将其写入 .csv 文件。我希望将这些数据写入 PDF 格式的取证报告中。我已经能够创建一个带有标题、日期、案件编号和简短详情段落的模板 PDF。我想知道如何将 .csv 文件数据写入 PDF 中的表格中。如所示,我尝试通过使用 csv.reader 读取它后迭代遍历 .csv 文件。我可以将初始标题写入文件,但无法从 .csv 文件中提取数据并写入。有没有人可以指点我正确的方向。
# Script to generate a PDF report after data has been parsed into .csv file

# import statements
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import portrait
import csv

# PDF document layout
canvas = canvas.Canvas("H:\College Fourth Year\Development Project\Final Year Project 2018\Forensic Reports\SMS Report.pdf", pagesize=letter)

canvas.setLineWidth(.3)
canvas.setFont('Helvetica', 12)
canvas.drawString(30,750,'LYIT MOBILE FORENSICS DIVISION')
canvas.drawString(500,750,"Date: 12/02/2018")
canvas.line(500,747,595,747)
canvas.drawString(500,725,'Case Number:')
canvas.drawString(580,725,"10")
canvas.line(500,723,595,723)

# Introduction text
line1 = 'This forensic report on SMS data has been compiled by the forensic'
line2 = 'examiner in conclusion to the investigation into the RTA'
line3 = 'case which occured on 23/01/2018'
textObject = canvas.beginText(30, 700)
lines = [line1, line2, line3]
for line in lines:
    textObject.textLine(line)
canvas.drawText(textObject)

# File that must be written to report
data_file = 'H:\College Fourth Year\Development Project\Final Year Project 2018\ExtractedEvidence\smsInfo.csv'
c = canvas

# Function for importing data
def import_Data(data_file):
    smsInfo = csv.reader(open(data_file, "r"))
    for row in smsInfo:
        ID = row[0]
        Incoming_Number = row[1]
        Date_And_Time = row[2]
        Read = row[3]
        Sent_Replied = row[4]
        Body = row[5]
        Seen = [6]
        pdf_filename = 'SMS Data Report.pdf'
    generate_report(ID, Incoming_Number, Date_And_Time, Read, Sent_Replied, Body, Seen)

def generate_report(ID, Date_And_Time, Read, Sent_Replied, Body, Seen, pdf_filename):
    #c = canvas.Canvas(pdf_filename, pagesize=portrait(letter))



    import_Data(data_file)
canvas.save()


print("Forensic Report Generated!")

如果您在字符串中使用反斜杠(database = "H:\College Fourth Year\Development Project\Final Year Project 2018\mmssms.db"),则应该转义它们(\\)或使用原始字符串:database = r"H:\College Fourth Year\Development Project\Final Year Project 2018\mmssms.db",或者使用斜杠,在Windows上也可以。 - Michiel Overtoom
2
不想冒犯,但您是否尝试将数据库导出脚本与其他脚本结合使用?您可以像循环选择结果一样循环CSV文件的行。 - ChatterOne
我已经尝试过了,但我不知道我做错了什么。我的尝试在上面的编辑中。 - GreenCoder90
你的问题中没有说明出现了什么错误。 - Jongware
好的,我想我几乎解决了它,但是它报错说:canvas.save() AttributeError: 'module' object has no attribute 'save'。我的更新代码如上所示。 - GreenCoder90
你从generate_report内部调用import_Data,并从import_Data内部调用generate_report,这将导致无限循环,但实际上你并没有调用这两个函数中的任何一个。我认为你只是在猜测而不是真正尝试理解发生了什么。 - ChatterOne
1个回答

1
也许你可以尝试一些不同的方法。最近我需要使用来自csv文件的数据制作类似的PDF文件。希望这能对你有所帮助:
# import statements
import requests
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4, inch, landscape, legal, letter
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Image, Spacer, PageBreak, Table, TableStyle 
from reportlab.lib.styles import getSampleStyleSheet

import csv
import os

# Get de work directory 
cwd = os.getcwd() 

# Introduction text
line1 = 'This forensic report on SMS data has been compiled by the forensic'
line2 = 'examiner in conclusion to the investigation into the RTA'
line3 = 'case which occured on 23/01/2018'

#PDF document layout
table_style = TableStyle([('ALIGN',(1,1),(-2,-2),'RIGHT'),
                       ('TEXTCOLOR',(1,1),(-2,-2),colors.red),
                       ('VALIGN',(0,0),(0,-1),'TOP'),
                       ('TEXTCOLOR',(0,0),(0,-1),colors.blue),
                       ('ALIGN',(0,-1),(-1,-1),'CENTER'),
                       ('VALIGN',(0,-1),(-1,-1),'MIDDLE'),
                       ('TEXTCOLOR',(0,-1),(-1,-1),colors.green),
                       ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
                       ('BOX', (0,0), (-1,-1), 0.25, colors.black),
                       ])
styles = getSampleStyleSheet() 
styleNormal = styles['Normal']
styleHeading = styles['Heading1']
styleHeading2 = styles['Heading2'] 
styleHeading.alignment = 1 # centre text (TA_CENTRE) 

#Configure style and word wrap
s = getSampleStyleSheet()
s = s["BodyText"]
s.wordWrap = 'CJK'

# File that must be written to report
with open ('smsInfo.csv', 'rb') as csvfile:
    reader = csv.reader(csvfile)
    lista = list(reader)

headers = lista[0]

conteo = 1

for numRecord in range(1,len(lista)):

    record1 = lista[numRecord]

    data = list()
    emptyRecords = list()
    records = list()
    header = list()

    countRecords = 0

    for line in record1:

        if line == '':
            emptyRecords.append(line)           
        else:
            records.append(line)
            header.append(headers[countRecords])

            data.append([str(headers[countRecords]), str(line)])

        countRecords = countRecords + 1

    data2 = [[Paragraph(cell, s) for cell in row] for row in data]
    t = Table(data2)
    t.setStyle(table_style)

    elements = []

    # Name of file
    fileName = cwd + '\\' + 'SMS Data Report' + '-' + str(conteo) + '.pdf'

    conteo = conteo + 1

    archivo_pdf = SimpleDocTemplate(fileName, pagesize = letter, rightMargin = 40, leftMargin = 40, topMargin = 40, bottomMargin = 28)

    #Send the data and build the file
    elements.append(Paragraph(line1, styleNormal))
    elements.append(Paragraph(line2, styleNormal))
    elements.append(Paragraph(line3, styleNormal))
    elements.append(Spacer(inch, .25*inch))
    elements.append(t)

    archivo_pdf.build(elements)
    print 'Forensic Report Generated:', fileName

这段代码会生成类似于以下文件:

PDF报告


这对我帮助很大,谢谢。我想知道如何在表格下面写这个内容:“此短信数据取证报告是由鉴定人员编制的,作为对2018年1月23日发生的RTA案件调查的结论。” - GreenCoder90
您可以使用append添加行,例如:elements.append(Paragraph('此短信数据取证报告由取证人员编制', styleNormal))。请在以下行中编写:elements.append(t)。 - Luis Vargas
太棒了!谢谢你。我现在会接受你的答案 :) - GreenCoder90
太好了!我忘记提到你可以更改line1、line2或line3文本的样式。只需将元素styleNormal更改为sstyleHeading或styleHeading2即可。在行元素中,添加(Paragraph(line1, styleNormal))。 - Luis Vargas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接