【问题标题】:Writing a CSV file into a PDF document将 CSV 文件写入 PDF 文档
【发布时间】:2018-02-12 11:56:50
【问题描述】:

我有一个 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。
  • 不要粗鲁,但您是否真的尝试过将您的数据库导出脚本合并到其他脚本中?循环遍历选择结果的方式与循环遍历 CSV 文件的行的方式相同。
  • 我试过了,但我不知道我做错了什么。我的尝试是在上面的编辑中。
  • 你不会在你的问题中告诉你出了什么问题。
  • 好的,我想我几乎已经破解了它,但它给出了一个错误消息:canvas.save() AttributeError: 'module' object has no attribute 'save'。我更新的代码显示在上面的问题中。

标签: python csv pdf sqlite reportlab


【解决方案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

【讨论】:

  • 这对我帮助很大,谢谢。我想知道我怎么能把这个写在桌子下面?:“这份关于 SMS 数据的法医报告是由法医编制的”“审查员对 RTA 的调查得出结论”“2018 年 1 月 23 日发生的案件”
  • 您可以像这样使用 append 添加行:elements.append(Paragraph('此短信数据的取证报告已由取证编译', styleNormal))。写在下面的行 elements.append(t)
  • 太棒了!。谢谢你。我现在会接受你的回答。 :)
  • 太棒了!!。我忘了提到您可以更改 line1、line2 或 line3 文本的样式。只需通过 sstyleHeading 或 styleHeading2 更改元素 styleNormal。在行 elements.append(Paragraph(line1, styleNormal))
猜你喜欢
  • 2014-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-16
  • 2016-04-19
  • 2018-11-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多