python将html存为pdf_使用Python将HTML转换为PDF

I am trying to convert HTML into a PDF document in Django and haven't been successful.

I have tried using wkhtmltopdf 0.9.9, however Apache throws an error that wkhtmltopdf cannot connect to server. When I use wkhtmltopdf directly, it runs perfectly fine and converts the HTML into a PDF document.

I have also tried using unoconv, however the rendered PDF file doesn't have any CSS applied to it. I have also tried using xhtml2pdf. Again I am facing same issue; the rendered PDF file doesn't have any CSS styling applied. I have spent the better part of today and last night trying to solve this issue and I'm still no closer to solving the problem.

Let me know if you need any more information

解决方案

Configuring Pisa for Django shouldn't be too hard.

There are really several examples on the net that show you how to do it and

explain how to link to external resources in your templates:

In your case you should try the link-callback-function mentioned in the first blog post:

def fetch_resources(uri, rel):

"""

Callback to allow pisa/reportlab to retrieve Images,Stylesheets, etc.

`uri` is the href attribute from the html link element.

`rel` gives a relative path, but it's not used here.

"""

path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))

return path

For newer Django-Version you probably should use STATIC_ROOT instead of MEDIA_ROOT

Then use fetch resources accordingly in your render-method:

pdf = pisa.pisaDocument(StringIO.StringIO(

html.encode("UTF-8")),

result,

link_callback=fetch_resources,

encoding="utf-8")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值