使用Python将HTML转换为PDF [英] Convert HTML into PDF using Python

查看:501
本文介绍了使用Python将HTML转换为PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我尝试使用wkhtmltopdf 0.9.9,但是Apache抛出一个wkhtmltopdf无法连接到服务器的错误。当我直接使用wkhtmltopdf时,它运行得很好,并将HTML转换为PDF文档。



我也尝试使用unoconv,但是渲染的PDF文件没有任何CSS应用于它。我也试过使用xhtml2pdf。我再次面对同样的问题;渲染的PDF文件没有应用任何CSS样式。我已经花了今天和昨晚的更好的一部分来解决这个问题,我还没有更接近解决问题。



如果你需要任何的话,让我知道更多信息

解决方案

为Django配置比萨不应该是太难了



真的有几个例子网络,告诉你如何做,
解释如何链接到您的模板中的外部资源:





在您的情况下,您应该尝试第一篇博文中提到的link-callback-function:

  def fetch_resources (uri,rel):

回调允许比萨/ reportlab检索图像,样式表等
`uri`是html链接元素的href属性。
`rel`给出一个相对路径,但这里不用。


path = os.path.join(settings.MEDIA_ROOT,uri.replace(settings.MEDIA_URL,))
返回路径

对于较新的Django版本,您可能应该使用 STATIC_ROOT 而不是 MEDIA_ROOT



然后在渲染中使用 fetch资源方法:

  pdf = pisa.pisaDocument(StringIO.StringIO(
html.encode(UTF-8) )
result,
link_callback = fetch_resources,
encoding =utf-8)


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")

这篇关于使用Python将HTML转换为PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆