You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

使用xhtml2pdf生成PDF时CSS未生效问题求助

xhtml2pdf生成PDF时CSS样式完全不生效的排查与解决

我使用xhtml2pdf工具生成PDF文件,文件已经成功创建,但CSS样式完全未生效。我已经确认link_callback函数返回的路径是正确的(路径示例:/Users/mypc/project/project/static/css/lender_borrower.css),相关代码如下:

转换代码

html = template.render(context)
resultFile = open(filepath, "w+b")
pdf = pisa.CreatePDF(html.encode('utf-8'), dest=resultFile,encoding='utf-8', link_callback=link_callback)
def link_callback(uri, rel):
    sUrl = settings.STATIC_URL  # Typically /static/
    sRoot = settings.STATIC_ROOT
    mUrl = settings.MEDIA_URL  # Typically /static/media/
    mRoot = settings.MEDIA_ROOT  # Typically /home/userX/project_static/media/

    # convert URIs to absolute system paths
    if uri.startswith(mUrl):
        path = os.path.join(mRoot, uri.replace(mUrl, ""))
    elif uri.startswith(sUrl):
        path = os.path.join(sRoot, uri.replace(sUrl, ""))
    else:
        return uri  # handle absolute uri (ie: http://some.tld/foo.png)

    # make sure that file exists
    if not os.path.isfile(path):
        raise Exception(
            'media URI must start with %s or %s' % (sUrl, mUrl)
        )
    return path

CSS代码

#page_1 {position:relative; overflow: hidden;margin: 64px 0px 65px 0px;padding: 0px;border: none;}
#page_1 #p1dimg1 {position:absolute;top:0px;left:20%;z-index:-1;width:600px;height:870px;}
#page_1 #p1dimg1 #p1img1 {width:600px;height:870px;}
#page_2 {position:relative; overflow: hidden;padding-left: 100px;border: none;height: 854px;}
#page_2 #p2dimg1 {position:absolute;left:27%;z-index:-1;width:490px;height:669px;}
#page_2 #p2dimg1 #p2img1 {width:490px;height:669px;}

可能的原因及解决方案

xhtml2pdf基于ReportLab,对CSS的支持并不是完全兼容标准CSS,很多现代CSS属性或者选择器可能无法被解析,结合你的情况,我整理了几个常见的排查方向:

  • 检查CSS选择器与属性的兼容性
    xhtml2pdf对CSS的支持有限,比如z-index: -1这类层叠属性基本不被支持;百分比单位(比如left:20%)的解析逻辑也和浏览器差异很大,建议先换成固定像素值测试。另外,避免使用嵌套ID选择器(比如#page_1 #p1dimg1),简化为单个ID或类选择器,因为它对复杂选择器的解析能力很弱。

  • 确认CSS文件是否被正确加载
    虽然你说link_callback返回路径正确,但可以在函数里加日志打印实际返回的路径,确认文件确实存在且程序有读取权限。同时要注意:xhtml2pdf只支持<link rel="stylesheet">标签引入CSS,不支持<style>内嵌(部分版本不稳定)和@import引入方式。

  • 调整PDF生成的编码与渲染方式
    尝试先把HTML内容写入临时文件,再读取文件生成PDF,避免字符串编码问题导致CSS解析失败:

    with open("temp.html", "w", encoding="utf-8") as f:
        f.write(html)
    with open(filepath, "w+b") as resultFile:
        pdf = pisa.CreatePDF(open("temp.html", "r", encoding="utf-8"), dest=resultFile, link_callback=link_callback)
    
  • 检查HTML结构的合规性
    xhtml2pdf要求HTML必须是严格的XHTML格式:所有标签必须闭合,属性必须用双引号包裹,不能有未闭合的标签,否则可能导致CSS无法绑定到对应元素上。

  • 测试简化的CSS和HTML
    先写一个极简测试案例:比如给一个<div>设置background-color: red; width: 100px; height:100px;,看是否能生效。如果生效,再逐步添加原有CSS,定位到具体是哪个属性或选择器导致的问题。

内容的提问来源于stack exchange,提问作者Prashant Jha

火山引擎 最新活动