django-xhtml2pdf的使用(加入图片,指定字体,设置样式)

本文介绍如何使用HTML生成带中文及图片的PDF文件,包括指定中文字体、处理图片路径及支持部分CSS样式的技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

新博客地址:http://muker.net/django-xhtml2pdf.html

这里仅仅讨论直接利用html生成pdf这种最常见也最简单的情况。

1、要利用html生成带中文的pdf要指定中文字体

即在要用的html中的style标签下要添加如下代码:

@font-face {
    font-family: simsun; src: url({{url}}); } 

上面指定了字体和字体路径。

2、生成包含图片的pdf

其实xhtml2pdf是支持图片的,但是很多时候并不能显示图片是因为没有给出正确的图片路径。
如上一步中的url,模板渲染结束后必须是绝对路径(如:F:\test)才能使字体的设置生效。
相应的,图片我们也需要为其指定绝对路径。
所以我们可以添加如下函数:

def fetch_resources(uri, rel):
    path = settings.BASE_DIR + uri
    return path 

函数功能是返回实际路径,如 uri为/static/123.jpg 则返回 F:\test/static/123.jpg(注意 \ 和 / 在这里的效果是一样的)
然后生成pdf的时候调用此函数:

pdf = pisa.CreatePDF(logohtml, result,link_callback=fetch_resources)

上面的语句的作用是将logohtml中的网页转为pdf存储到result中,网页中的路径通过fetch_resources处理。

3、设置样式

有时候网页转为pdf后样式发生了改变,这主要是因为xhtml2pdf并不是支持所有的CSS样式,其支持的样式如下:

background-color
border-bottom-color, border-bottom-style, border-bottom-width border-left-color, border-left-style, border-left-width border-right-color, border-right-style, border-right-width border-top-color, border-top-style, border-top-width colordisplay font-family, font-size, font-style, font-weight height line-height, list-style-type margin-bottom, margin-left, margin-right, margin-top padding-bottom, padding-left, padding-right, padding-top page-break-after, page-break-before size text-align, text-decoration, text-indent vertical-align white-space width zoom 

如果需要float等功能,可以考虑用text-align代替
或者从 这里 查看更高级的说明

转载于:https://www.cnblogs.com/muker715/p/4535967.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值