django将图像和文本导出为html格式为pdf
问题描述:
我在导出html文件中的图像时遇到了问题,因为pdf文件存在类似的解决方案here。django将图像和文本导出为html格式为pdf
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'})
该网址已妥善保管。
答
我后来发现,使用上述技术堆栈无法实现,因此我尝试获取模板图像并使用PIL根据上下文对其进行修改。这工作。
对此有帮助吗? http://stackoverflow.com/questions/4678723/django-pdf-question-with-pisa – jperelli 2012-02-13 18:38:19