简体   繁体   中英

How to add a chart to a PDF using ReportLab

I've a python project that generates a PDF from some data in a web app in Python using ReportLab. It's building a large text string and then adding that to a canvas, and then generating a PDF from the canvas. I've been asked to add a line chart in the middle of the PDF. I've found a lot of info out there on how to turn a chart directly into a PDF in ReportLab, for example this:

Adding Graph to Reportlab PDF

But nothing about how to add that chart to a PDF as part of other formatted content. Here's the code I'm working with:

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)

Where in this do I add code to add the chart? I tried adding it as a drawing but can't seem to figure out where I then can add the drawing to the canvas, or to the pdf itself.

You can manipulate size and position your chart on page like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM