我正在尝试使用django中的Pisa库将我的html页面导出为pdf,这是我用来执行此操作的代码:
def fetch_resources(uri, rel):
path = os.path.join(settings.STATIC_ROOT, uri.replace(settings.STATIC_URL, ""))
return path
def write_pdf(template_src, context_dict):
template = get_template(template_src)
context = Context(context_dict)
html = template.render(context)
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")),dest = result, encoding='UTF-8', link_callback=fetch_resources)
if not pdf.err:
return http.HttpResponse(result.getvalue(), mimetype='application/pdf')
return http.HttpResponse('Sorry, no pdf! %s' % cgi.escape(html))
def article(request):
return write_pdf('Storehouse/ReceiptPrint-v2.html',{'pagesize':'A4'})
但是当我得到pdf输出时我有两个问题:首先,它不会渲染我的css文件而且我的所有样式都在pdf中丢失(我的css文件非常大,所以请不要建议有html文件中的样式)第二,它不理解指定的unicode(UTF-8),我的html页面是在Farsi中,但当它变成pdf时,它会变成一些无意义的正方形。
任何帮助都会受到很多赞赏!