xhtml2pdf中文屏幕溢出问题

发布于:2025-06-13 ⋅ 阅读:(17) ⋅ 点赞:(0)

背景

使用xhtml2pdf转pdf的时候发现中文超长会出现屏幕溢出的问题
在这里插入图片描述

解决过程

官网

首先去官网看看有没有想关的解决方案:官方文档
但是看了一遍发现并没有相关描述,可能是bug。

思考

测试了英文是没问题的,于是思考,是否是由于中文分隔符无法识别的问题。
于是上测试代码测试,发现xhtml2pdf 无法使用标点符号进行分隔,只能用空格分隔。


# 测试边距
from xhtml2pdf import pisa


def html_to_pdf(html: str, output_path: str):
    full_html = """
<html>
<head>
<style>
    table { -pdf-keep-with-next: true; }
    p { margin: 0; -pdf-keep-with-next: true; }
</style>
</head>

<body>
    <p>Keepthesesetsof linesKeep these sets of linesKeep these sets of linesKeep these sets of linesKeep these sets of linesKeep these sets of linesKeep these sets of linesKeep these sets of linesKeep these sets of linesKeep these sets of lines</p>
    <p>随着硬件技术的发展和算法的不断进步,大模型的应用前景非常广阔。在未来,大模型有望在更多的领域得到应用,如自动驾驶、医疗诊断等。同时,研究人员也在探索如何降低大模型的计算资源需求,提高其训练效率,以及如何使其更加易于解释和调试。</p>
    <p>may appear in a different frame</p>
    <p class="separator">&nbsp;<p>
</body>
</html>    
"""
    with open(output_path, "wb") as f:
        pisa.CreatePDF(full_html, dest=f, encoding="UTF-8")
    print(f"PDF saved to: {output_path}")

if __name__ == "__main__":

    html_to_pdf("html", "output/output.pdf")
    # html_to_docx(html, "output/output.docx")

解决办法

提前处理html内容(推荐)

为每一个标点符号后面添加一个空格作为分隔符

# 增加分割符、防止屏幕溢出
chinese_punctuation = r'[,。!?;:、]'
clean_html = re.sub(f"({chinese_punctuation})(?![\s\n<])", r"\1 ", html_content)

源码解决

这个源码太复杂了,修改难度过高,不推荐