<p>我不知道Weasyprint,但我使用的是<a href="https://pypi.python.org/pypi/pisa/3.0.33" rel="nofollow noreferrer">Pisa</a>,它可以很好地将图片转换成PDF输出。</p>
<p>例如:</p>
<pre><code>def PDFGeneration(request) :
var1 = Table1.objects.last()
var2 = Table2.objects.last()
data = {"key1" : variable1, "key2" : variable2}
html = get_template('My_template_raw.html').render(data)
result = StringIO()
with open(path, "w+b") as file :
pdf = pisa.pisaDocument(StringIO(html), file, link_callback=link_callback)
file.close()
image_data = open(path, "rb").read()
return HttpResponse(image_data, content_type="application/pdf")
return render(request, 'HTML template', context)
</code></pre>
<p>以及</p>
<pre><code>def link_callback(uri, rel):
if uri.find('chart.apis.google.com') != -1:
return uri
return os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))
</code></pre>
<p>我的PDF是从一个.html文件生成的,我的图片如下:</p>
<pre><code><html>
<head>
{% load staticfiles %}
{% load static %}
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="{% static 'css/MyFile.css' %}"/>
<style>
body {
font-family: Courier New, Courier, monospace;
text-align: justify;
list-style-type: none;
}
</style>
</head>
<body>
<img src="{{MEDIA_ROOT}}Logo/logo.jpeg" width="250" height="66"/>
<br></br>
...
</code></pre>