将CSV文件写入PDF文档

时间:2018-02-12 11:56:50

标签: python csv pdf sqlite reportlab

我有一个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!")

1 个答案:

答案 0 :(得分: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 report