Ir al contenido principal

Ralsina.Me — El sitio web de Roberto Alsina

Using vector images in reportlab

One of the big lim­i­ta­tions of re­port­lab is that it has no sup­port for vec­tor-based im­ages. You can't in­sert SVG, EPS or any oth­er vec­tor-based for­mat in your doc­u­ments.

Un­til now.

By hi­jack­ing an­oth­er app called uni­con­ver­tor, I have man­aged to in­sert as vec­tors SVG im­ages in a re­port­lab doc­u­men­t.

Here's the hack­ish code:

import sys,os
from app.io import load
from app.plugins import plugins
import app
from reportlab.platypus import *
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import inch

app.init_lib()
plugins.load_plugin_configuration()


class SVGImage(Flowable):
  def __init__(self,imgname):
    self.doc = load.load_drawing(imgname)
    for k in dir(self.doc):
      print k
    self.saver = plugins.find_export_plugin(plugins.guess_export_plugin(".pdf"))
    Flowable.__init__(self)

  def wrap(self,aW,aH):
    br=self.doc.BoundingRect()
    return br[2],br[3]

  def drawOn(self,canv,x,y,_sW=0):
    canv.translate(x,y)
    self.saver (self.doc,".ignoreme.pdf",options={'pdfgen_canvas':canv})
    os.unlink(".ignoreme.pdf")

styles = getSampleStyleSheet()
def go():
    doc = SimpleDocTemplate("phello.pdf")
    Story = [Spacer(1,2*inch)]
    style = styles["Normal"]
    p = SVGImage('warning.svg')
    Story.append(p)
    doc.build(Story)

go()

It has sev­er­al prob­lems (see where the sec­ond para­graph end­ed), but it does work.

To run it, you need a warn­ing.svg file (ed­it as need­ed) and you run it this way (re­plac­ing the path as prop­er for your se­tup):

PYTHONPATH=/usr/lib/python2.5/site-packages/uniconvertor/ python use_uniconv.py

In fac­t, this is not lim­it­ed to SVG files. You should be able to use the fol­low­ing for­mat­s:

  • Corel­­DRAW ver.7-X3,X4 (C­­DR/CDT/C­CX/C­­DRX/CMX)

  • Adobe Il­lus­­tra­­tor up to 9 ver. (AI post­script based)

  • Post­script (P­S)

  • En­­cap­­su­lat­ed Post­script (EP­S)

  • Com­put­er Graph­ics Metafile (CG­M)

  • Win­­dows Metafile (WM­F)

  • XFIG

  • Scal­able Vec­­tor Graph­ics (SVG)

  • Sken­­cil/S­ketch/sK1 (SK and SK1)

  • Acorn Draw (AF­F)


Contents © 2000-2024 Roberto Alsina