回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我在django视图中使用reportlab编写pdf,它们非常简单,包括页眉、内容和页脚。</p>
<p>我使用的SimpleDocTemplate wich非常适合,要在内容中绘制表格,页脚和页眉是drwan使用的:</p>
<pre><code>build([data], onFirstPage=drawPageFrame, onLaterPages=drawPageFrame).
</code></pre>
<p>我的问题是,我怎样才能像使用Canvas.draw image(…)那样绘制图像?我需要一个“浮动”图像。。。放置在我想要的文本上,并且使用SimpleDocTemplate,我没有画布对象来执行此操作。</p>
<p>搜索我找到了这个:</p>
<blockquote>
<p>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.</p>
</blockquote>
<p>这个怎么用?</p>
<p>嗯,还有更多要测试的东西:</p>
<pre><code>flowables.Macro
flowables.CallerMacro
</code></pre>
<pre>
# -*- 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.<a href="https://www.cnpython.com/list/append" class="inner-link">append</a>(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)
</pre>
<p>这是一个宏方法…干净的出口,但没有第二个图像。</p>