【问题标题】:combine two charts into the single PDF using ReportLab?使用 ReportLab 将两个图表合并到一个 PDF 中?
【发布时间】:2013-11-30 08:16:29
【问题描述】:

我正在使用 Django 和 Reportlabs 生成 PDF 格式的报告。我指的是this tutorial

我读了this threadthis thread 也说使用canv.showpage() 然后我将能够在1 个pdf 中合并2 个图表,但我仍然只得到代码中第二个图表,就我而言,只有折线图。

如何在 1 个 pdf 中保存 2 个图表?

这是我的代码。

import barchart
import linechart
from django.http import HttpResponse
from reportlab.graphics.shapes import Drawing
from reportlab.graphics.charts.barcharts import VerticalBarChart
from reportlab.graphics import renderPDF    
from reportlab.pdfgen import canvas


def generate_report(request):


    #instantiate a drawing object
    canv = canvas.Canvas('output.pdf')#,pagesize=LETTER) 
    canv.setPageCompression(0)  
    d = barchart.MyBarChartDrawing()

    #extract the request params of interest.
    #I suggest having a default for everything.
    if 'height' in request:
        d.height = int(request['height'])
    if 'width' in request:
        d.width = int(request['width'])

    if 'numbers' in request:
        strNumbers = request['numbers']
        numbers = map(int, strNumbers.split(','))    
        d.chart.data = [numbers]   #bar charts take a list-of-lists for data

    if 'title' in request:
        d.title.text = request['title']


    #get a GIF (or PNG, JPG, or whatever)
    binaryStuff = d.asString('pdf')

    #binaryStuff.save()
    #return HttpResponse(binaryStuff, 'image/pdf')
    #instantiate a drawing object
    canv.showPage()
    a = linechart.MyLineChartDrawing()

    #extract the request params of interest.
    #I suggest having a default for everything.


    a.height = 300
    a.chart.height = 300


    a.width = 300
    a.chart.width = 300

    a.title._text = request.session.get('Some custom title')



    a.XLabel._text = request.session.get('X Axis Labell')
    a.YLabel._text = request.session.get('Y Axis Label')

    a.chart.data = [((1,1), (2,2), (2.5,1), (3,3), (4,5)),((1,2), (2,3), (2.5,2), (3.5,5), (4,6))]



    labels =  ["Label One","Label Two"]
    if labels:
        # set colors in the legend
        a.Legend.colorNamePairs = []
        for cnt,label in enumerate(labels):
            a.Legend.colorNamePairs.append((a.chart.lines[cnt].strokeColor,label))


    #get a GIF (or PNG, JPG, or whatever)
    binaryStuff1 = a.asString('pdf')
    canv.showPage()
    return HttpResponse(binaryStuff, 'pdf')

条形图和折线图代码与this site 相同。

如何只保存在一个 pdf 文件中?

【问题讨论】:

  • 我假设binaryStuff1 = a.asString('pdf') 实际上应该是binaryStuff = a.asString('pdf')

标签: python django reportlab


【解决方案1】:

根据提供的代码,您只能获得折线图,因为您只是将 BinaryStuff 传递给响应(查看代码的最后 3 行)。

尝试将图表创建为图像,将图像绘制到画布上,然后将画布以 PDF 格式返回。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-04
  • 1970-01-01
  • 2014-11-16
  • 1970-01-01
  • 2018-10-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多