首页 文章

如何使用ReportLab将图表添加到PDF

提问于
浏览
0

我有一个python项目,它使用ReportLab从Python中的Web应用程序中的某些数据生成PDF . 它正在构建一个大的文本字符串,然后将其添加到画布,然后从画布生成PDF . 我被要求在PDF中间添加折线图 . 我已经找到了很多关于如何在ReportLab中将图表直接转换为PDF的信息,例如:

Adding Graph to Reportlab PDF

但没有关于如何将该图表作为其他格式化内容的一部分添加到PDF中 . 这是我正在使用的代码:

class GenPDF(R):
@tornado.web.authenticated
def get(self):
    """takes text and generates PDF"""
    msg = gen_report(subject, test_name)

    filename = "filename.txt"
    self.set_header("Content-Type", 'application/pdf; charset="utf-8"')
    self.set_header("Content-Disposition", "attachment; filename=%s.pdf" %filename)                  
    io = StringIO.StringIO()
    c = canvas.Canvas(io, pagesize=A4)

    imagem = canvas.ImageReader(StringIO.StringIO(open('logo.jpeg', 'rb').read()))
    c.drawImage(imagem, 430, 688, 100, 100) # Draw it in the bottom left, 2 inches high and 2 inches wide

    text = c.beginText()
    text.setTextOrigin(100, 700)
    text.setFont("Times-Roman", 16)
    text.textLine("Test Report")
    text.setFont("Times-Roman", 12)
    text.textLines(msg)
    text.textLines(CLASS_MAP[test_name]['blurb'])
        text.textLine("_____________________________________________________________________________")
    text.textLines(CLASS_MAP[test_name]['scale'])
        text.textLine("_____________________________________________________________________________")
    text.setFont("Times-Roman", 8)

    text.textLines(DISCLAIMER)
    c.drawText(text)


    c.showPage()
    c.save()

    pdf=io.getvalue()
    io.close() 
    self.write(pdf)

在这里我添加代码来添加图表?我尝试将其添加为绘图但似乎无法弄清楚我可以将绘图添加到画布或pdf本身 .

1 回答

  • 0

    您可以在页面上操纵图表的大小和位置,如下所示:

    drawing = Drawing(350, 190)
    lc = HorizontalLineChart()
    lc.x = 10
    lc.y = 10
    lc.height = 150
    lc.width = 330
    ...
    drawing.hAlign = 'CENTER'
    drawing.add(lc)
    

相关问题