我正在使用Matplotlib和Pycairo生成PDF报告(仍处于草图阶段)。我故意避免使用ReportLabs作为设计选项和Pycairo技能的练习。
目前,我正在使用plt.get_current_fig_manager().canvas
将图形作为栅格插入,但我想更改它,以便获得仅用于矢量的PDF以进行优质打印,并且可能不是那么大的文件大小。
我的工作代码如下:
# coding: utf-8
from matplotlib import pyplot as plt
import cairo
import Image, StringIO
import numpy
## HARDCODED DATA (debug only)
doc = {'canais': ('Vasto Medial', 'Vasto Lateral', 'Reto Femoral', 'Semi-Tendinoso'),
'pico': ((98, 130, 122, 108, 112, 116, 132, 132, 106, 110),
(107, 112, 108, 114, 110, 109, 119, 125, 107, 102),
(166, 190, 174, 186, 171, 159, 209, 190, 187, 164),
(11, 13, 11, 10, 12, 11, 12, 13, 10, 24)),
'integral': ((128, 209, 202, 170, 191, 197, 215, 227, 184, 218),
(139, 180, 179, 180, 187, 184, 194, 214, 186, 203),
(217, 316, 289, 292, 289, 270, 341, 326, 324, 327),
(15, 21, 18, 16, 20, 19, 20, 22, 17, 48))}
## INITIALIZING PDF (A4 SIZE)
paper_width = 210.
paper_height = 297.
margin = 15.
print_width = paper_width - margin*2
point_to_milimeter = 72/25.4
pdfname = "Relatorio Standard.pdf"
pdf = cairo.PDFSurface(pdfname , paper_width*point_to_milimeter,
paper_height*point_to_milimeter)
cr = cairo.Context(pdf)
cr.scale(point_to_milimeter, point_to_milimeter)
cr.translate(margin, margin)
cr.select_font_face("Sans")
# HEADER
headerheight = 40
headerbottom = 5
cr.rectangle(0, 0, print_width, headerheight)
cr.set_source_rgb(0.8,0.8,0.8)
cr.fill()
cr.translate(0, headerheight + headerbottom)
# TITULO DO EXAME
cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD)
cr.set_font_size(7)
tx = "Surface Electromyography"
base, wid, hei = cr.text_extents(tx)[1:4]
cr.move_to((print_width - wid)/2, hei)
cr.set_source_rgb(0,0,0)
cr.show_text(tx)
cr.translate(0,20)
## PLOTTING AND EXTRACTING RASTER IMAGE
figwid = 180
fighei = 100
fig = plt.figure(figsize=(figwid/25.4, fighei/25.4))
fig.set_facecolor('#FFFFFF')
plt.subplots_adjust(left=0.05, right=0.98, bottom=0.02, top=0.98, hspace=0.1)
r = numpy.arange(0.5,len(doc['pico']))
for n, seq in enumerate(doc['pico']):
#p = plt.subplot(4,1,n+1)
#plt.bar(numpy.arange(0.25,len(seq)), seq, width=0.5)
plt.plot(seq)
#plt.setp(p.get_xticklabels(), visible=False)
buf = StringIO.StringIO()
canvas = plt.get_current_fig_manager().canvas
canvas.draw()
im = Image.fromstring('RGB', canvas.get_width_height(),
canvas.tostring_rgb())
im.save(buf, 'PNG'); buf.seek(0)
#im.show()
## INSERTING IMAGE IN PDF
imagesurface = cairo.ImageSurface.create_from_png(buf)
cr.save()
#imagesize = 50
#cr.translate(imagesize, 0)
#factor = 1./numpy.pi
factor = 1./4
cr.scale(factor, factor)
cr.set_source_surface(imagesurface, 0, 0)
cr.paint()
cr.restore()
# Some reference rectangle (showing graph is not the target size, but whatever
cr.rectangle(0, 0, figwid, fighei)
cr.set_source_rgba(1,0,0,0.1)
cr.set_line_width(1)
cr.fill()
pdf.show_page()
问题是:我如何使用此脚本中的matplotlib来获取最终pdf中的矢量图,而不是光栅。
或换句话说:是否可以将Pycairo和Matplotlib中的矢量数据“混合”(写入)到同一PDF目标文件中?