Search code examples
pythondjangoreportlab

Draw images with canvas and use SimpleDocTemplate


I'm writing pdfs with reportlab inside a django view, they are very simple, the header, the contents and the footer.

I'm using SimpleDocTemplate wich fits very well, to draw tables in the contents, the footer and the header are drwan using:

build([data], onFirstPage=drawPageFrame, onLaterPages=drawPageFrame).

My question is, How can I draw a image like using Canvas.drawImage(...)? I need a "floating" image... positioned over the text where I want, and with SimpleDocTemplate I don't have a Canvas object to do this.

Searching I have found this:

The platypus layout stuff uses flowables. Packers normally set the attribute canv onto each flowable when it is being wrapped, split or drawn ie around the wrap, split and draw methods. Inside those methods you have access to the canvas using the canv attribute of self.

How can this be used?

Ummmm, more stuff to test:

flowables.Macro
flowables.CallerMacro
# -*- coding: utf-8 -*-
from reportlab.lib.pagesizes import A4, landscape, portrait
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import Table, Flowable, SimpleDocTemplate, Paragraph, Spacer, Image
from reportlab.lib import randomtext
from reportlab import platypus

import os,random

styles = getSampleStyleSheet()
path = os.path.realpath(os.path.dirname(__file__))

def drawPageFrame(canvas, doc):
    canvas.saveState()
    canvas.drawImage(path+"/ujiPDF.jpg",50,50,57,57)
    canvas.restoreState()

doc = SimpleDocTemplate("salida.pdf",pagesize=A4)

elementos = []

com = 'canvas.drawImage("'+path+'/ujiPDF.jpg",100,100,57,57)'
print com
elementos.append(platypus.flowables.Macro('canvas.saveState()'))
print platypus.flowables.Macro(com)
elementos.append(platypus.flowables.Macro(com))
elementos.append(platypus.flowables.Macro('canvas.restoreState()'))

para = Paragraph(randomtext.randomText(randomtext.PYTHON,20), styles["Normal"])
elementos.append(para)

doc.build(elementos,onFirstPage=drawPageFrame, onLaterPages=drawPageFrame)

This is the Macro approach...clean exit but without the second image.


Solution

  • Your best option is to create a subclass of SimpleDocTemplate or BaseDocTemplate. In the build method you will have access to the canvas. If you want to tap into everything that SimpleDocTemplate does, you might try copying it directly from site-packages/reportlab/platypus/doctemplate.py.