django将html中的图像和文本导出为pdf

时间:2012-02-13 12:46:41

标签: django django-views pisa

我在将html文件中的图像导出为pdf时遇到问题,类似的解决方案存在here

正在服务器上正确呈现html。我通过在网址上交叉检查来验证它。

但是在尝试下载/渲染pdf时**我得到一个pdf但是它是空白的,它也说明了views.py中下载函数第三行的错误

这是我试过的:

html文件:

<html>
<head>
<link href="{{ STATIC_URL }}css/certificate.css" rel="stylesheet"
  type="text/css" />
</head> 
<body>
<div class="certificate_container">
    <div class="statictext">
        <p>{{ name }}</p>
    </div>
</div>
</body>
<html>

css文件:

body{margin:0px; padding:0px;}
.certificate_container{ width:792px; height:612px; background:url("../images/certificate.gif") no-repeat;}
.statictext{width:400px; margin:0px auto; padding-top:240px; height:30px; text-align:center; font:bold 14px Arial, Helvetica, sans-serif; color:#333;}

views.py:

#relevant imports
from reportlab.pdfgen import canvas
import xhtml2pdf.pisa as pisa
import cStringIO as StringIO

def download(request):
    html = render_to_string("certificate.html", { 'pagesize' : 'A4', }, context_instance=RequestContext(request))
    result = StringIO.StringIO()
    pdf = pisa.pisaDocument(StringIO.StringIO(), dest=result, link_callback=fetch_resources )
    if not pdf.err:
        return HttpResponse(result.getvalue(), mimetype='application/pdf')
    return HttpResponse('Gremlins ate your pdf! %s' % cgi.escape(html))

def fetch_resources(uri, rel):
    path = os.path.join(settings.STATIC_ROOT, uri.replace(settings.STATIC_URL, ""))
    return path


def home(request):
    return render(request, 'certificate.html', {'name':'user1'} )

网址已得到妥善处理。

1 个答案:

答案 0 :(得分:0)

我后来发现,使用上面的技术堆栈无法实现,因此我尝试获取模板图像并使用PIL根据上下文修改它。这很有效。